Compare commits

..

2 Commits

Author SHA1 Message Date
Terranom674
531bffa973 Bereinige versehentlich angelegte Leerdatei 2026-08-19 22:17:02 +02:00
Terranom674
5ed53dca8d noop 2026-08-19 22:15:46 +02:00
12 changed files with 111 additions and 455 deletions

View File

@@ -28,34 +28,18 @@ function bratonien_tools_nc_connector_webdav_site_id(array $connection)
return (int)$row['id']; return (int)$row['id'];
} }
function bratonien_tools_nc_connector_gallery_db_prefix(array $connection)
{
$config = isset($connection['config']) && is_array($connection['config']) ? $connection['config'] : array();
$gallery_root = rtrim((string)($config['parallel_gallery_root'] ?? ''), '/');
$piwigo_root = rtrim(PHPWG_ROOT_PATH, '/');
if ($gallery_root === '' || strpos($gallery_root, $piwigo_root.'/') !== 0) return '';
$relative = ltrim(substr($gallery_root, strlen($piwigo_root)), '/');
return $relative === '' ? '' : './'.rtrim($relative, '/').'/';
}
function bratonien_tools_nc_connector_remove_webdav_piwigo_content(array $connection) function bratonien_tools_nc_connector_remove_webdav_piwigo_content(array $connection)
{ {
$site_id = bratonien_tools_nc_connector_webdav_site_id($connection);
if ($site_id < 1) return array('site_id'=>0, 'images'=>0);
include_once(PHPWG_ROOT_PATH.'admin/include/functions.php'); include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
$site_id = bratonien_tools_nc_connector_webdav_site_id($connection);
$db_prefix = bratonien_tools_nc_connector_gallery_db_prefix($connection);
if ($db_prefix === '') return array('site_id'=>$site_id, 'images'=>0);
$escaped = pwg_db_real_escape_string(addcslashes($db_prefix, '_%\\'));
$image_rows = array(); $image_rows = array();
$result = pwg_query( $query = '\nSELECT DISTINCT i.id, i.path, i.representative_ext\n FROM '.IMAGES_TABLE.' AS i\n LEFT JOIN '.CATEGORIES_TABLE.' AS sc ON sc.id = i.storage_category_id\n LEFT JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON ic.image_id = i.id\n LEFT JOIN '.CATEGORIES_TABLE.' AS vc ON vc.id = ic.category_id\n WHERE sc.site_id = '.$site_id.' OR vc.site_id = '.$site_id.'\n;';
"SELECT id, path, representative_ext FROM ".IMAGES_TABLE. $result = pwg_query($query);
" WHERE path LIKE '".$escaped."%' ESCAPE '\\\\'"
);
while ($row = pwg_db_fetch_assoc($result)) while ($row = pwg_db_fetch_assoc($result))
{ {
if (strpos((string)$row['path'], $db_prefix) !== 0) continue;
$row['id'] = (int)$row['id']; $row['id'] = (int)$row['id'];
$image_rows[$row['id']] = $row; $image_rows[$row['id']] = $row;
} }
@@ -72,14 +56,20 @@ function bratonien_tools_nc_connector_remove_webdav_piwigo_content(array $connec
} }
} }
delete_site($site_id);
if ($image_rows) if ($image_rows)
{ {
delete_elements(array_map('intval', array_keys($image_rows)), false); $ids = array_keys($image_rows);
} $remaining = query2array(
'SELECT id FROM '.IMAGES_TABLE.' WHERE id IN ('.implode(',', array_map('intval', $ids)).')',
if ($site_id > 0) null,
{ 'id'
delete_site($site_id); );
if ($remaining)
{
delete_elements(array_map('intval', $remaining), false);
}
} }
invalidate_user_cache(true); invalidate_user_cache(true);
@@ -120,7 +110,14 @@ function bratonien_tools_nc_connector_delete_safe()
@file_put_contents($status_dir.'/deleted-'.$id, date('c')."\n", LOCK_EX); @file_put_contents($status_dir.'/deleted-'.$id, date('c')."\n", LOCK_EX);
} }
if ((int)$cleanup['site_id'] > 0)
{
return array(
'message'=>'Verbindung wurde gelöscht. Die zugehörigen Piwigo-Alben und '.(int)$cleanup['images'].' Bilder wurden aus Piwigo entfernt. Nextcloud-Dateien blieben unverändert.',
);
}
return array( return array(
'message'=>'Verbindung wurde gelöscht. '.(int)$cleanup['images'].' eindeutig zu dieser Verbindung gehörende Bilder wurden aus Piwigo entfernt. Nextcloud-Dateien blieben unverändert.', 'message'=>'Verbindung wurde gelöscht. Verbliebene Laufzeitdaten werden automatisch bereinigt. Quelldateien blieben unverändert.',
); );
} }

View File

@@ -27,72 +27,6 @@ function bratonien_tools_runtime_category_id()
return 0; return 0;
} }
function bratonien_tools_watermark_album_cover_category($src_image, $category_id=null)
{
static $map = null;
if ($map === null)
{
$map = new SplObjectStorage();
}
if (!is_object($src_image))
{
return 0;
}
if ($category_id !== null)
{
$category_id = (int)$category_id;
if ($category_id > 0)
{
$map[$src_image] = $category_id;
}
return $category_id;
}
return $map->contains($src_image) ? (int)$map[$src_image] : 0;
}
function bratonien_tools_watermark_prepare_album_overview($thumbnails)
{
if (!is_array($thumbnails))
{
return $thumbnails;
}
foreach ($thumbnails as &$thumbnail)
{
$category_id = (int)($thumbnail['id'] ?? $thumbnail['ID'] ?? 0);
if ($category_id < 1 || empty($thumbnail['representative']['src_image']) || !is_object($thumbnail['representative']['src_image']))
{
continue;
}
// Ein Repraesentantenbild kann fuer mehrere Alben verwendet werden. Piwigo
// reicht in der Albumuebersicht aber nur das SrcImage an get_derivative_url
// weiter. Deshalb bekommt jedes Album-Cover eine eigene SrcImage-Instanz,
// damit seine konkrete Albumregel erhalten bleibt.
$src_image = clone $thumbnail['representative']['src_image'];
$thumbnail['representative']['src_image'] = $src_image;
bratonien_tools_watermark_album_cover_category($src_image, $category_id);
}
unset($thumbnail);
return $thumbnails;
}
function bratonien_tools_runtime_derivative_category_id($src_image)
{
$category_id = bratonien_tools_runtime_category_id();
if ($category_id > 0)
{
return $category_id;
}
return bratonien_tools_watermark_album_cover_category($src_image);
}
function bratonien_tools_runtime_effective_rule($category_id) function bratonien_tools_runtime_effective_rule($category_id)
{ {
static $categories = null; static $categories = null;
@@ -296,7 +230,7 @@ function bratonien_tools_filter_derivative_url($url, $params, $src_image, $rel_u
return $url; return $url;
} }
$rule = bratonien_tools_runtime_effective_rule(bratonien_tools_runtime_derivative_category_id($src_image)); $rule = bratonien_tools_runtime_effective_rule(bratonien_tools_runtime_category_id());
if ($rule['mode'] !== 'profile' || empty($rule['profile_id'])) if ($rule['mode'] !== 'profile' || empty($rule['profile_id']))
{ {
return $url; return $url;

View File

@@ -0,0 +1,36 @@
<?php
if (!defined('PHPWG_ROOT_PATH'))
{
die('Hacking attempt!');
}
function bratonien_tools_filter_webdav_gallery_derivative_url($url, $params, $src_image, $rel_url)
{
if (!is_object($src_image) || empty($src_image->id) || empty($src_image->rel_path)) return $url;
$source_path = str_replace('\\', '/', (string)$src_image->rel_path);
if (!preg_match('#/nc-webdav-source/connection-[0-9]+/root-[0-9]+/.+$#', $source_path))
{
return $url;
}
try
{
$derivative = new DerivativeImage($params, $src_image);
if (!$derivative->same_as_source())
{
$path = $derivative->get_path();
if ($path !== '' && is_file($path) && is_readable($path))
{
return $url;
}
}
}
catch (Throwable $e)
{
error_log('Bratonien WebDAV gallery derivative lookup #'.(int)$src_image->id.': '.$e->getMessage());
}
$preview_url = bratonien_tools_webdav_image_url((int)$src_image->id, true);
return $preview_url ?: $url;
}

View File

@@ -1,7 +1,7 @@
<?php <?php
/* /*
Plugin Name: Bratonien Tools Plugin Name: Bratonien Tools
Version: 0.9.7.17 Version: 0.9.7.8
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
@@ -17,6 +17,7 @@ define('BRATONIEN_TOOLS_PATH', PHPWG_PLUGINS_PATH . BRATONIEN_TOOLS_ID . '/');
require_once(BRATONIEN_TOOLS_PATH . 'include/watermark_runtime.inc.php'); require_once(BRATONIEN_TOOLS_PATH . 'include/watermark_runtime.inc.php');
require_once(BRATONIEN_TOOLS_PATH . 'include/webdav_image_runtime.inc.php'); require_once(BRATONIEN_TOOLS_PATH . 'include/webdav_image_runtime.inc.php');
require_once(BRATONIEN_TOOLS_PATH . 'include/webdav_gallery_runtime.inc.php');
require_once(BRATONIEN_TOOLS_PATH . 'include/public_selection.inc.php'); require_once(BRATONIEN_TOOLS_PATH . 'include/public_selection.inc.php');
require_once(BRATONIEN_TOOLS_PATH . 'include/picture_navigation.inc.php'); require_once(BRATONIEN_TOOLS_PATH . 'include/picture_navigation.inc.php');
require_once(BRATONIEN_TOOLS_PATH . 'include/batch_titles.inc.php'); require_once(BRATONIEN_TOOLS_PATH . 'include/batch_titles.inc.php');
@@ -27,12 +28,11 @@ require_once(BRATONIEN_TOOLS_PATH . 'include/nc_productive_ws.inc.php');
require_once(BRATONIEN_TOOLS_PATH . 'include/nc_connector_scheduler.inc.php'); require_once(BRATONIEN_TOOLS_PATH . 'include/nc_connector_scheduler.inc.php');
add_event_handler('get_admin_plugin_menu_links', 'bratonien_tools_admin_menu'); add_event_handler('get_admin_plugin_menu_links', 'bratonien_tools_admin_menu');
add_event_handler('loc_end_index_category_thumbnails', 'bratonien_tools_watermark_prepare_album_overview');
add_event_handler('get_derivative_url', 'bratonien_tools_filter_derivative_url', EVENT_HANDLER_PRIORITY_NEUTRAL, 4); add_event_handler('get_derivative_url', 'bratonien_tools_filter_derivative_url', EVENT_HANDLER_PRIORITY_NEUTRAL, 4);
add_event_handler('get_src_image_url', 'bratonien_tools_filter_webdav_src_url', EVENT_HANDLER_PRIORITY_NEUTRAL + 50, 2); add_event_handler('get_src_image_url', 'bratonien_tools_filter_webdav_src_url', EVENT_HANDLER_PRIORITY_NEUTRAL + 50, 2);
add_event_handler('get_derivative_url', 'bratonien_tools_filter_webdav_gallery_derivative_url', EVENT_HANDLER_PRIORITY_NEUTRAL + 50, 4);
add_event_handler('loc_end_element_set_global', 'bratonien_tools_batch_titles_register_action'); add_event_handler('loc_end_element_set_global', 'bratonien_tools_batch_titles_register_action');
add_event_handler('element_set_global_action', 'bratonien_tools_batch_titles_apply', EVENT_HANDLER_PRIORITY_NEUTRAL, 2); add_event_handler('element_set_global_action', 'bratonien_tools_batch_titles_apply', EVENT_HANDLER_PRIORITY_NEUTRAL, 2);
add_event_handler('init', 'bratonien_tools_watermark_cache_upgrade', EVENT_HANDLER_PRIORITY_NEUTRAL - 40);
add_event_handler('init', 'bratonien_tools_prepare_connector_private_import', EVENT_HANDLER_PRIORITY_NEUTRAL - 30); add_event_handler('init', 'bratonien_tools_prepare_connector_private_import', EVENT_HANDLER_PRIORITY_NEUTRAL - 30);
add_event_handler('init', 'bratonien_tools_prepare_private_album_permissions', EVENT_HANDLER_PRIORITY_NEUTRAL - 20); add_event_handler('init', 'bratonien_tools_prepare_private_album_permissions', EVENT_HANDLER_PRIORITY_NEUTRAL - 20);
add_event_handler('init', 'bratonien_tools_preserve_private_album_access', EVENT_HANDLER_PRIORITY_NEUTRAL - 10); add_event_handler('init', 'bratonien_tools_preserve_private_album_access', EVENT_HANDLER_PRIORITY_NEUTRAL - 10);

View File

@@ -1,6 +1,5 @@
#!/usr/bin/env bash #!/usr/bin/env bash
set -Eeuo pipefail set -Eeuo pipefail
umask 0002
CONFIG_FILE="${PIWIGO_CONFIG:-}" CONFIG_FILE="${PIWIGO_CONFIG:-}"
[[ -n "$CONFIG_FILE" && -r "$CONFIG_FILE" ]] || { echo "WebDAV-Konfiguration fehlt: ${CONFIG_FILE:-<leer>}" >&2; exit 1; } [[ -n "$CONFIG_FILE" && -r "$CONFIG_FILE" ]] || { echo "WebDAV-Konfiguration fehlt: ${CONFIG_FILE:-<leer>}" >&2; exit 1; }
@@ -23,47 +22,6 @@ exec 9>"$LOCK_FILE"
flock -n 9 || exit 0 flock -n 9 || exit 0
PREVIEW_CACHE="$PIWIGO_ROOT/_data/bratonien-tools/nc-webdav-preview/connection-$CONNECTION_ID" PREVIEW_CACHE="$PIWIGO_ROOT/_data/bratonien-tools/nc-webdav-preview/connection-$CONNECTION_ID"
SOURCE_CACHE="$PIWIGO_ROOT/_data/bratonien-tools/nc-webdav-gallery/connection-$CONNECTION_ID"
DERIVATIVE_CACHE="$PIWIGO_ROOT/_data/i/_data/bratonien-tools/nc-webdav-gallery/connection-$CONNECTION_ID"
PIWIGO_DATA="$PIWIGO_ROOT/_data"
normalize_connector_cache_permissions() {
[[ -d "$PIWIGO_DATA" ]] || return 0
local data_uid data_gid current_uid path
data_uid="$(stat -c '%u' "$PIWIGO_DATA")"
data_gid="$(stat -c '%g' "$PIWIGO_DATA")"
current_uid="$(id -u)"
for path in "$SOURCE_CACHE" "$PREVIEW_CACHE" "$DERIVATIVE_CACHE"; do
[[ -e "$path" ]] || continue
if [[ "$current_uid" -eq 0 ]]; then
chown -R "$data_uid:$data_gid" -- "$path"
fi
if ! find "$path" -type d -exec chmod 2775 {} + 2>/dev/null; then
echo "Hinweis: Verzeichnisrechte konnten ohne Root-Rechte nicht vollständig repariert werden: $path" >&2
fi
if ! find "$path" -type f -exec chmod 0664 {} + 2>/dev/null; then
echo "Hinweis: Dateirechte konnten ohne Root-Rechte nicht vollständig repariert werden: $path" >&2
fi
done
}
# Altbestände aus früheren root/systemd-Läufen werden repariert, sobald dieser
# Lauf mit ausreichenden Rechten ausgeführt wird. Bei normalen Webserver-Läufen
# werden zumindest alle eigenen Dateien gruppenschreibbar gehalten.
normalize_connector_cache_permissions
# Dieser Medienlauf wird erst nach einem erfolgreichen WebDAV-Aufbau und einer
# erfolgreichen Piwigo-Synchronisierung gestartet. Deshalb darf erst hier aus
# "lokale Connector-Datei fehlt" auf eine in Nextcloud entfernte Freigabe/Datei
# geschlossen werden. Bei einer nicht erreichbaren Verbindung wird dieser Block
# niemals ausgeführt und der vorhandene Piwigo-Bestand bleibt unverändert.
php "$SCRIPT_DIR/cleanup-missing-webdav-images.php" \
--piwigo-root="$PIWIGO_ROOT" \
--connection-id="$CONNECTION_ID"
php "$SCRIPT_DIR/lib/precache-webdav-previews.php" \ php "$SCRIPT_DIR/lib/precache-webdav-previews.php" \
--mapping="$WEBDAV_MAPPING_FILE" \ --mapping="$WEBDAV_MAPPING_FILE" \
@@ -75,5 +33,3 @@ php "$SCRIPT_DIR/lib/precache-webdav-previews.php" \
php "$SCRIPT_DIR/lib/build-webdav-derivatives.php" \ php "$SCRIPT_DIR/lib/build-webdav-derivatives.php" \
--piwigo-root="$PIWIGO_ROOT" \ --piwigo-root="$PIWIGO_ROOT" \
--connection-id="$CONNECTION_ID" --connection-id="$CONNECTION_ID"
normalize_connector_cache_permissions

View File

@@ -1,124 +0,0 @@
#!/usr/bin/env php
<?php
if (PHP_SAPI !== 'cli')
{
fwrite(STDERR, "CLI only\n");
exit(1);
}
$options = getopt('', array('piwigo-root:', 'connection-id:'));
$piwigo_root = rtrim((string)($options['piwigo-root'] ?? ''), '/');
$connection_id = (int)($options['connection-id'] ?? 0);
if ($piwigo_root === '' || $connection_id < 1)
{
fwrite(STDERR, "Parameter --piwigo-root und --connection-id werden benoetigt.\n");
exit(1);
}
$db_config = $piwigo_root.'/local/config/database.inc.php';
if (!is_readable($db_config))
{
fwrite(STDERR, "Piwigo-Datenbankkonfiguration ist nicht lesbar.\n");
exit(1);
}
$conf = array();
$prefixeTable = 'piwigo_';
require $db_config;
foreach (array('db_host','db_user','db_password','db_base') as $key)
{
if (!isset($conf[$key]))
{
fwrite(STDERR, "Piwigo-Datenbankkonfiguration ist unvollstaendig: $key\n");
exit(1);
}
}
$db = new mysqli($conf['db_host'], $conf['db_user'], $conf['db_password'], $conf['db_base']);
if ($db->connect_errno)
{
fwrite(STDERR, "Piwigo-Datenbank ist nicht erreichbar: ".$db->connect_error."\n");
exit(1);
}
$db->set_charset('utf8mb4');
$table = $prefixeTable.'bratonien_tools_nc_connections';
$result = $db->query('SELECT config_json FROM `'.$table.'` WHERE id='.$connection_id.' LIMIT 1');
if (!$result || !$result->num_rows)
{
fwrite(STDERR, "Connector-Verbindung #$connection_id wurde nicht gefunden.\n");
exit(1);
}
$config = json_decode((string)$result->fetch_assoc()['config_json'], true);
if (!is_array($config) || (string)($config['source_mode'] ?? '') !== 'webdav-placeholder')
{
echo "Keine WebDAV-Bereinigung erforderlich.\n";
exit(0);
}
$gallery_root = rtrim((string)($config['parallel_gallery_root'] ?? ''), '/');
if ($gallery_root === '' || strpos($gallery_root, $piwigo_root.'/') !== 0)
{
fwrite(STDERR, "Verbindungseigene Gallery-Root ist ungueltig.\n");
exit(1);
}
$relative = ltrim(substr($gallery_root, strlen($piwigo_root)), '/');
$db_prefix = './'.rtrim($relative, '/').'/';
$escaped_prefix = $db->real_escape_string(addcslashes($db_prefix, "_%\\"));
$images_table = $prefixeTable.'images';
$query = "SELECT id, path FROM `{$images_table}` WHERE path LIKE '{$escaped_prefix}%' ESCAPE '\\\\'";
$rows = $db->query($query);
if (!$rows)
{
fwrite(STDERR, "Connector-Bilder konnten nicht gelesen werden: ".$db->error."\n");
exit(1);
}
$missing_ids = array();
while ($row = $rows->fetch_assoc())
{
$path = (string)$row['path'];
if (strpos($path, $db_prefix) !== 0)
{
continue;
}
$absolute = $piwigo_root.'/'.ltrim(preg_replace('#^\\./#', '', $path), '/');
if (!is_file($absolute))
{
$missing_ids[] = (int)$row['id'];
}
}
$db->close();
if (!$missing_ids)
{
echo "WebDAV-Bereinigung: keine fehlenden Piwigo-Bilder.\n";
exit(0);
}
// Erst jetzt Piwigo bootstrappen. Dieser Prozess wird nur nach einem erfolgreich
// abgeschlossenen WebDAV-Abruf gestartet. Eine nicht erreichbare Verbindung kann
// daher niemals ueber diesen Pfad Bilder loeschen.
define('PHPWG_ROOT_PATH', $piwigo_root.'/');
$_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/cleanup-missing-webdav-images.php';
$_SERVER['PHP_SELF'] = $_SERVER['SCRIPT_NAME'];
$_SERVER['QUERY_STRING'] = '';
$_SERVER['HTTPS'] = 'off';
require_once(PHPWG_ROOT_PATH.'include/common.inc.php');
include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
delete_elements($missing_ids, false);
update_category('all');
invalidate_user_cache(true);
echo 'WebDAV-Bereinigung: '.count($missing_ids)." nicht mehr freigegebene/ vorhandene Bilder aus Piwigo entfernt.\n";

View File

@@ -34,7 +34,7 @@ function fetch_remote_blob($url, $user, $password)
CURLOPT_HTTPAUTH => CURLAUTH_BASIC, CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
CURLOPT_USERPWD => $user.':'.$password, CURLOPT_USERPWD => $user.':'.$password,
CURLOPT_FAILONERROR => false, CURLOPT_FAILONERROR => false,
CURLOPT_USERAGENT => 'Bratonien-Tools-WebDAV-Precache/0.9.7.16', CURLOPT_USERAGENT => 'Bratonien-Tools-WebDAV-Precache/0.9.7.1',
); );
bratonien_tools_nc_transport_apply_curl($options, $url); bratonien_tools_nc_transport_apply_curl($options, $url);
curl_setopt_array($ch, $options); curl_setopt_array($ch, $options);
@@ -52,11 +52,12 @@ function fetch_remote_blob($url, $user, $password)
function preview_extension_for_entry(array $entry) function preview_extension_for_entry(array $entry)
{ {
$content_type = strtolower(trim((string)($entry['content_type'] ?? '')));
$path = strtolower((string)($entry['webdav_path'] ?? '')); $path = strtolower((string)($entry['webdav_path'] ?? ''));
$extension = strtolower(pathinfo($path, PATHINFO_EXTENSION)); if ($content_type === 'image/png' || preg_match('/\.png$/', $path))
if ($extension === 'png') return 'png'; {
if ($extension === 'gif') return 'gif'; return 'png';
if ($extension === 'webp') return 'webp'; }
return 'jpg'; return 'jpg';
} }
@@ -67,7 +68,7 @@ function preview_target_for_entry($cache_dir, $key, array $entry)
function remove_other_preview_format($cache_dir, $key, $keep_target) function remove_other_preview_format($cache_dir, $key, $keep_target)
{ {
foreach (array('jpg', 'png', 'gif', 'webp') as $ext) foreach (array('jpg', 'png', 'webp') as $ext)
{ {
$candidate = $cache_dir.'/'.$key.'.'.$ext; $candidate = $cache_dir.'/'.$key.'.'.$ext;
if ($candidate !== $keep_target && is_file($candidate)) @unlink($candidate); if ($candidate !== $keep_target && is_file($candidate)) @unlink($candidate);
@@ -89,19 +90,13 @@ function write_preview_imagick($blob, $target, $extension)
{ {
$image->setImageFormat('png'); $image->setImageFormat('png');
} }
elseif ($extension === 'gif')
{
$image->setImageFormat('gif');
}
elseif ($extension === 'webp')
{
$image->setImageFormat('webp');
$image->setImageCompressionQuality(BRATONIEN_WEBDAV_PREVIEW_JPEG_QUALITY);
}
else else
{ {
$image->setImageBackgroundColor('white'); $image->setImageBackgroundColor('white');
if (method_exists($image, 'mergeImageLayers')) $image = $image->mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN); if (method_exists($image, 'mergeImageLayers'))
{
$image = $image->mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN);
}
$image->setImageFormat('jpeg'); $image->setImageFormat('jpeg');
$image->setImageCompression(Imagick::COMPRESSION_JPEG); $image->setImageCompression(Imagick::COMPRESSION_JPEG);
$image->setImageCompressionQuality(BRATONIEN_WEBDAV_PREVIEW_JPEG_QUALITY); $image->setImageCompressionQuality(BRATONIEN_WEBDAV_PREVIEW_JPEG_QUALITY);
@@ -136,7 +131,7 @@ function write_preview_gd($blob, $target, $extension)
try try
{ {
if (in_array($extension, array('png', 'gif', 'webp'), true)) if ($extension === 'png')
{ {
imagealphablending($preview, false); imagealphablending($preview, false);
imagesavealpha($preview, true); imagesavealpha($preview, true);
@@ -154,12 +149,10 @@ function write_preview_gd($blob, $target, $extension)
fail_preview('GD konnte das Preview nicht skalieren.'); fail_preview('GD konnte das Preview nicht skalieren.');
} }
if ($extension === 'png') $written = imagepng($preview, $target, 6); $written = $extension === 'png'
elseif ($extension === 'gif') $written = function_exists('imagegif') ? imagegif($preview, $target) : false; ? imagepng($preview, $target, 6)
elseif ($extension === 'webp') $written = function_exists('imagewebp') ? imagewebp($preview, $target, BRATONIEN_WEBDAV_PREVIEW_JPEG_QUALITY) : false; : imagejpeg($preview, $target, BRATONIEN_WEBDAV_PREVIEW_JPEG_QUALITY);
else $written = imagejpeg($preview, $target, BRATONIEN_WEBDAV_PREVIEW_JPEG_QUALITY); if (!$written) fail_preview('GD konnte das Preview nicht schreiben.');
if (!$written) fail_preview('GD konnte das Preview im Format '.$extension.' nicht schreiben.');
} }
finally finally
{ {
@@ -175,7 +168,7 @@ function write_preview_gd($blob, $target, $extension)
function write_preview($blob, $target, $extension) function write_preview($blob, $target, $extension)
{ {
$dir = dirname($target); $dir = dirname($target);
if (!is_dir($dir) && !mkdir($dir, 0775, true) && !is_dir($dir)) fail_preview('Preview-Verzeichnis konnte nicht angelegt werden.'); if (!is_dir($dir) && !mkdir($dir, 0755, true) && !is_dir($dir)) fail_preview('Preview-Verzeichnis konnte nicht angelegt werden.');
if (class_exists('Imagick')) if (class_exists('Imagick'))
{ {
@@ -197,48 +190,7 @@ function write_preview($blob, $target, $extension)
@unlink($target); @unlink($target);
fail_preview('Das erzeugte Preview ist ungültig.'); fail_preview('Das erzeugte Preview ist ungültig.');
} }
@chmod($target, 0664); @chmod($target, 0644);
}
function local_source_is_hydrated($source_path, $preview)
{
if (!is_file($source_path) || !is_readable($source_path)) return false;
$source_size = @getimagesize($source_path);
$preview_size = @getimagesize($preview);
if (!is_array($source_size) || !is_array($preview_size)) return false;
if ((int)$source_size[0] !== (int)$preview_size[0] || (int)$source_size[1] !== (int)$preview_size[1]) return false;
$source_bytes = @filesize($source_path);
$preview_bytes = @filesize($preview);
return $source_bytes !== false && $preview_bytes !== false && (int)$source_bytes === (int)$preview_bytes;
}
function hydrate_local_source($source_path, $preview)
{
$normalized = str_replace('\\', '/', (string)$source_path);
if (!preg_match('#/nc-webdav-source/connection-[0-9]+/root-[0-9]+/#', $normalized))
{
fail_preview('Unsicherer lokaler Connector-Quellpfad: '.$source_path);
}
if (!is_file($preview) || !is_readable($preview)) fail_preview('Preview für lokale Quelle fehlt: '.$preview);
if (local_source_is_hydrated($source_path, $preview)) return false;
$dir = dirname($source_path);
if (!is_dir($dir) && !mkdir($dir, 0775, true) && !is_dir($dir)) fail_preview('Lokales Connector-Verzeichnis konnte nicht angelegt werden: '.$dir);
$tmp = $source_path.'.bratonien-next-'.getmypid();
if (!@copy($preview, $tmp)) fail_preview('Preview konnte nicht in lokale Piwigo-Quelle kopiert werden: '.$source_path);
@chmod($tmp, 0664);
$mtime = @filemtime($preview);
if ($mtime) @touch($tmp, $mtime);
if (!@rename($tmp, $source_path))
{
@unlink($tmp);
fail_preview('Lokale Piwigo-Quelle konnte nicht ersetzt werden: '.$source_path);
}
clearstatcache(true, $source_path);
$size = @getimagesize($source_path);
if (!is_array($size) || empty($size[0]) || empty($size[1])) fail_preview('Lokale Piwigo-Quelle ist nach dem Ersetzen ungültig: '.$source_path);
return true;
} }
try try
@@ -260,8 +212,8 @@ try
$mapping = json_decode((string)file_get_contents($mapping_file), true); $mapping = json_decode((string)file_get_contents($mapping_file), true);
if (!is_array($mapping) || !isset($mapping['files']) || !is_array($mapping['files'])) fail_preview('WebDAV-Mapping ist ungültig.'); if (!is_array($mapping) || !isset($mapping['files']) || !is_array($mapping['files'])) fail_preview('WebDAV-Mapping ist ungültig.');
if (!is_dir($cache_dir) && !mkdir($cache_dir, 0775, true) && !is_dir($cache_dir)) fail_preview('Preview-Cache konnte nicht angelegt werden.'); if (!is_dir($cache_dir) && !mkdir($cache_dir, 0755, true) && !is_dir($cache_dir)) fail_preview('Preview-Cache konnte nicht angelegt werden.');
@chmod($cache_dir, 2775); @chmod($cache_dir, 0755);
$state_file = $cache_dir.'/state.json'; $state_file = $cache_dir.'/state.json';
$old_state = array(); $old_state = array();
@@ -274,10 +226,9 @@ try
$new_state = array(); $new_state = array();
$generated = 0; $generated = 0;
$cached = 0; $cached = 0;
$hydrated = 0;
$errors = 0; $errors = 0;
foreach ($mapping['files'] as $local_path=>$entry) foreach ($mapping['files'] as $entry)
{ {
if (!is_array($entry) || (string)($entry['kind'] ?? '') !== 'file') continue; if (!is_array($entry) || (string)($entry['kind'] ?? '') !== 'file') continue;
$webdav_path = trim((string)($entry['webdav_path'] ?? ''), '/'); $webdav_path = trim((string)($entry['webdav_path'] ?? ''), '/');
@@ -294,29 +245,26 @@ try
'version' => BRATONIEN_WEBDAV_PREVIEW_VERSION, 'version' => BRATONIEN_WEBDAV_PREVIEW_VERSION,
); );
$old = $old_state[$key] ?? null;
if (
is_file($target)
&& is_array($old)
&& (string)($old['etag'] ?? '') === $etag
&& (string)($old['format'] ?? '') === $extension
&& (int)($old['version'] ?? 0) === BRATONIEN_WEBDAV_PREVIEW_VERSION
)
{
$cached++;
continue;
}
try try
{ {
$old = $old_state[$key] ?? null; $url = $base_url.'/remote.php/dav/files/'.rawurlencode($user).'/'.quote_webdav_path($webdav_path);
$valid_cached = is_file($target) $blob = fetch_remote_blob($url, $user, $password);
&& is_array($old) write_preview($blob, $target, $extension);
&& (string)($old['etag'] ?? '') === $etag remove_other_preview_format($cache_dir, $key, $target);
&& (string)($old['format'] ?? '') === $extension $generated++;
&& (int)($old['version'] ?? 0) === BRATONIEN_WEBDAV_PREVIEW_VERSION;
if (!$valid_cached)
{
$url = $base_url.'/remote.php/dav/files/'.rawurlencode($user).'/'.quote_webdav_path($webdav_path);
$blob = fetch_remote_blob($url, $user, $password);
write_preview($blob, $target, $extension);
remove_other_preview_format($cache_dir, $key, $target);
$generated++;
}
else
{
$cached++;
}
if (hydrate_local_source((string)$local_path, $target)) $hydrated++;
} }
catch (Throwable $e) catch (Throwable $e)
{ {
@@ -329,14 +277,14 @@ try
{ {
if (!is_file($file) || basename($file) === 'state.json') continue; if (!is_file($file) || basename($file) === 'state.json') continue;
$name = basename($file); $name = basename($file);
if (!preg_match('/^([a-f0-9]{40})\.(jpg|png|gif|webp)$/', $name, $m)) continue; if (!preg_match('/^([a-f0-9]{40})\.(jpg|png|webp)$/', $name, $m)) continue;
if (!isset($new_state[$m[1]])) @unlink($file); if (!isset($new_state[$m[1]])) @unlink($file);
} }
file_put_contents($state_file, json_encode($new_state, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT)."\n", LOCK_EX); file_put_contents($state_file, json_encode($new_state, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT)."\n", LOCK_EX);
@chmod($state_file, 0664); @chmod($state_file, 0644);
echo 'WebDAV-Previews: erzeugt='.$generated.' vorhanden='.$cached.' lokale_quellen='.$hydrated.' fehler='.$errors."\n"; echo 'WebDAV-Previews: erzeugt='.$generated.' vorhanden='.$cached.' fehler='.$errors."\n";
exit($errors > 0 ? 1 : 0); exit($errors > 0 ? 1 : 0);
} }
catch (Throwable $e) catch (Throwable $e)

View File

@@ -1,36 +0,0 @@
#!/usr/bin/env bash
set -Eeuo pipefail
PIWIGO_ROOT="${1:-/var/www/piwigo}"
PIWIGO_ROOT="${PIWIGO_ROOT%/}"
DATA_DIR="$PIWIGO_ROOT/_data"
[[ -d "$DATA_DIR" ]] || { echo "Piwigo-_data wurde nicht gefunden: $DATA_DIR" >&2; exit 1; }
[[ "$(id -u)" -eq 0 ]] || { echo "Die Reparatur muss als root ausgeführt werden." >&2; exit 1; }
DATA_UID="$(stat -c '%u' "$DATA_DIR")"
DATA_GID="$(stat -c '%g' "$DATA_DIR")"
PATHS=(
"$DATA_DIR/bratonien-tools/nc-webdav-gallery"
"$DATA_DIR/bratonien-tools/nc-webdav-preview"
"$DATA_DIR/i/_data/bratonien-tools/nc-webdav-gallery"
"$DATA_DIR/i/bratonien-watermark"
)
found=0
for path in "${PATHS[@]}"; do
[[ -e "$path" ]] || continue
found=1
echo "Repariere: $path"
chown -R "$DATA_UID:$DATA_GID" -- "$path"
find "$path" -type d -exec chmod 2775 {} +
find "$path" -type f -exec chmod 0664 {} +
done
if [[ "$found" -eq 0 ]]; then
echo "Keine Bratonien-Cache-Verzeichnisse gefunden."
exit 0
fi
echo "Bratonien-Cache-Rechte wurden an $DATA_DIR angeglichen (UID $DATA_UID, GID $DATA_GID)."

View File

@@ -61,7 +61,6 @@ function bratonien_tools_save_album_rule()
))); )));
} }
bratonien_tools_clear_watermark_cache();
return array('message'=>'Albumregel gespeichert.'); return array('message'=>'Albumregel gespeichert.');
} }
@@ -98,6 +97,9 @@ function bratonien_tools_resolve_album_rule($category_id, array $categories, arr
$root = $by_id[$category_id] ?? null; $root = $by_id[$category_id] ?? null;
$is_private = $root && isset($root['status']) && $root['status'] === 'private'; $is_private = $root && isset($root['status']) && $root['status'] === 'private';
// Privat ist eine Vererbungsgrenze. Eine direkt auf diesem privaten Album
// gesetzte Regel bleibt moeglich, aber Regeln oeffentlicher Eltern duerfen
// nicht in ein privates Album hineinvererbt werden.
if ($is_private) if ($is_private)
{ {
if (isset($rules[$category_id])) if (isset($rules[$category_id]))

View File

@@ -128,7 +128,6 @@ function bratonien_tools_save_watermark_profile()
mass_inserts($table, array_keys($data), array($data)); mass_inserts($table, array_keys($data), array($data));
} }
bratonien_tools_clear_watermark_cache();
return array('message'=>'Wasserzeichenprofil gespeichert.'); return array('message'=>'Wasserzeichenprofil gespeichert.');
} }
@@ -159,7 +158,6 @@ function bratonien_tools_delete_watermark_profile()
} }
pwg_query('DELETE FROM '.bratonien_tools_table('watermark_profiles').' WHERE id='.$id); pwg_query('DELETE FROM '.bratonien_tools_table('watermark_profiles').' WHERE id='.$id);
bratonien_tools_clear_watermark_cache();
return array('message'=>'Wasserzeichenprofil geloescht.'); return array('message'=>'Wasserzeichenprofil geloescht.');
} }
@@ -176,7 +174,6 @@ function bratonien_tools_duplicate_watermark_profile()
$profile['name'] .= ' (Kopie)'; $profile['name'] .= ' (Kopie)';
$profile['created'] = date('Y-m-d H:i:s'); $profile['created'] = date('Y-m-d H:i:s');
mass_inserts(bratonien_tools_table('watermark_profiles'), array_keys($profile), array($profile)); mass_inserts(bratonien_tools_table('watermark_profiles'), array_keys($profile), array($profile));
bratonien_tools_clear_watermark_cache();
return array('message'=>'Wasserzeichenprofil dupliziert.'); return array('message'=>'Wasserzeichenprofil dupliziert.');
} }

View File

@@ -4,59 +4,6 @@ if (!defined('PHPWG_ROOT_PATH'))
die('Hacking attempt!'); die('Hacking attempt!');
} }
function bratonien_tools_watermark_cache_dir()
{
return PHPWG_ROOT_PATH.PWG_DERIVATIVE_DIR.'bratonien-watermark';
}
function bratonien_tools_remove_tree($path)
{
$path = rtrim((string)$path, DIRECTORY_SEPARATOR);
if ($path === '' || !file_exists($path)) return;
if (is_file($path) || is_link($path))
{
@unlink($path);
return;
}
foreach (scandir($path) ?: array() as $entry)
{
if ($entry === '.' || $entry === '..') continue;
bratonien_tools_remove_tree($path.DIRECTORY_SEPARATOR.$entry);
}
@rmdir($path);
}
function bratonien_tools_clear_watermark_cache()
{
$dir = bratonien_tools_watermark_cache_dir();
$derivative_root = realpath(PHPWG_ROOT_PATH.PWG_DERIVATIVE_DIR);
$parent = realpath(dirname($dir));
if ($derivative_root === false || $parent === false || $parent !== $derivative_root)
{
throw new RuntimeException('Wasserzeichen-Cachepfad ist ungueltig.');
}
if (is_dir($dir))
{
bratonien_tools_remove_tree($dir);
}
}
function bratonien_tools_watermark_cache_upgrade()
{
$version = '0.9.7.13';
if ((string)conf_get_param('bratonien_watermark_cache_version', '') === $version)
{
return;
}
bratonien_tools_clear_watermark_cache();
conf_update_param('bratonien_watermark_cache_version', $version);
}
function bratonien_tools_get_watermark_defaults() function bratonien_tools_get_watermark_defaults()
{ {
$defaults = conf_get_param('bratonien_watermark_defaults', null); $defaults = conf_get_param('bratonien_watermark_defaults', null);
@@ -93,7 +40,6 @@ function bratonien_tools_save_watermark_defaults()
); );
conf_update_param('bratonien_watermark_defaults', json_encode($config)); conf_update_param('bratonien_watermark_defaults', json_encode($config));
bratonien_tools_clear_watermark_cache();
return array('message'=>'Globale Wasserzeichenregeln gespeichert.'); return array('message'=>'Globale Wasserzeichenregeln gespeichert.');
} }

View File

@@ -121,7 +121,7 @@ $options = array(
CURLOPT_USERPWD => $user.':'.$password, CURLOPT_USERPWD => $user.':'.$password,
CURLOPT_RETURNTRANSFER => false, CURLOPT_RETURNTRANSFER => false,
CURLOPT_FAILONERROR => false, CURLOPT_FAILONERROR => false,
CURLOPT_USERAGENT => 'Bratonien-Tools-WebDAV-Image/0.9.7.16', CURLOPT_USERAGENT => 'Bratonien-Tools-WebDAV-Image/0.9.7.1',
CURLOPT_HEADERFUNCTION => function($ch, $line) CURLOPT_HEADERFUNCTION => function($ch, $line)
{ {
$length = strlen($line); $length = strlen($line);