Compare commits

...

9 Commits

Author SHA1 Message Date
Terranom674
929f18a5f5 Fix duplicate private album access function and bump version 2026-08-20 13:49:33 +02:00
Terranom674
0c45576e2f Bump plugin version for WebDAV derivative test 2026-08-20 13:46:25 +02:00
Terranom674
ee01842cb4 Add parallel WebDAV derivative materialization test endpoint 2026-08-20 13:41:17 +02:00
Terranom674
a872f9238c Merge pull request #52 from Terranom674/fix/0963-clean-webdav-orphans
0.9.6.3: verwaiste WebDAV-Bilder einmalig bereinigen
2026-08-20 11:25:39 +02:00
Terranom674
fdcf045f39 0.9.6.3: WebDAV-Pfadfilter exakt begrenzen 2026-08-20 11:24:56 +02:00
Terranom674
7831a9513f Version 0.9.6.3 2026-08-20 11:24:19 +02:00
Terranom674
fed089db4c 0.9.6.3: Altlasten-Reparatur einmalig vor WebDAV-Sync ausführen 2026-08-20 11:23:54 +02:00
Terranom674
77a295d74f 0.9.6.3: einmalige Reparatur verwaister WebDAV-Bilder 2026-08-20 11:23:33 +02:00
Terranom674
ecabf2da2f Merge PR #51: WebDAV-only connector cleanup
Remove obsolete legacy/local connector paths while preserving the WebDAV connector, shadow tree, placeholder mapping and Piwigo sync bridge.
2026-08-20 11:08:55 +02:00
4 changed files with 483 additions and 17 deletions

View File

@@ -1,7 +1,7 @@
<?php <?php
/* /*
Plugin Name: Bratonien Tools Plugin Name: Bratonien Tools
Version: 0.9.6.2 Version: 0.9.6.5
Description: Erweiterbare Administrationswerkzeuge fuer die Bratonien-Piwigo-Installation. Description: Erweiterbare Administrationswerkzeuge fuer die Bratonien-Piwigo-Installation.
Plugin URI: https://github.com/Terranom674/Piwigo_Bratonien_Tools Plugin URI: https://github.com/Terranom674/Piwigo_Bratonien_Tools
Author: Bratonien Author: Bratonien
@@ -81,36 +81,46 @@ function bratonien_tools_prepare_private_album_permissions()
return; return;
} }
$result = pwg_query('SELECT status FROM '.CATEGORIES_TABLE.' WHERE id = '.$category_id.' LIMIT 1'); bratonien_tools_grant_private_album_access($category_id, (int)$user['id']);
if (!pwg_db_num_rows($result)) }
function bratonien_tools_grant_private_album_access($category_id, $user_id)
{
$category_id = (int)$category_id;
$user_id = (int)$user_id;
if ($category_id < 1 || $user_id < 1)
{ {
return; return;
} }
$category = pwg_db_fetch_assoc($result); $query = '
if ($category['status'] !== 'public') SELECT 1
FROM '.USER_ACCESS_TABLE.'
WHERE user_id = '.$user_id.'
AND cat_id = '.$category_id.'
LIMIT 1
;';
$result = pwg_query($query);
if (pwg_db_num_rows($result) > 0)
{ {
return; return;
} }
$users = isset($_POST['users']) && is_array($_POST['users']) ? $_POST['users'] : array(); single_insert(
$current_user_id = (int)$user['id']; USER_ACCESS_TABLE,
$normalized_user_ids = array_map('intval', $users); array(
'user_id' => $user_id,
if (!in_array($current_user_id, $normalized_user_ids, true)) 'cat_id' => $category_id,
{ )
$users[] = $current_user_id; );
}
$_POST['users'] = $users;
} }
function bratonien_tools_admin_menu($menu) function bratonien_tools_admin_menu($menu)
{ {
$menu[] = array( $menu[] = array(
'NAME' => 'Bratonien Tools', 'NAME' => 'Bratonien Tools',
'URL' => get_root_url() . 'admin.php?page=plugin-' . BRATONIEN_TOOLS_ID, 'URL' => get_root_url() . 'admin.php?page=plugin-' . BRATONIEN_TOOLS_ID,
); );
return $menu; return $menu;
} }
?>

View File

@@ -0,0 +1,101 @@
#!/usr/bin/env php
<?php
if (PHP_SAPI !== 'cli')
{
fwrite(STDERR, "CLI only\n");
exit(1);
}
$pluginRoot = dirname(__DIR__);
$piwigoRoot = dirname($pluginRoot, 2);
define('PHPWG_ROOT_PATH', rtrim($piwigoRoot, '/').'/');
$_SERVER['REMOTE_ADDR'] = '127.0.0.1';
$_SERVER['SERVER_ADDR'] = '127.0.0.1';
$_SERVER['SERVER_NAME'] = 'localhost';
$_SERVER['HTTP_HOST'] = 'localhost';
$_SERVER['SERVER_PORT'] = '80';
$_SERVER['REQUEST_METHOD'] = 'GET';
$_SERVER['REQUEST_URI'] = '/';
$_SERVER['SCRIPT_NAME'] = '/plugins/bratonien_tools/runtime/repair-webdav-orphans.php';
$_SERVER['PHP_SELF'] = $_SERVER['SCRIPT_NAME'];
$_SERVER['QUERY_STRING'] = '';
$_SERVER['HTTPS'] = 'off';
require_once(PHPWG_ROOT_PATH.'include/common.inc.php');
require_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
$stateRoot = '/var/lib/bratonien-tools/nc-connector';
$marker = $stateRoot.'/.webdav-orphan-repair-0963.done';
try
{
if (is_file($marker))
{
echo "NC WebDAV Altlasten-Reparatur: bereits abgeschlossen.\n";
exit(0);
}
if (!is_dir($stateRoot) && !mkdir($stateRoot, 0750, true))
{
throw new RuntimeException('State-Verzeichnis konnte nicht angelegt werden: '.$stateRoot);
}
$relativePrefix = './_data/bratonien-tools/nc-webdav-gallery/connection-';
$absolutePrefix = rtrim(PHPWG_ROOT_PATH, '/').'/_data/bratonien-tools/nc-webdav-gallery/connection-';
$relativeLength = strlen($relativePrefix);
$absoluteLength = strlen($absolutePrefix);
$query = "SELECT id,path FROM ".IMAGES_TABLE.
" WHERE LEFT(path,".$relativeLength.")='".pwg_db_real_escape_string($relativePrefix)."'".
" OR LEFT(path,".$absoluteLength.")='".pwg_db_real_escape_string($absolutePrefix)."'";
$result = pwg_query($query);
$staleIds = array();
while ($row = pwg_db_fetch_assoc($result))
{
$id = (int)$row['id'];
$storedPath = (string)$row['path'];
if ($id < 1 || $storedPath === '') continue;
if (strpos($storedPath, $relativePrefix) === 0)
{
$filesystemPath = rtrim(PHPWG_ROOT_PATH, '/').'/'.ltrim(substr($storedPath, 2), '/');
}
elseif (strpos($storedPath, $absolutePrefix) === 0)
{
$filesystemPath = $storedPath;
}
else
{
continue;
}
if (!is_file($filesystemPath))
{
$staleIds[] = $id;
}
}
$staleIds = array_values(array_unique(array_map('intval', $staleIds)));
if ($staleIds)
{
delete_elements($staleIds, false);
invalidate_user_cache(true);
}
$payload = date('c').' removed='.count($staleIds)."\n";
if (file_put_contents($marker, $payload, LOCK_EX) === false)
{
throw new RuntimeException('Abschlussmarker konnte nicht geschrieben werden: '.$marker);
}
@chmod($marker, 0640);
echo 'NC WebDAV Altlasten-Reparatur: entfernte verwaiste Bilder='.count($staleIds)."\n";
exit(0);
}
catch (Throwable $e)
{
fwrite(STDERR, 'NC WebDAV Altlasten-Reparatur: '.$e->getMessage()."\n");
exit(1);
}

View File

@@ -10,6 +10,11 @@ if ! php "$SCRIPT_DIR/reconcile-webdav.php"; then
exit 1 exit 1
fi fi
if ! php "$SCRIPT_DIR/repair-webdav-orphans.php"; then
echo "NC Connector: verwaiste WebDAV-Bilddatensaetze konnten nicht repariert werden." >&2
exit 1
fi
if ! php "$SCRIPT_DIR/cleanup-webdav-piwigo.php"; then if ! php "$SCRIPT_DIR/cleanup-webdav-piwigo.php"; then
echo "NC Connector: Piwigo-Inhalte geloeschter WebDAV-Verbindungen konnten nicht bereinigt werden." >&2 echo "NC Connector: Piwigo-Inhalte geloeschter WebDAV-Verbindungen konnten nicht bereinigt werden." >&2
exit 1 exit 1

350
webdav-derivative-test.php Normal file
View File

@@ -0,0 +1,350 @@
<?php
define('PHPWG_ROOT_PATH', '../../');
include_once(PHPWG_ROOT_PATH.'include/common.inc.php');
if (!defined('BRATONIEN_TOOLS_PATH'))
{
define('BRATONIEN_TOOLS_ID', basename(__DIR__));
define('BRATONIEN_TOOLS_PATH', PHPWG_ROOT_PATH.'plugins/'.BRATONIEN_TOOLS_ID.'/');
}
require_once(BRATONIEN_TOOLS_PATH.'include/webdav_image_runtime.inc.php');
require_once(PHPWG_ROOT_PATH.'include/derivative.inc.php');
function bratonien_tools_webdav_derivative_test_abort($status, $message)
{
http_response_code((int)$status);
header('Content-Type: text/plain; charset=utf-8');
header('Cache-Control: no-store');
echo $message;
exit;
}
function bratonien_tools_webdav_derivative_test_decrypt_secret($blob, $hex_key)
{
$hex_key = trim((string)$hex_key);
if (!preg_match('/^[a-f0-9]{64}$/', $hex_key)) return null;
$outer = base64_decode(trim((string)$blob), true);
$payload = is_string($outer) ? json_decode($outer, true) : null;
if (!is_array($payload) || (int)($payload['v'] ?? 0) !== 1) return null;
$iv = base64_decode((string)($payload['iv'] ?? ''), true);
$tag = base64_decode((string)($payload['tag'] ?? ''), true);
$cipher = base64_decode((string)($payload['data'] ?? ''), true);
if (!is_string($iv) || !is_string($tag) || !is_string($cipher)) return null;
$plain = openssl_decrypt($cipher, 'aes-256-gcm', hex2bin($hex_key), OPENSSL_RAW_DATA, $iv, $tag);
if ($plain === false) return null;
$decoded = json_decode((string)$plain, true);
return is_array($decoded) ? $decoded : null;
}
function bratonien_tools_webdav_derivative_test_quote_path($path)
{
$parts = array_values(array_filter(explode('/', trim((string)$path, '/')), 'strlen'));
return implode('/', array_map('rawurlencode', $parts));
}
function bratonien_tools_webdav_derivative_test_download(array $source, $destination, &$detail=null)
{
$detail = '';
$table = $GLOBALS['prefixeTable'].'bratonien_tools_nc_connections';
$result = pwg_query('SELECT config_json, secret_blob FROM `'.$table.'` WHERE id='.(int)$source['connection_id'].' LIMIT 1');
if (!pwg_db_num_rows($result))
{
$detail = 'WebDAV-Verbindung nicht gefunden.';
return false;
}
$row = pwg_db_fetch_assoc($result);
$config = json_decode((string)$row['config_json'], true);
if (!is_array($config))
{
$detail = 'WebDAV-Konfiguration ist ungueltig.';
return false;
}
$key_result = pwg_query("SELECT value FROM ".$GLOBALS['prefixeTable']."config WHERE param='bratonien_nc_connector_secret' LIMIT 1");
if (!pwg_db_num_rows($key_result))
{
$detail = 'Connector-Schluessel fehlt.';
return false;
}
$key_row = pwg_db_fetch_assoc($key_result);
$credentials = bratonien_tools_webdav_derivative_test_decrypt_secret((string)$row['secret_blob'], (string)$key_row['value']);
if (!is_array($credentials))
{
$detail = 'WebDAV-Zugangsdaten konnten nicht gelesen werden.';
return false;
}
$base_url = rtrim((string)($config['nextcloud_url'] ?? ''), '/');
$user = trim((string)($credentials['nextcloud_user'] ?? ''));
$password = (string)($credentials['nextcloud_password'] ?? '');
$webdav_path = trim((string)($source['webdav_path'] ?? ''), '/');
if ($base_url === '' || $user === '' || $password === '' || $webdav_path === '')
{
$detail = 'WebDAV-Bildquelle ist unvollstaendig.';
return false;
}
$fp = @fopen($destination, 'xb');
if (!$fp)
{
$detail = 'Temporaere Quelldatei konnte nicht angelegt werden.';
return false;
}
$url = $base_url.'/remote.php/dav/files/'.rawurlencode($user).'/'.bratonien_tools_webdav_derivative_test_quote_path($webdav_path);
$ch = curl_init($url);
curl_setopt_array($ch, array(
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_TIMEOUT => 180,
CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
CURLOPT_USERPWD => $user.':'.$password,
CURLOPT_RETURNTRANSFER => false,
CURLOPT_FAILONERROR => false,
CURLOPT_FILE => $fp,
CURLOPT_USERAGENT => 'Bratonien-Tools-WebDAV-Derivative-Test/0.9.6.3',
));
$ok = curl_exec($ch);
$errno = curl_errno($ch);
$error = curl_error($ch);
$http = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
fclose($fp);
if ($ok === false || $errno !== 0 || $http < 200 || $http >= 300)
{
@unlink($destination);
$detail = 'Nextcloud-Download fehlgeschlagen (HTTP '.$http.', cURL '.$errno.($error !== '' ? ': '.$error : '').').';
return false;
}
if (!is_file($destination) || filesize($destination) < 1 || @getimagesize($destination) === false)
{
@unlink($destination);
$detail = 'Nextcloud-Datei ist kein lesbares Bild.';
return false;
}
return true;
}
function bratonien_tools_webdav_derivative_test_inner_url($derivative_path)
{
$derivative_root = PHPWG_ROOT_PATH.PWG_DERIVATIVE_DIR;
if (strpos($derivative_path, $derivative_root) !== 0) return null;
$location = ltrim(substr($derivative_path, strlen($derivative_root)), '/');
if ($location === '') return null;
$segments = array_map('rawurlencode', explode('/', $location));
return rtrim(get_absolute_root_url(), '/').'/i.php?/'.implode('/', $segments);
}
function bratonien_tools_webdav_derivative_test_call_i($url, &$response_body, &$response_type, &$response_status, &$detail=null)
{
$detail = '';
$response_body = '';
$response_type = 'application/octet-stream';
$response_status = 500;
$ch = curl_init($url);
curl_setopt_array($ch, array(
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_TIMEOUT => 180,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FAILONERROR => false,
CURLOPT_USERAGENT => 'Bratonien-Tools-Derivative-Gate/0.9.6.3',
));
$body = curl_exec($ch);
$errno = curl_errno($ch);
$error = curl_error($ch);
$status = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
$content_type = (string)curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
curl_close($ch);
$response_status = $status;
if ($content_type !== '') $response_type = $content_type;
if (is_string($body)) $response_body = $body;
if ($body === false || $errno !== 0)
{
$detail = 'Interner i.php-Aufruf fehlgeschlagen (cURL '.$errno.($error !== '' ? ': '.$error : '').').';
return false;
}
if ($status < 200 || $status >= 400)
{
$detail = 'i.php antwortete mit HTTP '.$status.'.';
return false;
}
return true;
}
global $user;
if (!isset($user['status']) || !in_array($user['status'], array('admin', 'webmaster'), true))
{
bratonien_tools_webdav_derivative_test_abort(403, 'Dieser Test-Endpunkt ist nur fuer Administratoren verfuegbar.');
}
$image_id = (int)($_GET['id'] ?? 0);
if ($image_id < 1)
{
bratonien_tools_webdav_derivative_test_abort(400, 'Bild-ID fehlt.');
}
$type = trim((string)($_GET['type'] ?? IMG_THUMB));
$defined = ImageStdParams::get_defined_type_map();
if (!isset($defined[$type]))
{
bratonien_tools_webdav_derivative_test_abort(400, 'Unbekannter oder deaktivierter Derivat-Typ: '.$type);
}
$result = pwg_query('SELECT * FROM '.IMAGES_TABLE.' WHERE id='.$image_id.' LIMIT 1');
if (!pwg_db_num_rows($result))
{
bratonien_tools_webdav_derivative_test_abort(404, 'Bild nicht gefunden.');
}
$image_row = pwg_db_fetch_assoc($result);
$src_image = new SrcImage($image_row);
$source = bratonien_tools_webdav_image_source_info($image_id);
if (!$source)
{
bratonien_tools_webdav_derivative_test_abort(404, 'Keine WebDAV-Quelle fuer dieses Bild gefunden.');
}
$derivative = new DerivativeImage($defined[$type], $src_image);
if ($derivative->same_as_source())
{
bratonien_tools_webdav_derivative_test_abort(409, 'Dieser Typ ist fuer das Bild identisch mit der Quelle und erzeugt kein Derivat.');
}
$derivative_path = $derivative->get_path();
if (is_file($derivative_path) && is_readable($derivative_path))
{
header('X-Bratonien-WebDAV-Test: derivative-already-exists');
header('Content-Type: '.(function_exists('mime_content_type') ? (mime_content_type($derivative_path) ?: 'application/octet-stream') : 'application/octet-stream'));
header('Content-Length: '.filesize($derivative_path));
header('Cache-Control: no-store');
readfile($derivative_path);
exit;
}
$image_path = (string)($image_row['path'] ?? '');
$absolute_image_path = $image_path;
if (strpos($absolute_image_path, '/') !== 0)
{
$absolute_image_path = PHPWG_ROOT_PATH.ltrim(preg_replace('#^\./#', '', $absolute_image_path), '/');
}
$materialize_path = realpath($absolute_image_path);
if ($materialize_path === false || !is_file($materialize_path))
{
bratonien_tools_webdav_derivative_test_abort(500, 'Placeholder-Quelldatei konnte nicht aufgeloest werden.');
}
$normalized_materialize = str_replace('\\', '/', $materialize_path);
if (!preg_match('#/nc-webdav-source/connection-'.(int)$source['connection_id'].'/#', $normalized_materialize))
{
bratonien_tools_webdav_derivative_test_abort(500, 'Aufgeloester Placeholder-Pfad passt nicht zur WebDAV-Verbindung.');
}
$lock_path = $materialize_path.'.bratonien-materialize.lock';
$lock = @fopen($lock_path, 'c');
if (!$lock || !flock($lock, LOCK_EX))
{
if ($lock) fclose($lock);
bratonien_tools_webdav_derivative_test_abort(503, 'Materialisierungs-Lock konnte nicht gesetzt werden.');
}
$temp_path = $materialize_path.'.bratonien-real.'.getmypid().'.'.bin2hex(random_bytes(4)).'.part';
$backup_path = $materialize_path.'.bratonien-placeholder.'.getmypid().'.'.bin2hex(random_bytes(4));
$materialized = false;
$backup_created = false;
$cleaned = false;
$cleanup = function() use (&$cleaned, &$materialized, &$backup_created, $materialize_path, $backup_path, $temp_path, $lock)
{
if ($cleaned) return;
$cleaned = true;
if ($materialized && $backup_created && is_file($backup_path))
{
@rename($backup_path, $materialize_path);
}
elseif ($backup_created && is_file($backup_path) && !is_file($materialize_path))
{
@rename($backup_path, $materialize_path);
}
if (is_file($temp_path)) @unlink($temp_path);
if (is_file($backup_path)) @unlink($backup_path);
@flock($lock, LOCK_UN);
@fclose($lock);
};
register_shutdown_function($cleanup);
try
{
$detail = '';
if (!bratonien_tools_webdav_derivative_test_download($source, $temp_path, $detail))
{
bratonien_tools_webdav_derivative_test_abort(502, $detail);
}
// Preserve the exact placeholder inode via a second hard link. Replacing the
// real source entry with rename() is then atomic and does not overwrite the
// shared placeholder inode used by the WebDAV source tree.
if (!@link($materialize_path, $backup_path))
{
bratonien_tools_webdav_derivative_test_abort(500, 'Placeholder konnte nicht sicher per Hardlink gesichert werden.');
}
$backup_created = true;
if (!@rename($temp_path, $materialize_path))
{
bratonien_tools_webdav_derivative_test_abort(500, 'Nextcloud-Bild konnte nicht atomar materialisiert werden.');
}
$materialized = true;
clearstatcache(true, $materialize_path);
$inner_url = bratonien_tools_webdav_derivative_test_inner_url($derivative_path);
if ($inner_url === null)
{
bratonien_tools_webdav_derivative_test_abort(500, 'Piwigo-i.php-URL konnte nicht bestimmt werden.');
}
$body = '';
$content_type = 'application/octet-stream';
$status = 500;
if (!bratonien_tools_webdav_derivative_test_call_i($inner_url, $body, $content_type, $status, $detail))
{
bratonien_tools_webdav_derivative_test_abort(502, $detail."\n".$body);
}
// Restore before anything is sent to the client. The derivative itself stays
// in Piwigo; only the transient Nextcloud original disappears again.
$cleanup();
clearstatcache(true, $derivative_path);
if (!is_file($derivative_path) || !is_readable($derivative_path))
{
bratonien_tools_webdav_derivative_test_abort(500, 'i.php lieferte eine Antwort, aber das Piwigo-Derivat wurde nicht gefunden.');
}
header('X-Bratonien-WebDAV-Test: generated-by-piwigo-i.php');
header('Content-Type: '.$content_type);
header('Content-Length: '.strlen($body));
header('Cache-Control: no-store');
http_response_code($status);
echo $body;
}
finally
{
$cleanup();
}