feat: Explorer-Grundfunktionen, Suche, Konflikte, Archive und Unraid-Infos

- Neuer Ordner, Tastaturbedienung, Kopieren/Ausschneiden/Einfügen, Verlauf
  (Zurück/Vorwärts), anklickbare Pfadleiste, Statusleiste.
- Filter für den aktuellen Ordner und rekursive Suche als Hintergrund-Job.
- Konfliktdialog beim Kopieren/Verschieben (Ersetzen, Beide behalten,
  Überspringen), Kopien landen erst nach Erfolg am Ziel.
- Jobs mit Byte-Fortschritt, Geschwindigkeit, Restzeit und Abbrechen.
- Deutlicher Löschdialog; kein Papierkorb, wie in Unraid üblich.
- Vorschaubilder ohne Cache-Dateien, Favoriten, Nebeneinander-Ansicht.
- ZIP erstellen, ZIP/TAR entpacken mit Zip-Slip-Schutz.
- Prüfsummen, Dateivergleich, Unraid-Rechte reparieren, physischer
  Disk-/Pool-Ort und freier Speicher.
- PHP-Integrationstests gegen die echte Plugin-API (tests/php).
- Paket 2026.11.21.r003.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Mikei386andClaude Opus 5.5 committed 2026-11-21 13:17:02 +01:00
1 parent 0bf6eae6d8
commit 17cb65bd64
16 files changed
+2697 -219

No files matched your search

@@ -3,36 +3,97 @@
const UNAV_DEFAULT_ROOT = '/mnt/user';
const UNAV_JOB_DIR = '/tmp/u-navigator/jobs';
const UNAV_SETTINGS_FILE = '/boot/config/plugins/u-navigator/settings.json';
const UNAV_MAX_FAVORITES = 50;
function unav_settings_file(): string {
return getenv('U_NAV_SETTINGS_FILE') ?: UNAV_SETTINGS_FILE;
}
function unav_job_base_dir(): string {
return getenv('U_NAV_JOB_DIR') ?: UNAV_JOB_DIR;
}
// Unraid mount base (/mnt): disks, pools and the user share view live below it.
function unav_mnt_dir(): string {
return rtrim(getenv('U_NAV_MNT') ?: '/mnt', '/');
}
function unav_settings(): array {
$defaults = [
'readOnly' => true,
'debug' => false,
'thumbnails' => true,
'favorites' => [],
];
if (!is_file(UNAV_SETTINGS_FILE)) {
$file = unav_settings_file();
if (!is_file($file)) {
return $defaults;
}
$settings = json_decode(file_get_contents(UNAV_SETTINGS_FILE) ?: '{}', true);
$settings = json_decode(file_get_contents($file) ?: '{}', true);
if (!is_array($settings)) {
return $defaults;
}
return array_merge($defaults, [
'readOnly' => filter_var($settings['readOnly'] ?? $defaults['readOnly'], FILTER_VALIDATE_BOOLEAN),
'debug' => filter_var($settings['debug'] ?? $defaults['debug'], FILTER_VALIDATE_BOOLEAN),
'thumbnails' => filter_var($settings['thumbnails'] ?? $defaults['thumbnails'], FILTER_VALIDATE_BOOLEAN),
'favorites' => unav_clean_favorites($settings['favorites'] ?? [], false),
]);
}
// Favorites are plain strings in settings.json; on write they must resolve to folders inside a root.
function unav_clean_favorites($favorites, bool $verify): array {
if (is_string($favorites)) {
$favorites = json_decode($favorites, true);
}
if (!is_array($favorites)) {
return [];
}
$clean = [];
foreach ($favorites as $favorite) {
if (!is_string($favorite) || $favorite === '' || strlen($favorite) > 4096 || str_contains($favorite, "\0")) {
continue;
}
if ($verify) {
$real = realpath($favorite);
if ($real === false || !is_dir($real) || !unav_is_in_any_root($real)) {
continue;
}
$favorite = $real;
}
$clean[$favorite] = true;
if (count($clean) >= UNAV_MAX_FAVORITES) {
break;
}
}
return array_keys($clean);
}
function unav_is_in_any_root(string $real): bool {
foreach (unav_roots() as $root) {
if (unav_is_inside($real, $root['path'])) {
return true;
}
}
return false;
}
function unav_settings_write(array $settings): array {
$current = unav_settings();
$next = [
'readOnly' => filter_var($settings['readOnly'] ?? $current['readOnly'], FILTER_VALIDATE_BOOLEAN),
'debug' => filter_var($settings['debug'] ?? $current['debug'], FILTER_VALIDATE_BOOLEAN),
'thumbnails' => filter_var($settings['thumbnails'] ?? $current['thumbnails'], FILTER_VALIDATE_BOOLEAN),
'favorites' => array_key_exists('favorites', $settings)
? unav_clean_favorites($settings['favorites'], true)
: $current['favorites'],
];
$dir = dirname(UNAV_SETTINGS_FILE);
$file = unav_settings_file();
$dir = dirname($file);
if (!is_dir($dir) && !mkdir($dir, 0777, true) && !is_dir($dir)) {
unav_error(500, 'Could not create settings directory');
}
file_put_contents(UNAV_SETTINGS_FILE, json_encode($next, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT), LOCK_EX);
file_put_contents($file, json_encode($next, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT), LOCK_EX);
return $next;
}
@@ -255,12 +316,13 @@ function unav_permission_options(array $data): array {
}
function unav_job_dir(): string {
if (!is_dir(UNAV_JOB_DIR) && !mkdir(UNAV_JOB_DIR, 0700, true) && !is_dir(UNAV_JOB_DIR)) {
$dir = unav_job_base_dir();
if (!is_dir($dir) && !mkdir($dir, 0700, true) && !is_dir($dir)) {
unav_error(500, 'Could not create job directory');
}
// Job files drive a root worker: keep them private, also for directories created by older versions.
@chmod(UNAV_JOB_DIR, 0700);
return UNAV_JOB_DIR;
@chmod($dir, 0700);
return $dir;
}
function unav_job_path(string $id): string {
@@ -287,3 +349,47 @@ function unav_job_write(array $job): void {
$job['updatedAt'] = date(DATE_ATOM);
file_put_contents(unav_job_path($id), json_encode($job, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT), LOCK_EX);
}
// Cancellation uses a separate marker file so the worker never overwrites the request.
function unav_job_cancel_path(string $id): string {
return preg_replace('/\\.json$/', '.cancel', unav_job_path($id));
}
function unav_job_cancel_requested(string $id): bool {
clearstatcache(true, unav_job_cancel_path($id));
return is_file(unav_job_cancel_path($id));
}
function unav_valid_name(string $name): bool {
return $name !== '' && $name !== '.' && $name !== '..' && strlen($name) <= 255
&& !str_contains($name, '/') && !str_contains($name, "\0");
}
// "Datei.txt" -> "Datei (2).txt"; directories and dotfiles keep their full name as stem.
function unav_unique_path(string $path): string {
if (!file_exists($path) && !is_link($path)) {
return $path;
}
$dir = dirname($path);
$name = basename($path);
$dot = strrpos($name, '.');
$isDir = is_dir($path);
$stem = ($dot === false || $dot === 0 || $isDir) ? $name : substr($name, 0, $dot);
$ext = ($dot === false || $dot === 0 || $isDir) ? '' : substr($name, $dot);
// "Datei (2).txt" continues with "Datei (3).txt" instead of "Datei (2) (2).txt".
$stem = preg_replace('/ \(\d+\)$/', '', $stem);
for ($i = 2; $i < 10000; $i++) {
$candidate = $dir . '/' . $stem . ' (' . $i . ')' . $ext;
if (!file_exists($candidate) && !is_link($candidate)) {
return $candidate;
}
}
unav_error(409, 'No free destination name found');
}
// Matches the Unraid "New Permissions" tool: nobody:users, dirs 0777, files 0666.
function unav_unraid_permissions(string $path, bool $isDir): void {
@chown($path, 'nobody');
@chgrp($path, 'users');
@chmod($path, $isDir ? 0777 : 0666);
}
@@ -1,19 +1,20 @@
<?php
require_once __DIR__ . '/common.php';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$data = unav_request_data();
$settings = unav_settings_write($data);
unav_json([
'readOnly' => $settings['readOnly'],
function unav_config_payload(array $settings): array {
return [
'readOnly' => unav_read_only(),
'debug' => $settings['debug'],
'thumbnails' => $settings['thumbnails'],
'favorites' => $settings['favorites'],
'roots' => unav_roots(),
]);
'thumbnailSupport' => function_exists('imagecreatefromstring'),
'archiveSupport' => class_exists('ZipArchive'),
];
}
$settings = unav_settings();
unav_json([
'readOnly' => unav_read_only(),
'debug' => $settings['debug'],
'roots' => unav_roots(),
]);
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
unav_json(unav_config_payload(unav_settings_write(unav_request_data())));
}
unav_json(unav_config_payload(unav_settings()));
@@ -1,55 +1,154 @@
<?php
require_once __DIR__ . '/common.php';
const UNAV_JOB_ACTIONS = ['move', 'copy', 'delete', 'size', 'permissions', 'fixperms', 'search', 'checksum', 'compare', 'extract', 'compress'];
const UNAV_ARCHIVE_PATTERN = '/\.(zip|tar|tar\.gz|tgz|tar\.bz2|tbz2|tar\.xz|txz)$/i';
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
unav_json(unav_job_read($_GET['id'] ?? ''));
}
$action = $_GET['action'] ?? '';
if (!in_array($action, ['move', 'copy', 'delete', 'size', 'permissions'], true)) {
if ($action === 'cancel') {
$data = unav_request_data();
$job = unav_job_read((string)($data['id'] ?? ''));
if (in_array($job['status'], ['queued', 'running'], true)) {
touch(unav_job_cancel_path($job['id']));
$job['status'] = 'cancel_requested';
$job['message'] = 'Wird abgebrochen';
}
unav_json($job);
}
if (!in_array($action, UNAV_JOB_ACTIONS, true)) {
unav_error(404, 'Unknown job action');
}
$data = unav_request_data();
$source = unav_existing_path($data['source'] ?? null);
$destination = null;
$permissions = null;
if (in_array($action, ['move', 'delete', 'permissions'], true)) {
unav_assert_not_root($source['path']);
$job = [
'type' => $action,
'source' => null,
'sources' => null,
'destination' => null,
'permissions' => null,
'conflict' => 'fail',
'query' => null,
'target' => null,
];
if ($action === 'compress') {
unav_assert_writable();
$sources = json_decode((string)($data['sources'] ?? '[]'), true);
if (!is_array($sources) || !$sources || count($sources) > 1000) {
unav_error(400, 'Missing sources');
}
$job['sources'] = array_map(fn($source) => unav_existing_path(is_string($source) ? $source : null)['path'], $sources);
$job['source'] = $job['sources'][0];
$destination = unav_destination_path($data['destination'] ?? null)['path'];
if (!preg_match('/\.zip$/i', $destination)) {
unav_error(400, 'Archive name must end with .zip');
}
$job['destination'] = unav_unique_path($destination);
} else {
$source = unav_existing_path($data['source'] ?? null);
$job['source'] = $source['path'];
}
if (in_array($action, ['move', 'copy'], true)) {
unav_assert_writable();
$destination = unav_destination_path($data['destination'] ?? null);
unav_guard_destination($source['path'], $destination['path']);
} elseif ($action === 'delete') {
unav_assert_writable();
} elseif ($action === 'permissions') {
unav_assert_writable();
$permissions = unav_permission_options($data);
if (in_array($action, ['move', 'delete', 'permissions', 'fixperms'], true)) {
unav_assert_not_root($job['source']);
}
switch ($action) {
case 'move':
case 'copy':
unav_assert_writable();
$destination = unav_destination_path($data['destination'] ?? null)['path'];
$conflict = (string)($data['conflict'] ?? 'fail');
if (!in_array($conflict, ['fail', 'overwrite', 'rename'], true)) {
unav_error(400, 'Invalid conflict mode');
}
$exists = file_exists($destination) || is_link($destination);
if ($exists && $conflict === 'rename') {
$destination = unav_unique_path($destination);
} elseif ($exists && $conflict === 'overwrite') {
unav_assert_not_root($destination);
if (unav_is_inside($job['source'], $destination)) {
unav_error(400, 'Destination cannot contain the source');
}
}
if (!$exists || $conflict !== 'overwrite') {
unav_guard_destination($job['source'], $destination);
} elseif (is_dir($job['source']) && str_starts_with(rtrim($destination, '/') . '/', rtrim($job['source'], '/') . '/')) {
unav_error(400, 'Destination cannot be inside source');
}
$job['destination'] = $destination;
$job['conflict'] = $exists ? $conflict : 'fail';
break;
case 'delete':
unav_assert_writable();
break;
case 'permissions':
unav_assert_writable();
$job['permissions'] = unav_permission_options($data);
break;
case 'fixperms':
unav_assert_writable();
break;
case 'search':
if (!is_dir($job['source'])) {
unav_error(400, 'Search location must be a directory');
}
$query = trim((string)($data['query'] ?? ''));
if ($query === '' || strlen($query) > 200) {
unav_error(400, 'Invalid search query');
}
$job['query'] = $query;
break;
case 'checksum':
if (!is_file($job['source'])) {
unav_error(400, 'Checksums are only available for files');
}
break;
case 'compare':
$target = unav_existing_path($data['target'] ?? null)['path'];
if (!is_file($job['source']) || !is_file($target)) {
unav_error(400, 'Only files can be compared');
}
$job['target'] = $target;
break;
case 'extract':
unav_assert_writable();
if (!is_file($job['source']) || !preg_match(UNAV_ARCHIVE_PATTERN, $job['source'])) {
unav_error(400, 'Unsupported archive');
}
$destination = unav_destination_path($data['destination'] ?? null)['path'];
$job['destination'] = unav_unique_path($destination);
break;
case 'size':
break;
}
$id = str_replace('.', '', uniqid($action . '-', true));
$now = date(DATE_ATOM);
$job = [
$job = array_merge($job, [
'id' => $id,
'type' => $action,
'status' => 'queued',
'progress' => 0,
'message' => 'Queued',
'error' => null,
'source' => $source['path'],
'destination' => $destination['path'] ?? null,
'permissions' => $permissions,
'bytesDone' => 0,
'bytesTotal' => null,
'createdAt' => $now,
'updatedAt' => $now,
];
]);
unav_job_write($job);
$worker = __DIR__ . '/job_worker.php';
$php = is_executable('/usr/bin/php') ? '/usr/bin/php' : (PHP_BINARY ?: 'php');
$started = false;
if (unav_function_available('exec') && is_file($worker)) {
if (getenv('U_NAV_SYNC_JOBS') !== '1' && unav_function_available('exec') && is_file($worker)) {
try {
$exitCode = 0;
@exec(escapeshellarg($php) . ' ' . escapeshellarg($worker) . ' ' . escapeshellarg($id) . ' > /dev/null 2>&1 &', $output, $exitCode);
@@ -1,39 +1,76 @@
<?php
require_once __DIR__ . '/common.php';
const UNAV_COPY_CHUNK = 4194304;
const UNAV_SEARCH_LIMIT = 2000;
const UNAV_PROGRESS_INTERVAL = 0.5;
class UnavCancelled extends RuntimeException {
}
if (PHP_SAPI === 'cli' && realpath($_SERVER['SCRIPT_FILENAME'] ?? '') === __FILE__) {
unav_run_job($argv[1] ?? '');
}
function unav_run_job(string $id): void {
$job = unav_job_read($id);
$job['startedAt'] = date(DATE_ATOM);
$job['lastWrite'] = 0.0;
try {
unav_worker_update($job, 'running', 5, 'Preparing');
if (in_array($job['type'], ['move', 'delete', 'permissions'], true)) {
unav_worker_update($job, 'running', 2, 'Vorbereiten');
if (in_array($job['type'], ['move', 'delete', 'permissions', 'fixperms'], true)) {
unav_worker_assert_not_root($job['source']);
}
if ($job['type'] === 'move') {
unav_worker_guard($job['source'], $job['destination']);
unav_worker_move($job['source'], $job['destination'], $job);
} elseif ($job['type'] === 'copy') {
unav_worker_guard($job['source'], $job['destination']);
unav_worker_copy($job['source'], $job['destination'], $job);
} elseif ($job['type'] === 'delete') {
unav_worker_delete_job($job['source'], $job);
} elseif ($job['type'] === 'size') {
$result = unav_worker_size($job['source'], $job);
$job['result'] = $result;
} elseif ($job['type'] === 'permissions') {
unav_worker_permissions($job['source'], $job['permissions'] ?? [], $job);
} else {
throw new RuntimeException('Unknown job action');
switch ($job['type']) {
case 'move':
unav_worker_guard($job);
unav_worker_move($job);
break;
case 'copy':
unav_worker_guard($job);
unav_worker_copy_job($job);
break;
case 'delete':
unav_worker_delete_job($job);
break;
case 'size':
$job['result'] = unav_worker_size_recursive(unav_worker_guard_source($job['source']));
break;
case 'permissions':
unav_worker_permissions($job['source'], $job['permissions'] ?? [], $job);
break;
case 'fixperms':
unav_worker_fixperms($job);
break;
case 'search':
unav_worker_search($job);
break;
case 'checksum':
unav_worker_checksum($job);
break;
case 'compare':
unav_worker_compare($job);
break;
case 'extract':
unav_worker_extract($job);
break;
case 'compress':
unav_worker_compress($job);
break;
default:
throw new RuntimeException('Unknown job action');
}
unav_worker_update($job, 'completed', 100, 'Completed');
unav_worker_update($job, 'completed', 100, 'Fertig');
} catch (UnavCancelled $error) {
$job['error'] = null;
unav_worker_update($job, 'cancelled', 100, 'Abgebrochen');
} catch (Throwable $error) {
$job['error'] = $error->getMessage();
unav_worker_update($job, 'failed', 100, $error->getMessage());
} finally {
@unlink(unav_job_cancel_path($id));
}
}
@@ -41,26 +78,46 @@ function unav_worker_update(array &$job, string $status, int $progress, string $
$job['status'] = $status;
$job['progress'] = $progress;
$job['message'] = $message;
unav_job_write($job);
$job['lastWrite'] = microtime(true);
$copy = $job;
unset($copy['lastWrite']);
unav_job_write($copy);
}
function unav_worker_guard(string $source, string $destination): void {
$sourceReal = realpath($source);
if ($sourceReal === false) {
throw new RuntimeException('Source not found');
// Throttled progress write plus cancellation check; called from every hot loop.
function unav_worker_tick(array &$job, string $message, bool $force = false): void {
if (unav_job_cancel_requested($job['id'])) {
throw new UnavCancelled('Cancelled');
}
unav_worker_assert_inside_root($sourceReal);
if (!$force && microtime(true) - ($job['lastWrite'] ?? 0) < UNAV_PROGRESS_INTERVAL) {
return;
}
$progress = $job['progress'] ?? 0;
if (!empty($job['bytesTotal'])) {
$progress = 5 + (int)floor(90 * min(1, $job['bytesDone'] / $job['bytesTotal']));
}
unav_worker_update($job, 'running', $progress, $message);
}
function unav_worker_guard(array $job): void {
$sourceReal = unav_worker_guard_source($job['source']);
$destination = $job['destination'];
$parentReal = realpath(dirname($destination));
if ($parentReal === false) {
throw new RuntimeException('Destination parent not found');
}
unav_worker_assert_inside_root($parentReal);
$destinationPath = $parentReal . '/' . basename($destination);
if (file_exists($destinationPath)) {
$exists = file_exists($destinationPath) || is_link($destinationPath);
if ($exists && ($job['conflict'] ?? 'fail') !== 'overwrite') {
throw new RuntimeException('Destination already exists');
}
if ($exists) {
unav_worker_assert_not_root($destinationPath);
if (unav_is_inside($sourceReal, $destinationPath)) {
throw new RuntimeException('Destination cannot contain the source');
}
}
$normalizedSource = rtrim($sourceReal, '/');
$normalizedDestination = rtrim($destinationPath, '/');
if ($normalizedSource === $normalizedDestination || (is_dir($sourceReal) && str_starts_with($normalizedDestination, $normalizedSource . '/'))) {
@@ -85,35 +142,152 @@ function unav_worker_assert_not_root(string $path): void {
}
function unav_worker_assert_inside_root(string $path): void {
foreach (unav_roots() as $root) {
if (unav_is_inside($path, $root['path'])) {
if (!unav_is_in_any_root($path)) {
throw new RuntimeException('Path is outside allowed roots');
}
}
// Temporary sibling in the destination folder; renamed into place only after success.
function unav_worker_temp_path(array $job): string {
return dirname($job['destination']) . '/.u-nav-' . $job['id'] . '.part';
}
function unav_worker_replace_destination(string $temporary, string $destination): void {
if (file_exists($destination) || is_link($destination)) {
unav_worker_delete($destination);
}
if (!rename($temporary, $destination)) {
throw new RuntimeException('Could not move result into place');
}
}
function unav_worker_move(array &$job): void {
$source = $job['source'];
$destination = $job['destination'];
$overwrite = file_exists($destination) || is_link($destination);
unav_worker_update($job, 'running', 5, 'Verschieben');
if (!$overwrite && @rename($source, $destination)) {
return;
}
if ($overwrite) {
$temporary = unav_worker_temp_path($job);
if (@rename($source, $temporary)) {
try {
unav_worker_replace_destination($temporary, $destination);
} catch (Throwable $error) {
@rename($temporary, $source);
throw $error;
}
return;
}
}
throw new RuntimeException('Path is outside allowed roots');
}
function unav_worker_move(string $source, string $destination, array &$job): void {
unav_worker_update($job, 'running', 15, 'Moving');
if (@rename($source, $destination)) {
return;
}
unav_worker_copy($source, $destination, $job);
// Different filesystem (e.g. between Unraid shares): copy, then remove the source.
unav_worker_copy_job($job, 'Verschieben');
unav_worker_update($job, 'running', 96, 'Quelle entfernen');
unav_worker_delete($source);
}
function unav_worker_delete_job(string $source, array &$job): void {
$sourceReal = unav_worker_guard_source($source);
unav_worker_update($job, 'running', 15, 'Deleting');
unav_worker_delete($sourceReal);
function unav_worker_copy_job(array &$job, string $label = 'Kopieren'): void {
$source = $job['source'];
$temporary = unav_worker_temp_path($job);
$total = unav_worker_size_recursive($source);
$job['bytesTotal'] = $total['size'];
$job['bytesDone'] = 0;
$job['filesTotal'] = $total['files'];
unav_worker_tick($job, $label, true);
try {
unav_worker_copy($source, $temporary, $job, $label);
unav_worker_replace_destination($temporary, $job['destination']);
} catch (Throwable $error) {
if (file_exists($temporary) || is_link($temporary)) {
unav_worker_delete($temporary);
}
throw $error;
}
}
function unav_worker_size(string $source, array &$job): array {
$sourceReal = unav_worker_guard_source($source);
unav_worker_update($job, 'running', 10, 'Calculating size');
$result = unav_worker_size_recursive($sourceReal);
unav_worker_update($job, 'running', 95, 'Size calculated');
return $result;
function unav_worker_copy(string $source, string $destination, array &$job, string $label): void {
if (is_link($source)) {
throw new RuntimeException('Copying symlinks is not allowed');
}
if (is_dir($source)) {
if (!mkdir($destination, 0777, true) && !is_dir($destination)) {
throw new RuntimeException('Could not create destination directory');
}
foreach (scandir($source) ?: [] as $entry) {
if ($entry === '.' || $entry === '..') {
continue;
}
unav_worker_copy($source . '/' . $entry, $destination . '/' . $entry, $job, $label);
}
@chmod($destination, fileperms($source) & 07777);
@touch($destination, filemtime($source) ?: time());
return;
}
if (!is_file($source)) {
throw new RuntimeException('Only files and directories can be copied');
}
$in = fopen($source, 'rb');
$out = $in ? fopen($destination, 'xb') : false;
if (!$in || !$out) {
if ($in) {
fclose($in);
}
throw new RuntimeException('Copy failed: ' . basename($source));
}
try {
while (!feof($in)) {
$chunk = fread($in, UNAV_COPY_CHUNK);
if ($chunk === false) {
throw new RuntimeException('Read failed: ' . basename($source));
}
if ($chunk === '') {
continue;
}
if (fwrite($out, $chunk) !== strlen($chunk)) {
throw new RuntimeException('Write failed (disk full?): ' . basename($source));
}
$job['bytesDone'] += strlen($chunk);
$job['currentFile'] = basename($source);
unav_worker_tick($job, $label . ': ' . basename($source));
}
} finally {
fclose($in);
fclose($out);
}
@chmod($destination, fileperms($source) & 07777);
@touch($destination, filemtime($source) ?: time());
}
function unav_worker_delete_job(array &$job): void {
$sourceReal = unav_worker_guard_source($job['source']);
$job['itemsDone'] = 0;
unav_worker_update($job, 'running', 10, 'Löschen');
unav_worker_delete($sourceReal, $job);
}
function unav_worker_delete(string $path, ?array &$job = null): void {
if ($job !== null) {
$job['itemsDone'] = ($job['itemsDone'] ?? 0) + 1;
unav_worker_tick($job, 'Löschen: ' . $job['itemsDone'] . ' Elemente');
}
if (is_link($path) || is_file($path)) {
if (!unlink($path)) {
throw new RuntimeException('Could not delete ' . basename($path));
}
return;
}
if (is_dir($path)) {
foreach (scandir($path) ?: [] as $entry) {
if ($entry === '.' || $entry === '..') {
continue;
}
unav_worker_delete($path . '/' . $entry, $job);
}
if (!rmdir($path)) {
throw new RuntimeException('Could not delete directory ' . basename($path));
}
}
}
function unav_worker_size_recursive(string $path): array {
@@ -151,11 +325,10 @@ function unav_worker_permissions(string $source, array $options, array &$job): v
throw new RuntimeException('No permission changes requested');
}
unav_worker_update($job, 'running', 10, 'Updating permissions');
unav_worker_update($job, 'running', 10, 'Rechte ändern');
$count = 0;
unav_worker_permissions_apply($sourceReal, $mode, $owner, $group, $recursive, $job, $count);
$job['result'] = ['changed' => $count];
unav_worker_update($job, 'running', 95, 'Permissions updated');
}
function unav_worker_permissions_apply(string $path, ?string $mode, ?string $owner, ?string $group, bool $recursive, array &$job, int &$count): void {
@@ -176,9 +349,7 @@ function unav_worker_permissions_apply(string $path, ?string $mode, ?string $own
throw new RuntimeException('Could not change group');
}
$count++;
if ($count % 100 === 0) {
unav_worker_update($job, 'running', 50, 'Updating permissions');
}
unav_worker_tick($job, 'Rechte ändern: ' . $count . ' Elemente');
if (!$recursive || !is_dir($path)) {
return;
@@ -191,47 +362,369 @@ function unav_worker_permissions_apply(string $path, ?string $mode, ?string $own
}
}
function unav_worker_copy(string $source, string $destination, array &$job): void {
if (is_link($source)) {
throw new RuntimeException('Copying symlinks is not allowed');
}
if (is_dir($source)) {
if (!mkdir($destination, 0777, true) && !is_dir($destination)) {
throw new RuntimeException('Could not create destination directory');
function unav_worker_fixperms(array &$job): void {
$count = 0;
$walk = function (string $path) use (&$walk, &$job, &$count): void {
if (is_link($path)) {
return;
}
$entries = array_values(array_filter(scandir($source) ?: [], fn($entry) => $entry !== '.' && $entry !== '..'));
$total = max(count($entries), 1);
foreach ($entries as $index => $entry) {
unav_worker_copy($source . '/' . $entry, $destination . '/' . $entry, $job);
unav_worker_update($job, 'running', min(95, 10 + (int)((($index + 1) / $total) * 80)), 'Copying directory');
$isDir = is_dir($path);
unav_unraid_permissions($path, $isDir);
$count++;
unav_worker_tick($job, 'Rechte reparieren: ' . $count . ' Elemente');
if (!$isDir) {
return;
}
return;
foreach (scandir($path) ?: [] as $entry) {
if ($entry !== '.' && $entry !== '..') {
$walk($path . '/' . $entry);
}
}
};
$walk(unav_worker_guard_source($job['source']));
$job['result'] = ['changed' => $count];
}
function unav_lower(string $value): string {
return function_exists('mb_strtolower') ? mb_strtolower($value) : strtolower($value);
}
// Plain text matches anywhere in the name; * and ? switch to wildcard matching of the whole name.
function unav_worker_search_matcher(string $query): callable {
$needle = unav_lower($query);
if (strpbrk($query, '*?') !== false) {
return fn(string $name) => fnmatch($needle, unav_lower($name));
}
if (!is_file($source)) {
throw new RuntimeException('Only files and directories can be copied');
}
unav_worker_update($job, 'running', 35, 'Copying file');
if (!copy($source, $destination)) {
throw new RuntimeException('Copy failed');
return fn(string $name) => str_contains(unav_lower($name), $needle);
}
function unav_worker_search(array &$job): void {
$root = unav_worker_guard_source($job['source']);
$matches = unav_worker_search_matcher($job['query']);
$job['result'] = ['results' => [], 'scanned' => 0, 'truncated' => false];
$stack = [$root];
while ($stack) {
$dir = array_pop($stack);
$entries = @scandir($dir);
if ($entries === false) {
continue;
}
foreach ($entries as $name) {
if ($name === '.' || $name === '..') {
continue;
}
$path = $dir . '/' . $name;
$isLink = is_link($path);
$isDir = !$isLink && is_dir($path);
$job['result']['scanned']++;
if ($matches($name)) {
$job['result']['results'][] = [
'name' => $name,
'path' => $path,
'type' => $isLink ? 'symlink' : ($isDir ? 'directory' : (is_file($path) ? 'file' : 'other')),
'size' => (!$isDir && !$isLink) ? (@filesize($path) ?: 0) : 0,
'modifiedAt' => date(DATE_ATOM, @filemtime($path) ?: time()),
];
if (count($job['result']['results']) >= UNAV_SEARCH_LIMIT) {
$job['result']['truncated'] = true;
return;
}
}
if ($isDir) {
$stack[] = $path;
}
}
unav_worker_tick($job, 'Suche: ' . $job['result']['scanned'] . ' geprüft, ' . count($job['result']['results']) . ' Treffer');
}
}
function unav_worker_delete(string $path): void {
if (is_link($path) || is_file($path)) {
if (!unlink($path)) {
throw new RuntimeException('Could not remove source after move');
function unav_worker_checksum(array &$job): void {
$path = unav_worker_guard_source($job['source']);
$job['bytesTotal'] = filesize($path) ?: 0;
$job['bytesDone'] = 0;
$md5 = hash_init('md5');
$sha256 = hash_init('sha256');
$handle = fopen($path, 'rb');
if (!$handle) {
throw new RuntimeException('Could not read file');
}
try {
while (!feof($handle)) {
$chunk = fread($handle, UNAV_COPY_CHUNK);
if ($chunk === false) {
throw new RuntimeException('Could not read file');
}
hash_update($md5, $chunk);
hash_update($sha256, $chunk);
$job['bytesDone'] += strlen($chunk);
unav_worker_tick($job, 'Prüfsumme berechnen');
}
} finally {
fclose($handle);
}
$job['result'] = ['md5' => hash_final($md5), 'sha256' => hash_final($sha256), 'size' => $job['bytesDone']];
}
function unav_worker_compare(array &$job): void {
$first = unav_worker_guard_source($job['source']);
$second = unav_worker_guard_source($job['target']);
$sizeA = filesize($first) ?: 0;
$sizeB = filesize($second) ?: 0;
$job['result'] = ['identical' => false, 'sizeA' => $sizeA, 'sizeB' => $sizeB, 'firstDifference' => null];
if ($sizeA !== $sizeB) {
return;
}
$job['bytesTotal'] = $sizeA;
$job['bytesDone'] = 0;
$a = fopen($first, 'rb');
$b = fopen($second, 'rb');
if (!$a || !$b) {
throw new RuntimeException('Could not read files');
}
try {
while (!feof($a)) {
$chunkA = fread($a, UNAV_COPY_CHUNK);
$chunkB = fread($b, UNAV_COPY_CHUNK);
if ($chunkA !== $chunkB) {
$length = min(strlen((string)$chunkA), strlen((string)$chunkB));
$offset = 0;
while ($offset < $length && $chunkA[$offset] === $chunkB[$offset]) {
$offset++;
}
$job['result']['firstDifference'] = $job['bytesDone'] + $offset;
return;
}
$job['bytesDone'] += strlen((string)$chunkA);
unav_worker_tick($job, 'Vergleichen');
}
} finally {
fclose($a);
fclose($b);
}
$job['result']['identical'] = true;
}
function unav_worker_extract(array &$job): void {
$archive = unav_worker_guard_source($job['source']);
$destination = $job['destination'];
$parent = realpath(dirname($destination));
if ($parent === false) {
throw new RuntimeException('Destination parent not found');
}
unav_worker_assert_inside_root($parent);
$destination = $parent . '/' . basename($destination);
if (file_exists($destination) || is_link($destination)) {
throw new RuntimeException('Destination already exists');
}
$temporary = unav_worker_temp_path(['destination' => $destination, 'id' => $job['id']]);
if (!mkdir($temporary, 0777)) {
throw new RuntimeException('Could not create destination directory');
}
try {
if (preg_match('/\.zip$/i', $archive)) {
unav_worker_extract_zip($archive, $temporary, $job);
} else {
unav_worker_extract_tar($archive, $temporary, $job);
}
if (!rename($temporary, $destination)) {
throw new RuntimeException('Could not move result into place');
}
} catch (Throwable $error) {
unav_worker_delete($temporary);
throw $error;
}
$job['destination'] = $destination;
}
// Entries are written one by one so absolute paths, ".." and symlinks can be rejected (zip slip).
function unav_worker_extract_zip(string $archive, string $target, array &$job): void {
if (!class_exists('ZipArchive')) {
throw new RuntimeException('ZIP support is not available');
}
$zip = new ZipArchive();
if ($zip->open($archive) !== true) {
throw new RuntimeException('Could not open ZIP archive');
}
try {
$total = 0;
for ($i = 0; $i < $zip->numFiles; $i++) {
$total += (int)($zip->statIndex($i)['size'] ?? 0);
}
$job['bytesTotal'] = $total;
$job['bytesDone'] = 0;
for ($i = 0; $i < $zip->numFiles; $i++) {
$stat = $zip->statIndex($i);
$name = str_replace('\\', '/', (string)($stat['name'] ?? ''));
$parts = array_values(array_filter(explode('/', $name), fn($part) => $part !== '' && $part !== '.'));
if (!$parts || str_starts_with($name, '/') || in_array('..', $parts, true)) {
throw new RuntimeException('Unsafe path in archive: ' . $name);
}
$opsys = 0;
$attributes = 0;
if ($zip->getExternalAttributesIndex($i, $opsys, $attributes) && $opsys === ZipArchive::OPSYS_UNIX
&& ((($attributes >> 16) & 0170000) === 0120000)) {
continue;
}
$path = $target . '/' . implode('/', $parts);
if (str_ends_with($name, '/')) {
if (!is_dir($path) && !mkdir($path, 0777, true)) {
throw new RuntimeException('Could not create ' . $name);
}
continue;
}
if (!is_dir(dirname($path)) && !mkdir(dirname($path), 0777, true)) {
throw new RuntimeException('Could not create ' . dirname($name));
}
$in = $zip->getStream($stat['name']);
$out = fopen($path, 'xb');
if (!$in || !$out) {
throw new RuntimeException('Could not extract ' . $name);
}
try {
while (!feof($in)) {
$chunk = fread($in, UNAV_COPY_CHUNK);
if ($chunk === false || fwrite($out, $chunk) !== strlen($chunk)) {
throw new RuntimeException('Could not extract ' . $name);
}
$job['bytesDone'] += strlen($chunk);
unav_worker_tick($job, 'Entpacken: ' . basename($name));
}
} finally {
fclose($in);
fclose($out);
}
if (!empty($stat['mtime'])) {
@touch($path, (int)$stat['mtime']);
}
}
} finally {
$zip->close();
}
}
// GNU tar refuses absolute and ".." member names and defers symlinks; ownership is not restored.
function unav_worker_extract_tar(string $archive, string $target, array &$job): void {
if (!unav_function_available('proc_open')) {
throw new RuntimeException('tar extraction is not available');
}
unav_worker_update($job, 'running', 20, 'Entpacken');
$command = ['tar', '-xf', $archive, '-C', $target, '--no-same-owner'];
$process = proc_open($command, [1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes);
if (!is_resource($process)) {
throw new RuntimeException('Could not start tar');
}
stream_set_blocking($pipes[1], false);
stream_set_blocking($pipes[2], false);
$errors = '';
while (true) {
$status = proc_get_status($process);
$errors .= (string)stream_get_contents($pipes[2]);
stream_get_contents($pipes[1]);
if (!$status['running']) {
break;
}
try {
unav_worker_tick($job, 'Entpacken');
} catch (UnavCancelled $cancel) {
proc_terminate($process);
proc_close($process);
throw $cancel;
}
usleep(200000);
}
$errors .= (string)stream_get_contents($pipes[2]);
fclose($pipes[1]);
fclose($pipes[2]);
proc_close($process);
if (($status['exitcode'] ?? 1) !== 0) {
throw new RuntimeException('tar failed: ' . trim(substr($errors, 0, 300)));
}
}
function unav_worker_compress(array &$job): void {
if (!class_exists('ZipArchive')) {
throw new RuntimeException('ZIP support is not available');
}
$sources = array_map('unav_worker_guard_source', $job['sources'] ?? []);
$destination = $job['destination'];
$parent = realpath(dirname($destination));
if ($parent === false) {
throw new RuntimeException('Destination parent not found');
}
unav_worker_assert_inside_root($parent);
$destination = $parent . '/' . basename($destination);
if (file_exists($destination)) {
throw new RuntimeException('Destination already exists');
}
$temporary = unav_worker_temp_path(['destination' => $destination, 'id' => $job['id']]);
$zip = new ZipArchive();
if ($zip->open($temporary, ZipArchive::CREATE | ZipArchive::EXCL) !== true) {
throw new RuntimeException('Could not create ZIP archive');
}
$total = 0;
foreach ($sources as $source) {
$total += unav_worker_size_recursive($source)['size'];
}
$job['bytesTotal'] = $total;
$job['bytesDone'] = 0;
$used = [];
$closed = false;
try {
foreach ($sources as $source) {
$name = basename($source);
$base = $name;
for ($i = 2; isset($used[$name]); $i++) {
$name = $base . ' (' . $i . ')';
}
$used[$name] = true;
unav_worker_zip_add($zip, $source, $name, $job);
}
if (method_exists($zip, 'registerCancelCallback')) {
$zip->registerCancelCallback(fn() => unav_job_cancel_requested($job['id']) ? -1 : 0);
}
unav_worker_update($job, 'running', 90, 'Archiv schreiben');
$closed = true;
if (!$zip->close()) {
if (unav_job_cancel_requested($job['id'])) {
throw new UnavCancelled('Cancelled');
}
throw new RuntimeException('Could not write ZIP archive');
}
unav_worker_tick($job, 'Archiv schreiben', true);
if (!rename($temporary, $destination)) {
throw new RuntimeException('Could not move result into place');
}
} catch (Throwable $error) {
if (!$closed) {
try {
$zip->close();
} catch (Throwable $ignored) {
}
}
@unlink($temporary);
throw $error;
}
$job['destination'] = $destination;
}
function unav_worker_zip_add(ZipArchive $zip, string $path, string $name, array &$job): void {
if (is_link($path)) {
return;
}
if (is_dir($path)) {
$zip->addEmptyDir($name);
foreach (scandir($path) ?: [] as $entry) {
if ($entry === '.' || $entry === '..') {
continue;
if ($entry !== '.' && $entry !== '..') {
unav_worker_zip_add($zip, $path . '/' . $entry, $name . '/' . $entry, $job);
}
unav_worker_delete($path . '/' . $entry);
}
if (!rmdir($path)) {
throw new RuntimeException('Could not remove source directory after move');
}
return;
}
if (is_file($path)) {
$zip->addFile($path, $name);
$job['bytesDone'] += filesize($path) ?: 0;
// Bytes are only read on close(); this tracks the collected share of the archive.
$job['bytesDone'] = min($job['bytesDone'], (int)(($job['bytesTotal'] ?: 1) * 0.9));
unav_worker_tick($job, 'Archiv vorbereiten: ' . $name);
}
}
@@ -0,0 +1,28 @@
<?php
require_once __DIR__ . '/common.php';
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
unav_error(405, 'Method not allowed');
}
unav_assert_writable();
$data = unav_request_data();
$parent = unav_existing_path($data['path'] ?? null);
if (!is_dir($parent['path'])) {
unav_error(400, 'Target must be a directory');
}
$name = trim((string)($data['name'] ?? ''));
if (!unav_valid_name($name)) {
unav_error(400, 'Ungültiger Ordnername');
}
$path = $parent['path'] . '/' . $name;
if (file_exists($path) || is_link($path)) {
unav_error(409, 'Destination already exists');
}
if (!mkdir($path, 0777)) {
unav_error(500, 'Could not create directory');
}
// New share content should be usable over SMB like everything else on Unraid.
if (function_exists('posix_geteuid') && posix_geteuid() === 0) {
unav_unraid_permissions($path, true);
}
unav_json(['path' => $path, 'name' => $name], 201);
@@ -0,0 +1,62 @@
<?php
require_once __DIR__ . '/common.php';
// Free space for the current folder plus, for the user share view, the physical
// disks/pools that actually hold the item (Unraid spreads shares over several devices).
$resolved = unav_existing_path($_GET['path'] ?? null);
$path = $resolved['path'];
$mnt = unav_mnt_dir();
function unav_storage_space(string $path): array {
$free = @disk_free_space($path);
$total = @disk_total_space($path);
return [
'free' => $free === false ? null : (int)$free,
'total' => $total === false ? null : (int)$total,
];
}
function unav_storage_devices(string $mnt): array {
$skip = ['user', 'user0', 'disks', 'remotes', 'addons', 'rootshare'];
$devices = [];
foreach (scandir($mnt) ?: [] as $name) {
if ($name === '.' || $name === '..' || in_array($name, $skip, true) || str_starts_with($name, '.')) {
continue;
}
$dir = $mnt . '/' . $name;
if (!is_dir($dir) || is_link($dir)) {
continue;
}
$devices[] = array_merge([
'name' => $name,
'path' => $dir,
'kind' => preg_match('/^disk\d+$/', $name) ? 'disk' : 'pool',
], unav_storage_space($dir));
}
usort($devices, fn($a, $b) => strnatcmp($a['name'], $b['name']));
return $devices;
}
$locations = [];
$devices = [];
$userPrefix = $mnt . '/user/';
if (str_starts_with($path . '/', $userPrefix) && $path !== rtrim($userPrefix, '/')) {
$relative = substr($path, strlen($userPrefix));
$devices = unav_storage_devices($mnt);
foreach ($devices as $device) {
if (file_exists($device['path'] . '/' . $relative)) {
$locations[] = $device;
}
}
} elseif (preg_match('#^' . preg_quote($mnt, '#') . '/([^/]+)#', $path, $match)) {
$device = $mnt . '/' . $match[1];
if (!in_array($match[1], ['user', 'user0'], true) && is_dir($device)) {
$locations[] = array_merge([
'name' => $match[1],
'path' => $device,
'kind' => preg_match('/^disk\d+$/', $match[1]) ? 'disk' : 'pool',
], unav_storage_space($device));
}
}
unav_json(array_merge(['path' => $path, 'locations' => $locations], unav_storage_space($path)));
@@ -0,0 +1,43 @@
<?php
require_once __DIR__ . '/common.php';
// Small JPEG previews for the icon view, rendered on the fly; nothing is written to disk.
const UNAV_THUMB_MAX_PIXELS = 40000000;
const UNAV_THUMB_MAX_BYTES = 52428800;
$resolved = unav_existing_path($_GET['path'] ?? null);
$path = $resolved['path'];
$size = max(32, min(512, (int)($_GET['size'] ?? 192)));
if (!is_file($path) || !preg_match('/\.(jpe?g|png|gif|webp)$/i', $path)) {
unav_error(415, 'No thumbnail for this file type');
}
if (!function_exists('imagecreatefromstring') || (filesize($path) ?: 0) > UNAV_THUMB_MAX_BYTES) {
unav_error(415, 'Thumbnail not available');
}
$info = @getimagesize($path);
if (!$info || $info[0] < 1 || $info[1] < 1 || $info[0] * $info[1] > UNAV_THUMB_MAX_PIXELS) {
unav_error(415, 'Thumbnail not available');
}
$etag = '"' . md5($path . '|' . filemtime($path) . '|' . filesize($path) . '|' . $size) . '"';
header('Cache-Control: private, max-age=86400');
header('ETag: ' . $etag);
if (($_SERVER['HTTP_IF_NONE_MATCH'] ?? '') === $etag) {
http_response_code(304);
exit;
}
ini_set('memory_limit', '512M');
$image = @imagecreatefromstring(file_get_contents($path));
if (!$image) {
unav_error(415, 'Thumbnail not available');
}
$scale = min(1, $size / max($info[0], $info[1]));
$width = max(1, (int)round($info[0] * $scale));
$height = max(1, (int)round($info[1] * $scale));
$thumb = imagecreatetruecolor($width, $height);
imagefill($thumb, 0, 0, imagecolorallocate($thumb, 255, 255, 255));
imagecopyresampled($thumb, $image, 0, 0, 0, 0, $width, $height, $info[0], $info[1]);
header('Content-Type: image/jpeg');
header('X-Content-Type-Options: nosniff');
imagejpeg($thumb, null, 80);