mirror of
https://github.com/Terranom674/Piwigo_Bratonien_Tools.git
synced 2026-09-19 10:34:30 +00:00
Compare commits
16 Commits
9eb38d7dcf
...
238c06be33
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
238c06be33 | ||
|
|
792e8eb7d2 | ||
|
|
d489bd7979 | ||
|
|
e8a5f5f0f7 | ||
|
|
ecc7665ed3 | ||
|
|
0d3764f043 | ||
|
|
81b3b31689 | ||
|
|
dcd1b9fb66 | ||
|
|
72a89a4636 | ||
|
|
2e03cc50d8 | ||
|
|
d2f171718e | ||
|
|
403b1df43f | ||
|
|
38e6ebdb19 | ||
|
|
474acf1de3 | ||
|
|
fe3c7fede2 | ||
|
|
ec801b88d2 |
@@ -4,9 +4,14 @@ if (!defined('PHPWG_ROOT_PATH'))
|
||||
die('Hacking attempt!');
|
||||
}
|
||||
|
||||
function bratonien_tools_nc_connector_systemctl_value(array $args)
|
||||
function bratonien_tools_nc_connector_systemctl_run(array $args)
|
||||
{
|
||||
if (!function_exists('proc_open')) return '';
|
||||
$result = array('exit'=>-1, 'stdout'=>'', 'stderr'=>'');
|
||||
if (!function_exists('proc_open'))
|
||||
{
|
||||
$result['stderr'] = 'proc_open ist in PHP nicht verfügbar.';
|
||||
return $result;
|
||||
}
|
||||
|
||||
$command = array_merge(array('/usr/bin/systemctl'), $args);
|
||||
$spec = array(
|
||||
@@ -16,13 +21,38 @@ function bratonien_tools_nc_connector_systemctl_value(array $args)
|
||||
);
|
||||
$environment = array_merge($_ENV, array('LC_ALL'=>'C','LANG'=>'C'));
|
||||
$process = @proc_open($command, $spec, $pipes, null, $environment);
|
||||
if (!is_resource($process)) return '';
|
||||
$stdout = stream_get_contents($pipes[1]);
|
||||
stream_get_contents($pipes[2]);
|
||||
if (!is_resource($process))
|
||||
{
|
||||
$result['stderr'] = 'systemctl konnte nicht gestartet werden.';
|
||||
return $result;
|
||||
}
|
||||
|
||||
$result['stdout'] = trim((string)stream_get_contents($pipes[1]));
|
||||
$result['stderr'] = trim((string)stream_get_contents($pipes[2]));
|
||||
fclose($pipes[1]);
|
||||
fclose($pipes[2]);
|
||||
$exit = proc_close($process);
|
||||
return $exit === 0 ? trim((string)$stdout) : '';
|
||||
$result['exit'] = (int)proc_close($process);
|
||||
return $result;
|
||||
}
|
||||
|
||||
function bratonien_tools_nc_connector_systemctl_value(array $args)
|
||||
{
|
||||
$result = bratonien_tools_nc_connector_systemctl_run($args);
|
||||
return $result['exit'] === 0 ? $result['stdout'] : '';
|
||||
}
|
||||
|
||||
function bratonien_tools_nc_connector_run_now()
|
||||
{
|
||||
$service = 'bratonien-nc-connector.service';
|
||||
$result = bratonien_tools_nc_connector_systemctl_run(array('start','--no-block',$service));
|
||||
if ($result['exit'] !== 0)
|
||||
{
|
||||
$detail = $result['stderr'] !== '' ? $result['stderr'] : $result['stdout'];
|
||||
if ($detail === '') $detail = 'systemctl Exit-Code '.$result['exit'];
|
||||
throw new RuntimeException('WebDAV-Abgleich konnte nicht gestartet werden: '.$detail);
|
||||
}
|
||||
|
||||
return array('message'=>'WebDAV-Abgleich wurde gestartet.');
|
||||
}
|
||||
|
||||
function bratonien_tools_nc_connector_parse_systemd_time($value)
|
||||
@@ -112,6 +142,15 @@ function bratonien_tools_nc_connector_last_status(array $connections)
|
||||
return $latest;
|
||||
}
|
||||
|
||||
function bratonien_tools_nc_connector_status_message(array $last)
|
||||
{
|
||||
if ((string)($last['state'] ?? '') === 'ok')
|
||||
{
|
||||
return 'WebDAV eingelesen und Piwigo synchronisiert';
|
||||
}
|
||||
return (string)($last['message'] ?? '');
|
||||
}
|
||||
|
||||
function bratonien_tools_nc_connector_system_status(array $connections = array())
|
||||
{
|
||||
$timer = 'bratonien-nc-connector.timer';
|
||||
@@ -143,7 +182,7 @@ function bratonien_tools_nc_connector_system_status(array $connections = array()
|
||||
'last_run_timestamp'=>(int)$last['timestamp'],
|
||||
'last_run_label'=>$last['timestamp'] > 0 ? date('d.m.Y H:i:s', (int)$last['timestamp']) : 'Nicht verfügbar',
|
||||
'last_run_state'=>(string)$last['state'],
|
||||
'last_run_message'=>(string)$last['message'],
|
||||
'last_run_message'=>bratonien_tools_nc_connector_status_message($last),
|
||||
'last_run_auth_mode'=>(string)$last['auth_mode'],
|
||||
'last_run_api_state'=>(string)$last['api_state'],
|
||||
'last_run_api_message'=>(string)$last['api_message'],
|
||||
|
||||
@@ -50,6 +50,7 @@ function bratonien_tools_get_tools()
|
||||
'nc_connector_create_webdav_parallel' => array('handler' => 'bratonien_tools_nc_connector_create_webdav_placeholder_from_wizard'),
|
||||
'nc_connector_delete' => array('handler' => 'bratonien_tools_nc_connector_delete_safe'),
|
||||
'nc_connector_update_name' => array('handler' => 'bratonien_tools_nc_connector_update_name'),
|
||||
'nc_connector_run_now' => array('handler' => 'bratonien_tools_nc_connector_run_now'),
|
||||
'nc_connector_wizard_scan' => array('handler' => 'bratonien_tools_nc_wizard_scan_webdav_first'),
|
||||
'nc_connector_wizard_directory_browse' => array('handler' => 'bratonien_tools_nc_wizard_directory_browse'),
|
||||
'nc_connector_wizard_directory_add' => array('handler' => 'bratonien_tools_nc_wizard_directory_add'),
|
||||
|
||||
274
include/webdav_materialize_runtime.inc.php
Normal file
274
include/webdav_materialize_runtime.inc.php
Normal file
@@ -0,0 +1,274 @@
|
||||
<?php
|
||||
if (!defined('PHPWG_ROOT_PATH'))
|
||||
{
|
||||
die('Hacking attempt!');
|
||||
}
|
||||
|
||||
function bratonien_tools_webdav_materialize_source_info($image_id)
|
||||
{
|
||||
static $cache = array();
|
||||
|
||||
$image_id = (int)$image_id;
|
||||
if ($image_id < 1) return null;
|
||||
if (array_key_exists($image_id, $cache)) return $cache[$image_id];
|
||||
|
||||
$result = pwg_query('SELECT path, coi FROM '.IMAGES_TABLE.' WHERE id='.$image_id.' LIMIT 1');
|
||||
if (!pwg_db_num_rows($result)) return $cache[$image_id] = null;
|
||||
|
||||
$row = pwg_db_fetch_assoc($result);
|
||||
$path = (string)($row['path'] ?? '');
|
||||
if ($path === '') return $cache[$image_id] = null;
|
||||
|
||||
$absolute = $path;
|
||||
if (strpos($absolute, '/') !== 0)
|
||||
{
|
||||
$absolute = PHPWG_ROOT_PATH.ltrim(preg_replace('#^\./#', '', $absolute), '/');
|
||||
}
|
||||
|
||||
$resolved = realpath($absolute);
|
||||
if ($resolved === false) return $cache[$image_id] = null;
|
||||
|
||||
$normalized = str_replace('\\', '/', $resolved);
|
||||
if (!preg_match('#/nc-webdav-source/connection-([0-9]+)/root-([0-9]+)/(.*)$#', $normalized, $match))
|
||||
{
|
||||
return $cache[$image_id] = null;
|
||||
}
|
||||
|
||||
$connection_id = (int)$match[1];
|
||||
$root_fileid = (int)$match[2];
|
||||
$relative_path = trim((string)$match[3], '/');
|
||||
if ($connection_id < 1 || $root_fileid < 1 || $relative_path === '')
|
||||
{
|
||||
return $cache[$image_id] = null;
|
||||
}
|
||||
|
||||
$table = defined('BRATONIEN_TOOLS_NC_CONNECTIONS_TABLE')
|
||||
? BRATONIEN_TOOLS_NC_CONNECTIONS_TABLE
|
||||
: $GLOBALS['prefixeTable'].'bratonien_tools_nc_connections';
|
||||
$connection_result = pwg_query('SELECT config_json FROM `'.$table.'` WHERE id='.$connection_id.' LIMIT 1');
|
||||
if (!pwg_db_num_rows($connection_result)) return $cache[$image_id] = null;
|
||||
|
||||
$connection_row = pwg_db_fetch_assoc($connection_result);
|
||||
$config = json_decode((string)$connection_row['config_json'], true);
|
||||
if (!is_array($config) || (string)($config['source_mode'] ?? '') !== 'webdav-placeholder')
|
||||
{
|
||||
return $cache[$image_id] = null;
|
||||
}
|
||||
|
||||
$root_found = false;
|
||||
$root_path = '';
|
||||
$roots = isset($config['roots']) && is_array($config['roots']) ? $config['roots'] : array();
|
||||
foreach ($roots as $root)
|
||||
{
|
||||
if ((int)($root['fileid'] ?? 0) === $root_fileid)
|
||||
{
|
||||
$root_found = true;
|
||||
$root_path = trim((string)($root['webdav_path'] ?? ''), '/');
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!$root_found) return $cache[$image_id] = null;
|
||||
|
||||
$webdav_path = trim($root_path === '' ? $relative_path : $root_path.'/'.$relative_path, '/');
|
||||
if ($webdav_path === '') return $cache[$image_id] = null;
|
||||
|
||||
$content_type = '';
|
||||
$size = 0;
|
||||
$etag = '';
|
||||
$state_dir = rtrim((string)($config['state_dir'] ?? ''), '/');
|
||||
if ($state_dir !== '')
|
||||
{
|
||||
$mapping_file = $state_dir.'/webdav-map.json';
|
||||
if (is_readable($mapping_file))
|
||||
{
|
||||
$mapping = json_decode((string)file_get_contents($mapping_file), true);
|
||||
if (is_array($mapping) && isset($mapping['files']) && is_array($mapping['files']))
|
||||
{
|
||||
$entry = $mapping['files'][$resolved] ?? $mapping['files'][$normalized] ?? null;
|
||||
if (is_array($entry) && (string)($entry['kind'] ?? '') === 'file')
|
||||
{
|
||||
$mapped_path = trim((string)($entry['webdav_path'] ?? ''), '/');
|
||||
if ($mapped_path !== '') $webdav_path = $mapped_path;
|
||||
$content_type = (string)($entry['content_type'] ?? '');
|
||||
$size = (int)($entry['size'] ?? 0);
|
||||
$etag = (string)($entry['etag'] ?? '');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $cache[$image_id] = array(
|
||||
'image_id'=>$image_id,
|
||||
'connection_id'=>$connection_id,
|
||||
'root_fileid'=>$root_fileid,
|
||||
'relative_path'=>$relative_path,
|
||||
'webdav_path'=>$webdav_path,
|
||||
'content_type'=>$content_type,
|
||||
'size'=>$size,
|
||||
'etag'=>$etag,
|
||||
'coi'=>$row['coi'] ?? null,
|
||||
);
|
||||
}
|
||||
|
||||
function bratonien_tools_webdav_materialize_image_url($image_id)
|
||||
{
|
||||
$info = bratonien_tools_webdav_materialize_source_info($image_id);
|
||||
if (!$info) return null;
|
||||
|
||||
$url = get_root_url().'plugins/'.BRATONIEN_TOOLS_ID.'/webdav-image.php?id='.(int)$image_id;
|
||||
if ($info['etag'] !== '') $url .= '&v='.rawurlencode(substr(sha1($info['etag']), 0, 12));
|
||||
return $url;
|
||||
}
|
||||
|
||||
function bratonien_tools_webdav_materialize_custom_params($key)
|
||||
{
|
||||
if (!class_exists('DerivativeParams') || !class_exists('SizingParams')) return null;
|
||||
|
||||
$tokens = explode('_', trim((string)$key));
|
||||
if (!$tokens || $tokens[0] === '') return null;
|
||||
|
||||
$parse_size = function($value)
|
||||
{
|
||||
if (!preg_match('/^[0-9]+(?:x[0-9]+)?$/', (string)$value)) return null;
|
||||
$parts = explode('x', (string)$value, 2);
|
||||
$width = (int)$parts[0];
|
||||
$height = count($parts) === 1 ? $width : (int)$parts[1];
|
||||
if ($width < 1 || $height < 1 || $width > 20000 || $height > 20000) return null;
|
||||
return array($width, $height);
|
||||
};
|
||||
|
||||
$token = array_shift($tokens);
|
||||
$crop = 0;
|
||||
$min_size = null;
|
||||
|
||||
if (isset($token[0]) && $token[0] === 's')
|
||||
{
|
||||
$size = $parse_size(substr($token, 1));
|
||||
}
|
||||
elseif (isset($token[0]) && $token[0] === 'e')
|
||||
{
|
||||
$crop = 1;
|
||||
$size = $min_size = $parse_size(substr($token, 1));
|
||||
}
|
||||
else
|
||||
{
|
||||
if (count($tokens) < 2) return null;
|
||||
$size = $parse_size($token);
|
||||
$crop_token = (string)array_shift($tokens);
|
||||
$min_size = $parse_size(array_shift($tokens));
|
||||
if (!preg_match('/^[a-z]$/', $crop_token) || $min_size === null) return null;
|
||||
$crop = function_exists('char_to_fraction') ? char_to_fraction($crop_token) : 0;
|
||||
}
|
||||
|
||||
if ($size === null) return null;
|
||||
|
||||
$params = new DerivativeParams(new SizingParams($size, $crop, $min_size));
|
||||
if (class_exists('ImageStdParams')) ImageStdParams::apply_global($params);
|
||||
return $params;
|
||||
}
|
||||
|
||||
function bratonien_tools_webdav_materialize_variant_from_params($params)
|
||||
{
|
||||
if (!is_object($params) || !class_exists('ImageStdParams')) return null;
|
||||
|
||||
$type = (string)($params->type ?? '');
|
||||
$defined = ImageStdParams::get_defined_type_map();
|
||||
if ($type !== '' && defined('IMG_CUSTOM') && $type !== IMG_CUSTOM && isset($defined[$type]))
|
||||
{
|
||||
return 'standard:'.$type;
|
||||
}
|
||||
|
||||
if (!method_exists($params, 'add_url_tokens')) return null;
|
||||
$tokens = array();
|
||||
$params->add_url_tokens($tokens);
|
||||
if (!$tokens) return null;
|
||||
|
||||
$key = implode('_', $tokens);
|
||||
if (!preg_match('/^[A-Za-z0-9_x-]+$/', $key)) return null;
|
||||
return 'custom:'.$key;
|
||||
}
|
||||
|
||||
function bratonien_tools_webdav_materialize_params_from_variant($variant)
|
||||
{
|
||||
$variant = trim((string)$variant);
|
||||
if ($variant === '' || !class_exists('ImageStdParams')) return null;
|
||||
|
||||
if (strpos($variant, 'standard:') === 0)
|
||||
{
|
||||
$type = substr($variant, strlen('standard:'));
|
||||
$defined = ImageStdParams::get_defined_type_map();
|
||||
return isset($defined[$type]) ? $defined[$type] : null;
|
||||
}
|
||||
|
||||
if (strpos($variant, 'custom:') === 0)
|
||||
{
|
||||
$key = substr($variant, strlen('custom:'));
|
||||
if (!preg_match('/^[A-Za-z0-9_x-]+$/', $key)) return null;
|
||||
return bratonien_tools_webdav_materialize_custom_params($key);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function bratonien_tools_webdav_materialize_b64url_encode($value)
|
||||
{
|
||||
return rtrim(strtr(base64_encode((string)$value), '+/', '-_'), '=');
|
||||
}
|
||||
|
||||
function bratonien_tools_webdav_materialize_after_signature($image_id, $variant, $after_url)
|
||||
{
|
||||
global $conf;
|
||||
$key = !empty($conf['secret_key']) ? $conf['secret_key'] : ($conf['db_password'] ?? 'bratonien-tools');
|
||||
return hash_hmac('sha256', (int)$image_id.'|'.(string)$variant.'|'.(string)$after_url, $key);
|
||||
}
|
||||
|
||||
function bratonien_tools_webdav_materialize_derivative_url($image_id, $variant, array $info, $after_url='')
|
||||
{
|
||||
$url = get_root_url().'plugins/'.BRATONIEN_TOOLS_ID.'/webdav-derivative.php?id='.(int)$image_id.'&variant='.rawurlencode($variant);
|
||||
if ($after_url !== '')
|
||||
{
|
||||
$url .= '&after='.rawurlencode(bratonien_tools_webdav_materialize_b64url_encode($after_url));
|
||||
$url .= '&sig='.rawurlencode(bratonien_tools_webdav_materialize_after_signature($image_id, $variant, $after_url));
|
||||
}
|
||||
if (!empty($info['etag'])) $url .= '&v='.rawurlencode(substr(sha1((string)$info['etag']), 0, 12));
|
||||
return $url;
|
||||
}
|
||||
|
||||
function bratonien_tools_filter_webdav_materialize_src_url($url, $src_image)
|
||||
{
|
||||
if (!is_object($src_image) || empty($src_image->id)) return $url;
|
||||
$webdav_url = bratonien_tools_webdav_materialize_image_url((int)$src_image->id);
|
||||
return $webdav_url ?: $url;
|
||||
}
|
||||
|
||||
function bratonien_tools_filter_webdav_materialize_derivative_url($url, $params, $src_image, $rel_url)
|
||||
{
|
||||
if (!is_object($src_image) || empty($src_image->id)) return $url;
|
||||
|
||||
$image_id = (int)$src_image->id;
|
||||
$info = bratonien_tools_webdav_materialize_source_info($image_id);
|
||||
if (!$info) return $url;
|
||||
|
||||
try
|
||||
{
|
||||
$derivative = new DerivativeImage($params, $src_image);
|
||||
if ($derivative->same_as_source())
|
||||
{
|
||||
$source_url = bratonien_tools_webdav_materialize_image_url($image_id);
|
||||
return $source_url ?: $url;
|
||||
}
|
||||
|
||||
$path = $derivative->get_path();
|
||||
if ($path !== '' && is_file($path) && is_readable($path)) return $url;
|
||||
|
||||
$variant = bratonien_tools_webdav_materialize_variant_from_params($params);
|
||||
if ($variant === null) return $url;
|
||||
|
||||
return bratonien_tools_webdav_materialize_derivative_url($image_id, $variant, $info, (string)$url);
|
||||
}
|
||||
catch (Throwable $e)
|
||||
{
|
||||
error_log('Bratonien WebDAV materialize derivative #'.$image_id.': '.$e->getMessage());
|
||||
return $url;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,40 @@
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
function initNcConnectorRunNow() {
|
||||
var section = document.getElementById('nc-connector');
|
||||
if (!section || section.querySelector('[data-nc-run-now]')) return;
|
||||
|
||||
var statusCard = section.querySelector('.bratonien-card');
|
||||
var token = section.querySelector('input[name="pwg_token"]');
|
||||
if (!statusCard || !token) return;
|
||||
|
||||
var actions = document.createElement('div');
|
||||
actions.className = 'bratonien-actions';
|
||||
actions.style.marginTop = '1rem';
|
||||
actions.setAttribute('data-nc-run-now', '1');
|
||||
|
||||
var form = document.createElement('form');
|
||||
form.method = 'post';
|
||||
|
||||
var tokenInput = document.createElement('input');
|
||||
tokenInput.type = 'hidden';
|
||||
tokenInput.name = 'pwg_token';
|
||||
tokenInput.value = token.value;
|
||||
|
||||
var button = document.createElement('button');
|
||||
button.className = 'buttonLike';
|
||||
button.type = 'submit';
|
||||
button.name = 'bratonien_tool';
|
||||
button.value = 'nc_connector_run_now';
|
||||
button.textContent = 'Jetzt abrufen';
|
||||
|
||||
form.appendChild(tokenInput);
|
||||
form.appendChild(button);
|
||||
actions.appendChild(form);
|
||||
statusCard.appendChild(actions);
|
||||
}
|
||||
|
||||
function initBratonienTabs() {
|
||||
var admin = document.querySelector('.bratonien-admin');
|
||||
if (!admin) return;
|
||||
@@ -113,9 +147,14 @@
|
||||
activate(initial, false);
|
||||
}
|
||||
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', initBratonienTabs);
|
||||
} else {
|
||||
function init() {
|
||||
initBratonienTabs();
|
||||
initNcConnectorRunNow();
|
||||
}
|
||||
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', init);
|
||||
} else {
|
||||
init();
|
||||
}
|
||||
})();
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<?php
|
||||
/*
|
||||
Plugin Name: Bratonien Tools
|
||||
Version: 0.9.6.8.5
|
||||
Version: 0.9.6.8.11
|
||||
Description: Erweiterbare Administrationswerkzeuge fuer die Bratonien-Piwigo-Installation.
|
||||
Plugin URI: https://github.com/Terranom674/Piwigo_Bratonien_Tools
|
||||
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/webdav_image_runtime.inc.php');
|
||||
require_once(BRATONIEN_TOOLS_PATH . 'include/webdav_materialize_runtime.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/batch_titles.inc.php');
|
||||
@@ -26,8 +27,8 @@ require_once(BRATONIEN_TOOLS_PATH . 'include/nc_productive_ws.inc.php');
|
||||
|
||||
add_event_handler('get_admin_plugin_menu_links', 'bratonien_tools_admin_menu');
|
||||
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_derivative_url', 'bratonien_tools_filter_webdav_derivative_url', EVENT_HANDLER_PRIORITY_NEUTRAL + 50, 4);
|
||||
add_event_handler('get_src_image_url', 'bratonien_tools_filter_webdav_materialize_src_url', EVENT_HANDLER_PRIORITY_NEUTRAL + 50, 2);
|
||||
add_event_handler('get_derivative_url', 'bratonien_tools_filter_webdav_materialize_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('element_set_global_action', 'bratonien_tools_batch_titles_apply', EVENT_HANDLER_PRIORITY_NEUTRAL, 2);
|
||||
add_event_handler('init', 'bratonien_tools_prepare_connector_private_import', EVENT_HANDLER_PRIORITY_NEUTRAL - 30);
|
||||
@@ -123,4 +124,4 @@ function bratonien_tools_admin_menu($menu)
|
||||
);
|
||||
return $menu;
|
||||
}
|
||||
?>
|
||||
?>
|
||||
|
||||
@@ -12,6 +12,7 @@ from pathlib import Path
|
||||
|
||||
ALLOWED = frozenset("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.")
|
||||
GERMAN = str.maketrans({"ä": "ae", "ö": "oe", "ü": "ue", "Ä": "Ae", "Ö": "Oe", "Ü": "Ue", "ß": "ss", "ẞ": "SS"})
|
||||
SHADOW_DIR_MODE = 0o777
|
||||
|
||||
|
||||
def safe_name(name: str) -> str:
|
||||
@@ -79,8 +80,13 @@ def preferred_target(source_key: str, raw_name: str, parent_target: Path, old_ma
|
||||
return safe_name(raw_name)
|
||||
|
||||
|
||||
def ensure_shadow_directory(path: Path) -> None:
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
path.chmod(SHADOW_DIR_MODE)
|
||||
|
||||
|
||||
def mirror_directory(source: Path, target: Path, source_key: str, target_key: Path, old_map: dict[str, str], new_map: dict[str, str]) -> None:
|
||||
target.mkdir(parents=True, exist_ok=True)
|
||||
ensure_shadow_directory(target)
|
||||
used: set[str] = set()
|
||||
for child in sorted(source.iterdir(), key=lambda item: (item.name.casefold(), item.name)):
|
||||
if child.is_symlink():
|
||||
@@ -116,7 +122,7 @@ def build(manifest: Path, destination: Path, state_file: Path) -> None:
|
||||
remove_tree(previous)
|
||||
if state_staging.exists():
|
||||
state_staging.unlink()
|
||||
staging.mkdir(parents=True)
|
||||
ensure_shadow_directory(staging)
|
||||
|
||||
try:
|
||||
used_roots: set[str] = set()
|
||||
|
||||
@@ -14,6 +14,10 @@
|
||||
<span class="bratonien-label">Nächster Lauf</span><strong data-nc-next-run>{if $nc_system_available}{$NC_CONNECTOR.system.next_run_label|escape:html}{else}Nicht verfügbar{/if}</strong>
|
||||
</div>
|
||||
{if $nc_system_available && $NC_CONNECTOR.system.last_run_message}<p class="bratonien-base-note">Letztes Ergebnis: <strong>{$NC_CONNECTOR.system.last_run_message|escape:html}</strong></p>{/if}
|
||||
<form method="post" class="bratonien-actions" style="margin-top:.75rem">
|
||||
<input type="hidden" name="pwg_token" value="{$PWG_TOKEN|escape:html}">
|
||||
<button class="buttonLike" type="submit" name="bratonien_tool" value="nc_connector_run_now"{if $NC_CONNECTOR.connection_count < 1} disabled{/if}>Jetzt abrufen</button>
|
||||
</form>
|
||||
{if $nc_system_available && $NC_CONNECTOR.system.last_run_api_state == 'error'}<p class="bratonien-main-cache__warning"><strong>API:</strong> {$NC_CONNECTOR.system.last_run_api_message|escape:html}</p>{/if}
|
||||
{if $nc_system_available && $NC_CONNECTOR.system.last_run_fallback_state == 'error'}<p class="bratonien-main-cache__warning"><strong>Fallback:</strong> {$NC_CONNECTOR.system.last_run_fallback_message|escape:html}</p>{/if}
|
||||
{if $nc_system_available && $NC_CONNECTOR.system.last_run_error_detail}<details><summary>Technische Fehlerdetails</summary><p class="bratonien-main-cache__warning">{$NC_CONNECTOR.system.last_run_error_detail|escape:html}</p></details>{/if}
|
||||
|
||||
368
webdav-derivative.php
Normal file
368
webdav-derivative.php
Normal file
@@ -0,0 +1,368 @@
|
||||
<?php
|
||||
define('PHPWG_ROOT_PATH', '../../');
|
||||
include_once(PHPWG_ROOT_PATH.'include/common.inc.php');
|
||||
require_once(PHPWG_ROOT_PATH.'include/derivative.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_materialize_runtime.inc.php');
|
||||
|
||||
function bratonien_tools_webdav_derivative_debug($request_id, $event, array $fields=array())
|
||||
{
|
||||
$parts = array('[BRAT-WD '.$request_id.']', $event);
|
||||
foreach ($fields as $key => $value)
|
||||
{
|
||||
if (is_bool($value)) $value = $value ? '1' : '0';
|
||||
elseif ($value === null) $value = 'NULL';
|
||||
elseif (is_array($value) || is_object($value)) $value = json_encode($value);
|
||||
$parts[] = $key.'='.str_replace(array("\r", "\n"), array('\\r', '\\n'), (string)$value);
|
||||
}
|
||||
error_log(implode(' ', $parts));
|
||||
}
|
||||
|
||||
function bratonien_tools_webdav_derivative_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_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_quote_path($path)
|
||||
{
|
||||
$parts = array_values(array_filter(explode('/', trim((string)$path, '/')), 'strlen'));
|
||||
return implode('/', array_map('rawurlencode', $parts));
|
||||
}
|
||||
|
||||
function bratonien_tools_webdav_derivative_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_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_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-Materialize',
|
||||
));
|
||||
$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_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_call_i($url, &$status, &$detail=null)
|
||||
{
|
||||
$detail = '';
|
||||
$status = 500;
|
||||
$ch = curl_init($url);
|
||||
curl_setopt_array($ch, array(
|
||||
CURLOPT_FOLLOWLOCATION => false,
|
||||
CURLOPT_CONNECTTIMEOUT => 10,
|
||||
CURLOPT_TIMEOUT => 180,
|
||||
CURLOPT_RETURNTRANSFER => false,
|
||||
CURLOPT_FAILONERROR => false,
|
||||
CURLOPT_USERAGENT => 'Bratonien-Tools-WebDAV-Materialize-Gate',
|
||||
CURLOPT_WRITEFUNCTION => function($ch, $data) { return strlen($data); },
|
||||
));
|
||||
$ok = curl_exec($ch);
|
||||
$errno = curl_errno($ch);
|
||||
$error = curl_error($ch);
|
||||
$status = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
curl_close($ch);
|
||||
if ($ok === 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;
|
||||
}
|
||||
|
||||
function bratonien_tools_webdav_derivative_after_url($encoded)
|
||||
{
|
||||
$encoded = trim((string)$encoded);
|
||||
if ($encoded === '') return null;
|
||||
$raw = strtr($encoded, '-_', '+/');
|
||||
$padding = strlen($raw) % 4;
|
||||
if ($padding) $raw .= str_repeat('=', 4 - $padding);
|
||||
$url = base64_decode($raw, true);
|
||||
if (!is_string($url) || $url === '' || preg_match('/[\r\n]/', $url)) return null;
|
||||
if (strpos($url, '//') === 0) return null;
|
||||
if (preg_match('#^https?://#i', $url))
|
||||
{
|
||||
$root_parts = parse_url(get_absolute_root_url());
|
||||
$url_parts = parse_url($url);
|
||||
if (!is_array($root_parts) || !is_array($url_parts)) return null;
|
||||
if (strcasecmp((string)($root_parts['scheme'] ?? ''), (string)($url_parts['scheme'] ?? '')) !== 0) return null;
|
||||
if (strcasecmp((string)($root_parts['host'] ?? ''), (string)($url_parts['host'] ?? '')) !== 0) return null;
|
||||
if ((int)($root_parts['port'] ?? 0) !== (int)($url_parts['port'] ?? 0)) return null;
|
||||
return $url;
|
||||
}
|
||||
if (strpos($url, ':') !== false && !preg_match('#^[A-Za-z0-9_./?&=%+-]+$#', $url)) return null;
|
||||
return $url;
|
||||
}
|
||||
|
||||
function bratonien_tools_webdav_derivative_needs_after_redirect($url)
|
||||
{
|
||||
if (!is_string($url) || $url === '') return false;
|
||||
return strpos($url, '/plugins/'.BRATONIEN_TOOLS_ID.'/watermark.php') !== false
|
||||
|| strpos($url, 'plugins/'.BRATONIEN_TOOLS_ID.'/watermark.php') === 0;
|
||||
}
|
||||
|
||||
function bratonien_tools_webdav_derivative_serve($path)
|
||||
{
|
||||
clearstatcache(true, $path);
|
||||
if (!is_file($path) || !is_readable($path)) bratonien_tools_webdav_derivative_abort(500, 'Piwigo-Derivat ist nicht lesbar.');
|
||||
$size = @getimagesize($path);
|
||||
$content_type = is_array($size) && !empty($size['mime']) ? (string)$size['mime'] : 'application/octet-stream';
|
||||
header('Content-Type: '.$content_type);
|
||||
header('Content-Length: '.(int)filesize($path));
|
||||
header('Cache-Control: public, max-age=31536000');
|
||||
header('X-Content-Type-Options: nosniff');
|
||||
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'HEAD') readfile($path);
|
||||
exit;
|
||||
}
|
||||
|
||||
$image_id = (int)($_GET['id'] ?? 0);
|
||||
$variant = trim((string)($_GET['variant'] ?? ''));
|
||||
$request_id = bin2hex(random_bytes(4));
|
||||
bratonien_tools_webdav_derivative_debug($request_id, 'start', array('image_id'=>$image_id, 'variant'=>$variant));
|
||||
|
||||
$after_url = bratonien_tools_webdav_derivative_after_url($_GET['after'] ?? '');
|
||||
$after_sig = trim((string)($_GET['sig'] ?? ''));
|
||||
if ($image_id < 1) bratonien_tools_webdav_derivative_abort(400, 'Bild-ID fehlt.');
|
||||
if ($variant === '') bratonien_tools_webdav_derivative_abort(400, 'Derivat-Variante fehlt.');
|
||||
if ($after_url !== null)
|
||||
{
|
||||
$expected_sig = bratonien_tools_webdav_materialize_after_signature($image_id, $variant, $after_url);
|
||||
if ($after_sig === '' || !hash_equals($expected_sig, $after_sig)) $after_url = null;
|
||||
}
|
||||
$redirect_after = bratonien_tools_webdav_derivative_needs_after_redirect($after_url) ? $after_url : null;
|
||||
|
||||
$permission_condition = get_sql_condition_FandF(array('forbidden_categories'=>'category_id'), null, true);
|
||||
$access_result = pwg_query('SELECT 1 FROM '.IMAGE_CATEGORY_TABLE.' WHERE image_id='.$image_id.' AND '.$permission_condition.' LIMIT 1');
|
||||
if (!pwg_db_num_rows($access_result)) bratonien_tools_webdav_derivative_abort(403, 'Kein Zugriff auf dieses Bild.');
|
||||
$result = pwg_query('SELECT * FROM '.IMAGES_TABLE.' WHERE id='.$image_id.' LIMIT 1');
|
||||
if (!pwg_db_num_rows($result)) bratonien_tools_webdav_derivative_abort(404, 'Bild nicht gefunden.');
|
||||
$image_row = pwg_db_fetch_assoc($result);
|
||||
|
||||
$raw_source_path = (string)($image_row['path'] ?? '');
|
||||
$absolute_source_path = $raw_source_path;
|
||||
if ($absolute_source_path !== '' && strpos($absolute_source_path, '/') !== 0)
|
||||
{
|
||||
$absolute_source_path = PHPWG_ROOT_PATH.ltrim(preg_replace('#^\./#', '', $absolute_source_path), '/');
|
||||
}
|
||||
bratonien_tools_webdav_derivative_debug($request_id, 'source_before_resolve', array(
|
||||
'path'=>$raw_source_path,
|
||||
'is_link'=>$absolute_source_path !== '' && is_link($absolute_source_path),
|
||||
'realpath'=>$absolute_source_path !== '' ? (realpath($absolute_source_path) ?: 'FALSE') : 'EMPTY',
|
||||
));
|
||||
|
||||
$source = bratonien_tools_webdav_materialize_source_info($image_id);
|
||||
if (!$source)
|
||||
{
|
||||
bratonien_tools_webdav_derivative_debug($request_id, 'source_resolve_failed');
|
||||
bratonien_tools_webdav_derivative_abort(404, 'Keine WebDAV-Quelle fuer dieses Bild gefunden.');
|
||||
}
|
||||
bratonien_tools_webdav_derivative_debug($request_id, 'source_resolved', array('connection_id'=>$source['connection_id'] ?? 0, 'root_fileid'=>$source['root_fileid'] ?? 0, 'webdav_path'=>$source['webdav_path'] ?? ''));
|
||||
|
||||
$params = bratonien_tools_webdav_materialize_params_from_variant($variant);
|
||||
if (!$params) bratonien_tools_webdav_derivative_abort(400, 'Unbekannte Derivat-Variante.');
|
||||
$real_src = new SrcImage($image_row);
|
||||
$real_derivative = new DerivativeImage($params, $real_src);
|
||||
if ($real_derivative->same_as_source())
|
||||
{
|
||||
$source_url = bratonien_tools_webdav_materialize_image_url($image_id);
|
||||
if (!$source_url) bratonien_tools_webdav_derivative_abort(404, 'WebDAV-Original konnte nicht bestimmt werden.');
|
||||
header('Location: '.$source_url, true, 302);
|
||||
exit;
|
||||
}
|
||||
|
||||
$target_path = $real_derivative->get_path();
|
||||
$derivative_root = PHPWG_ROOT_PATH.PWG_DERIVATIVE_DIR;
|
||||
if ($target_path === '' || strpos($target_path, $derivative_root) !== 0) bratonien_tools_webdav_derivative_abort(500, 'Ungueltiger Piwigo-Derivatpfad.');
|
||||
if (is_file($target_path) && is_readable($target_path))
|
||||
{
|
||||
bratonien_tools_webdav_derivative_debug($request_id, 'target_exists', array('target'=>$target_path));
|
||||
if ($redirect_after !== null) { header('Location: '.$redirect_after, true, 302); exit; }
|
||||
bratonien_tools_webdav_derivative_serve($target_path);
|
||||
}
|
||||
|
||||
$shadow_path = $raw_source_path;
|
||||
if ($shadow_path === '') bratonien_tools_webdav_derivative_abort(500, 'Piwigo-Quellpfad fehlt.');
|
||||
if (strpos($shadow_path, '/') !== 0) $shadow_path = PHPWG_ROOT_PATH.ltrim(preg_replace('#^\./#', '', $shadow_path), '/');
|
||||
$shadow_normalized = str_replace('\\', '/', $shadow_path);
|
||||
if (!preg_match('#/_data/bratonien-tools/nc-webdav-gallery/connection-'.(int)$source['connection_id'].'/#', $shadow_normalized)) bratonien_tools_webdav_derivative_abort(500, 'Piwigo-Quellpfad liegt nicht im WebDAV-Shadow-Baum.');
|
||||
if (!is_link($shadow_path)) bratonien_tools_webdav_derivative_abort(500, 'WebDAV-Shadow-Quelle ist kein Placeholder-Symlink.');
|
||||
|
||||
$placeholder_target = realpath($shadow_path);
|
||||
$placeholder_normalized = $placeholder_target === false ? '' : str_replace('\\', '/', $placeholder_target);
|
||||
if ($placeholder_target === false || !preg_match('#/nc-webdav-source/connection-'.(int)$source['connection_id'].'/root-'.(int)$source['root_fileid'].'/#', $placeholder_normalized)) bratonien_tools_webdav_derivative_abort(500, 'WebDAV-Placeholder-Ziel ist ungueltig.');
|
||||
|
||||
$shadow_dir = dirname($shadow_path);
|
||||
if (!is_dir($shadow_dir) || !is_writable($shadow_dir)) bratonien_tools_webdav_derivative_abort(500, 'WebDAV-Shadow-Verzeichnis ist fuer PHP nicht beschreibbar.');
|
||||
$upload_dir = rtrim((string)($GLOBALS['conf']['upload_dir'] ?? './upload'), '/');
|
||||
$work_rel_dir = $upload_dir.'/bratonien-webdav-materialize';
|
||||
$work_root = PHPWG_ROOT_PATH.$work_rel_dir;
|
||||
if (!is_dir($work_root) && !@mkdir($work_root, 0755, true)) bratonien_tools_webdav_derivative_abort(500, 'WebDAV-Materialisierungsbereich konnte nicht angelegt werden.');
|
||||
if (!is_writable($work_root)) bratonien_tools_webdav_derivative_abort(500, 'WebDAV-Materialisierungsbereich ist fuer PHP nicht beschreibbar.');
|
||||
|
||||
$lock_path = $work_root.'/image-'.$image_id.'.lock';
|
||||
bratonien_tools_webdav_derivative_debug($request_id, 'waiting_lock', array('lock'=>$lock_path, 'is_link'=>is_link($shadow_path), 'realpath'=>realpath($shadow_path) ?: 'FALSE'));
|
||||
$lock = @fopen($lock_path, 'c');
|
||||
if (!$lock || !flock($lock, LOCK_EX))
|
||||
{
|
||||
if ($lock) fclose($lock);
|
||||
bratonien_tools_webdav_derivative_abort(503, 'WebDAV-Materialisierungslock konnte nicht gesetzt werden.');
|
||||
}
|
||||
bratonien_tools_webdav_derivative_debug($request_id, 'lock_acquired', array('is_link'=>is_link($shadow_path), 'realpath'=>realpath($shadow_path) ?: 'FALSE'));
|
||||
|
||||
clearstatcache(true, $target_path);
|
||||
if (is_file($target_path) && is_readable($target_path))
|
||||
{
|
||||
bratonien_tools_webdav_derivative_debug($request_id, 'target_created_while_waiting', array('target'=>$target_path));
|
||||
@flock($lock, LOCK_UN); @fclose($lock);
|
||||
if ($redirect_after !== null) { header('Location: '.$redirect_after, true, 302); exit; }
|
||||
bratonien_tools_webdav_derivative_serve($target_path);
|
||||
}
|
||||
|
||||
$token = getmypid().'-'.bin2hex(random_bytes(6));
|
||||
$download_path = $work_root.'/source-'.$image_id.'-'.$token.'.tmp';
|
||||
$staging_path = $shadow_path.'.bratonien-'.$token.'.tmp';
|
||||
$placeholder_backup = $shadow_path.'.bratonien-placeholder';
|
||||
$swapped = false;
|
||||
$cleaned = false;
|
||||
|
||||
$cleanup = function() use (&$cleaned, &$swapped, $shadow_path, $staging_path, $placeholder_backup, $download_path, $lock, $request_id)
|
||||
{
|
||||
if ($cleaned) return;
|
||||
$cleaned = true;
|
||||
if ($swapped)
|
||||
{
|
||||
if (is_file($shadow_path) && !is_link($shadow_path)) @unlink($shadow_path);
|
||||
if (is_link($placeholder_backup)) @rename($placeholder_backup, $shadow_path);
|
||||
$swapped = false;
|
||||
}
|
||||
if (is_file($staging_path) || is_link($staging_path)) @unlink($staging_path);
|
||||
if (is_file($download_path)) @unlink($download_path);
|
||||
bratonien_tools_webdav_derivative_debug($request_id, 'restored', array('is_link'=>is_link($shadow_path), 'realpath'=>realpath($shadow_path) ?: 'FALSE'));
|
||||
@flock($lock, LOCK_UN);
|
||||
@fclose($lock);
|
||||
};
|
||||
register_shutdown_function($cleanup);
|
||||
|
||||
try
|
||||
{
|
||||
if (is_link($placeholder_backup)) bratonien_tools_webdav_derivative_abort(503, 'WebDAV-Placeholder-Backup existiert bereits; vorheriger Materialisierungslauf ist nicht sauber abgeschlossen.');
|
||||
$detail = '';
|
||||
$download_start = microtime(true);
|
||||
if (!bratonien_tools_webdav_derivative_download($source, $download_path, $detail)) bratonien_tools_webdav_derivative_abort(502, $detail);
|
||||
bratonien_tools_webdav_derivative_debug($request_id, 'download_done', array('ms'=>round((microtime(true)-$download_start)*1000, 1), 'bytes'=>@filesize($download_path) ?: 0));
|
||||
|
||||
if (!@copy($download_path, $staging_path)) bratonien_tools_webdav_derivative_abort(500, 'Original konnte nicht in den WebDAV-Shadow-Baum kopiert werden.');
|
||||
@chmod($staging_path, 0644);
|
||||
if (@getimagesize($staging_path) === false) bratonien_tools_webdav_derivative_abort(500, 'Materialisierte Shadow-Quelle ist kein gueltiges Bild.');
|
||||
|
||||
bratonien_tools_webdav_derivative_debug($request_id, 'swap_begin', array('placeholder'=>$placeholder_target));
|
||||
if (!@rename($shadow_path, $placeholder_backup)) bratonien_tools_webdav_derivative_abort(500, 'WebDAV-Placeholder konnte nicht temporaer gesichert werden.');
|
||||
if (!@rename($staging_path, $shadow_path))
|
||||
{
|
||||
@rename($placeholder_backup, $shadow_path);
|
||||
bratonien_tools_webdav_derivative_abort(500, 'Materialisiertes Original konnte nicht am Piwigo-Quellpfad aktiviert werden.');
|
||||
}
|
||||
$swapped = true;
|
||||
clearstatcache(true, $shadow_path);
|
||||
bratonien_tools_webdav_derivative_debug($request_id, 'swapped', array('is_link'=>is_link($shadow_path), 'realpath'=>realpath($shadow_path) ?: 'FALSE'));
|
||||
if (!is_file($shadow_path) || is_link($shadow_path) || @getimagesize($shadow_path) === false) bratonien_tools_webdav_derivative_abort(500, 'Piwigo-Quellpfad enthaelt nach Materialisierung kein gueltiges Original.');
|
||||
|
||||
$inner_url = bratonien_tools_webdav_derivative_inner_url($target_path);
|
||||
if ($inner_url === null) bratonien_tools_webdav_derivative_abort(500, 'Piwigo-i.php-URL konnte nicht bestimmt werden.');
|
||||
$inner_status = 500;
|
||||
$i_start = microtime(true);
|
||||
bratonien_tools_webdav_derivative_debug($request_id, 'i_start', array('url'=>$inner_url));
|
||||
$i_ok = bratonien_tools_webdav_derivative_call_i($inner_url, $inner_status, $detail);
|
||||
bratonien_tools_webdav_derivative_debug($request_id, 'i_done', array('status'=>$inner_status, 'ok'=>$i_ok, 'ms'=>round((microtime(true)-$i_start)*1000, 1), 'detail'=>$detail));
|
||||
if (!$i_ok) bratonien_tools_webdav_derivative_abort(502, $detail);
|
||||
|
||||
clearstatcache(true, $target_path);
|
||||
$final_size = @getimagesize($target_path);
|
||||
if (!is_file($target_path) || !is_readable($target_path) || !is_array($final_size)) bratonien_tools_webdav_derivative_abort(500, 'Piwigo hat kein gueltiges finales Derivat erzeugt.');
|
||||
|
||||
$cleanup();
|
||||
bratonien_tools_webdav_derivative_debug($request_id, 'serve', array('target'=>$target_path, 'width'=>$final_size[0] ?? 0, 'height'=>$final_size[1] ?? 0));
|
||||
if ($redirect_after !== null) { header('Location: '.$redirect_after, true, 302); exit; }
|
||||
bratonien_tools_webdav_derivative_serve($target_path);
|
||||
}
|
||||
finally
|
||||
{
|
||||
$cleanup();
|
||||
}
|
||||
@@ -8,6 +8,7 @@ if (!defined('BRATONIEN_TOOLS_PATH'))
|
||||
define('BRATONIEN_TOOLS_PATH', PHPWG_ROOT_PATH.'plugins/'.BRATONIEN_TOOLS_ID.'/');
|
||||
}
|
||||
require_once(BRATONIEN_TOOLS_PATH.'include/webdav_image_runtime.inc.php');
|
||||
require_once(BRATONIEN_TOOLS_PATH.'include/webdav_materialize_runtime.inc.php');
|
||||
|
||||
function bratonien_tools_webdav_image_abort($status, $message)
|
||||
{
|
||||
@@ -48,7 +49,7 @@ $permission_condition = get_sql_condition_FandF(array('forbidden_categories'=>'c
|
||||
$access_result = pwg_query('SELECT 1 FROM '.IMAGE_CATEGORY_TABLE.' WHERE image_id='.$image_id.' AND '.$permission_condition.' LIMIT 1');
|
||||
if (!pwg_db_num_rows($access_result)) bratonien_tools_webdav_image_abort(403, 'Kein Zugriff auf dieses Bild.');
|
||||
|
||||
$source = bratonien_tools_webdav_image_source_info($image_id);
|
||||
$source = bratonien_tools_webdav_materialize_source_info($image_id);
|
||||
if (!$source) bratonien_tools_webdav_image_abort(404, 'Keine WebDAV-Quelle für dieses Bild gefunden.');
|
||||
|
||||
if (!empty($_GET['preview']))
|
||||
@@ -120,7 +121,7 @@ $options = array(
|
||||
CURLOPT_USERPWD => $user.':'.$password,
|
||||
CURLOPT_RETURNTRANSFER => false,
|
||||
CURLOPT_FAILONERROR => false,
|
||||
CURLOPT_USERAGENT => 'Bratonien-Tools-WebDAV-Image/0.9.6.1',
|
||||
CURLOPT_USERAGENT => 'Bratonien-Tools-WebDAV-Image/0.9.6.8.6',
|
||||
CURLOPT_HEADERFUNCTION => function($ch, $line)
|
||||
{
|
||||
$length = strlen($line);
|
||||
|
||||
Reference in New Issue
Block a user