mirror of
https://github.com/Terranom674/Piwigo_Bratonien_Tools.git
synced 2026-09-19 22:14:33 +00:00
Compare commits
22 Commits
992cb55714
...
fix/connec
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2ed84ad089 | ||
|
|
60c0a51f01 | ||
|
|
84d263b16b | ||
|
|
94c81789ed | ||
|
|
e3b1f06be3 | ||
|
|
15a3ceb01c | ||
|
|
0f5812a179 | ||
|
|
377b29a127 | ||
|
|
d9696172c5 | ||
|
|
3f2a85fb0b | ||
|
|
c882ba994b | ||
|
|
cd2c9e350b | ||
|
|
394f375e91 | ||
|
|
3b1ccd99a5 | ||
|
|
04d88cd40f | ||
|
|
a4f953551c | ||
|
|
b4161471ca | ||
|
|
71fdadb7f8 | ||
|
|
98134b5ab8 | ||
|
|
5f82f2ad71 | ||
|
|
494f8bf192 | ||
|
|
c46f9bb5bd |
19
.github/workflows/lint.yml
vendored
19
.github/workflows/lint.yml
vendored
@@ -25,6 +25,25 @@ jobs:
|
||||
php -l "$file"
|
||||
done < <(find . -type f -name '*.php' -print0)
|
||||
|
||||
- name: Doppelte Bratonien-Funktionen pruefen
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
duplicates="$(grep -RhoE 'function[[:space:]]+bratonien_tools_[A-Za-z0-9_]+' --include='*.php' . | awk '{print $2}' | sort | uniq -d || true)"
|
||||
if [[ -n "$duplicates" ]]; then
|
||||
echo "Doppelte globale Bratonien-Funktionen gefunden:" >&2
|
||||
printf '%s\n' "$duplicates" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Admin JavaScript Syntax pruefen
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
sed -n '/<script>/,/<\/script>/p' template/admin_tabs.tpl | sed '1d;$d' > /tmp/bratonien-admin-tabs.js
|
||||
node --check /tmp/bratonien-admin-tabs.js
|
||||
node --check js/nc_connector_edit_v2.js
|
||||
|
||||
- name: Python Syntax pruefen
|
||||
shell: bash
|
||||
run: |
|
||||
|
||||
338
include/nc_connector_edit.inc.php
Normal file
338
include/nc_connector_edit.inc.php
Normal file
@@ -0,0 +1,338 @@
|
||||
<?php
|
||||
if (!defined('PHPWG_ROOT_PATH'))
|
||||
{
|
||||
die('Hacking attempt!');
|
||||
}
|
||||
|
||||
function bratonien_tools_nc_connector_migration_state(array $connection)
|
||||
{
|
||||
$config = isset($connection['config']) && is_array($connection['config']) ? $connection['config'] : array();
|
||||
$credentials = bratonien_tools_nc_connector_scoped_secret($connection);
|
||||
$missing = array();
|
||||
|
||||
if (trim((string)($config['nextcloud_url'] ?? '')) === '') $missing[] = 'Nextcloud-Adresse';
|
||||
if (trim((string)($credentials['nextcloud_user'] ?? '')) === '') $missing[] = 'Nextcloud-Benutzer';
|
||||
if ((string)($credentials['nextcloud_password'] ?? '') === '') $missing[] = 'Nextcloud-Passwort';
|
||||
if (trim((string)($credentials['api_key_id'] ?? '')) === '') $missing[] = 'Piwigo-API-Schluessel-ID';
|
||||
if (trim((string)($credentials['api_key_secret'] ?? '')) === '') $missing[] = 'Piwigo-API-Geheimnis';
|
||||
|
||||
return array(
|
||||
'ready'=>!$missing,
|
||||
'missing'=>$missing,
|
||||
);
|
||||
}
|
||||
|
||||
function bratonien_tools_nc_connector_validate_nextcloud_access($base_url, $username, $password)
|
||||
{
|
||||
$base_url = bratonien_tools_nc_wizard_normalize_url($base_url);
|
||||
$username = trim((string)$username);
|
||||
$password = (string)$password;
|
||||
if ($username === '' || $password === '') throw new RuntimeException('Nextcloud-Benutzer und Passwort werden benoetigt.');
|
||||
|
||||
$status_response = bratonien_tools_nc_wizard_http($base_url.'/status.php');
|
||||
if ($status_response['status'] < 200 || $status_response['status'] >= 300)
|
||||
{
|
||||
throw new RuntimeException('Die Nextcloud-Adresse konnte nicht bestaetigt werden.');
|
||||
}
|
||||
$status = json_decode((string)$status_response['body'], true);
|
||||
if (!is_array($status) || empty($status['installed']))
|
||||
{
|
||||
throw new RuntimeException('Unter dieser Adresse wurde keine installierte Nextcloud erkannt.');
|
||||
}
|
||||
|
||||
$user_response = bratonien_tools_nc_wizard_http(
|
||||
$base_url.'/ocs/v2.php/cloud/user?format=json',
|
||||
$username,
|
||||
$password,
|
||||
array('OCS-APIRequest: true')
|
||||
);
|
||||
if ($user_response['status'] === 401 || $user_response['status'] === 403)
|
||||
{
|
||||
throw new RuntimeException('Nextcloud hat Benutzername oder Passwort abgelehnt.');
|
||||
}
|
||||
if ($user_response['status'] < 200 || $user_response['status'] >= 300)
|
||||
{
|
||||
throw new RuntimeException('Nextcloud ist erreichbar, aber der Benutzerzugang konnte nicht geprueft werden.');
|
||||
}
|
||||
$user_data = bratonien_tools_nc_wizard_ocs_data($user_response['body']);
|
||||
$resolved = trim((string)($user_data['id'] ?? $username));
|
||||
|
||||
return array(
|
||||
'base_url'=>$base_url,
|
||||
'username'=>$resolved !== '' ? $resolved : $username,
|
||||
);
|
||||
}
|
||||
|
||||
function bratonien_tools_nc_connector_validate_scoped_api($api_key_id, $api_key_secret)
|
||||
{
|
||||
$api_key_id = trim((string)$api_key_id);
|
||||
$api_key_secret = trim((string)$api_key_secret);
|
||||
if ($api_key_id === '' || $api_key_secret === '')
|
||||
{
|
||||
throw new RuntimeException('Piwigo-API-Schluessel-ID und API-Geheimnis werden benoetigt.');
|
||||
}
|
||||
|
||||
$status = bratonien_tools_nc_connector_piwigo_api_request($api_key_id, $api_key_secret, 'pwg.session.getStatus');
|
||||
if (!is_array($status)) throw new RuntimeException('Piwigo hat keinen auswertbaren API-Benutzerstatus geliefert.');
|
||||
$role = strtolower(trim((string)($status['status'] ?? '')));
|
||||
if (!in_array($role, array('admin','webmaster'), true))
|
||||
{
|
||||
throw new RuntimeException('Der API-Key funktioniert, gehoert aber keinem Piwigo-Administrator/Webmaster.');
|
||||
}
|
||||
|
||||
$method_result = bratonien_tools_nc_connector_piwigo_api_request($api_key_id, $api_key_secret, 'reflection.getMethodList');
|
||||
$method_map = array();
|
||||
bratonien_tools_nc_connector_collect_method_names($method_result, $method_map);
|
||||
$required = array('bratonien.nc.syncProductive', 'bratonien.nc.syncOrphans');
|
||||
$missing = array_values(array_diff($required, array_keys($method_map)));
|
||||
if ($missing)
|
||||
{
|
||||
throw new RuntimeException('Der API-Key ist gueltig, aber benoetigte Bratonien-Sync-Methoden fehlen: '.implode(', ', $missing).'.');
|
||||
}
|
||||
}
|
||||
|
||||
function bratonien_tools_nc_connector_prepare_webdav_wizard_from_connection(array $connection, $mode)
|
||||
{
|
||||
$id = (int)$connection['id'];
|
||||
$config = isset($connection['config']) && is_array($connection['config']) ? $connection['config'] : array();
|
||||
$credentials = bratonien_tools_nc_connector_scoped_secret($connection);
|
||||
|
||||
$base_url = trim((string)($config['nextcloud_url'] ?? ''));
|
||||
$username = trim((string)($credentials['nextcloud_user'] ?? ''));
|
||||
if ($username === '')
|
||||
{
|
||||
$username = trim((string)($config['nextcloud_access_user'] ?? $config['access_user'] ?? ''));
|
||||
}
|
||||
$password = (string)($credentials['nextcloud_password'] ?? '');
|
||||
|
||||
$roots = isset($config['roots']) && is_array($config['roots']) ? array_values($config['roots']) : array();
|
||||
$selected = array();
|
||||
$selected_ids = array();
|
||||
foreach ($roots as $root)
|
||||
{
|
||||
$path = trim((string)($root['webdav_path'] ?? ''), '/');
|
||||
$fileid = (int)($root['fileid'] ?? 0);
|
||||
if ($path === '' || $fileid < 1) continue;
|
||||
$selected[] = $path;
|
||||
$selected_ids[$path] = $fileid;
|
||||
}
|
||||
|
||||
$state = bratonien_tools_nc_wizard_state();
|
||||
$state = array_merge($state, array(
|
||||
'editing_connection_id'=>$id,
|
||||
'editing_adapter'=>(string)$connection['adapter'],
|
||||
'editing_mode'=>(string)$mode,
|
||||
'connection_name'=>(string)$connection['name'],
|
||||
'host_input'=>$base_url,
|
||||
'base_url'=>$base_url,
|
||||
'username'=>$username,
|
||||
'_password'=>$password,
|
||||
'_fallback_user'=>(string)($credentials['piwigo_user'] ?? ''),
|
||||
'_fallback_password'=>(string)($credentials['piwigo_password'] ?? ''),
|
||||
'_api_key_id'=>(string)($credentials['api_key_id'] ?? ''),
|
||||
'_api_key_secret'=>(string)($credentials['api_key_secret'] ?? ''),
|
||||
'api_status'=>trim((string)($credentials['api_key_id'] ?? '')) !== '' && trim((string)($credentials['api_key_secret'] ?? '')) !== '' ? 'ok' : 'pending',
|
||||
'roots'=>$roots,
|
||||
'directory_selected'=>$selected,
|
||||
'directory_selected_fileids'=>$selected_ids,
|
||||
'source_mode'=>'webdav-placeholder',
|
||||
'transport'=>'webdav',
|
||||
));
|
||||
|
||||
if ($base_url !== '' && $username !== '' && $password !== '')
|
||||
{
|
||||
$state['step'] = 2;
|
||||
$state['scan_ok'] = true;
|
||||
$state['technical_stage'] = 'mounts';
|
||||
$state['technical_source'] = 'WebDAV';
|
||||
$state['technical_error'] = '';
|
||||
$state['technical_complete'] = false;
|
||||
$state['directory_selection_ready'] = true;
|
||||
$state['directory_path'] = '';
|
||||
$state['directory_parent'] = '';
|
||||
$state['directory_children'] = array();
|
||||
$state['directory_current_fileid'] = 0;
|
||||
|
||||
try
|
||||
{
|
||||
bratonien_tools_nc_wizard_refresh_directory_state($state, '');
|
||||
}
|
||||
catch (Throwable $e)
|
||||
{
|
||||
$state['step'] = 1;
|
||||
$state['scan_ok'] = false;
|
||||
$state['technical_error'] = $e->getMessage();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
$state['step'] = 1;
|
||||
$state['scan_ok'] = false;
|
||||
}
|
||||
|
||||
bratonien_tools_nc_wizard_store($state);
|
||||
}
|
||||
|
||||
function bratonien_tools_nc_connector_edit_start()
|
||||
{
|
||||
$id = (int)($_POST['connection_id'] ?? 0);
|
||||
$connection = bratonien_tools_nc_connector_connection($id, true);
|
||||
if (!$connection) throw new RuntimeException('Connector-Verbindung wurde nicht gefunden.');
|
||||
|
||||
$config = isset($connection['config']) && is_array($connection['config']) ? $connection['config'] : array();
|
||||
$is_webdav = (string)$connection['adapter'] === 'remote'
|
||||
&& (string)($config['source_mode'] ?? '') === 'webdav-placeholder';
|
||||
if (!$is_webdav)
|
||||
{
|
||||
throw new RuntimeException('Diese Legacy-Verbindung wird direkt bearbeitet. Eine WebDAV-Migration ist eine separate Aktion.');
|
||||
}
|
||||
|
||||
bratonien_tools_nc_connector_prepare_webdav_wizard_from_connection($connection, 'update');
|
||||
return array('message'=>'Verbindung #'.$id.' wurde zum Bearbeiten geoeffnet.');
|
||||
}
|
||||
|
||||
function bratonien_tools_nc_connector_migrate_start()
|
||||
{
|
||||
$id = (int)($_POST['connection_id'] ?? 0);
|
||||
$connection = bratonien_tools_nc_connector_connection($id, true);
|
||||
if (!$connection) throw new RuntimeException('Connector-Verbindung wurde nicht gefunden.');
|
||||
if ((string)$connection['adapter'] !== 'local')
|
||||
{
|
||||
throw new RuntimeException('Nur eine Legacy-Verbindung kann auf WebDAV migriert werden.');
|
||||
}
|
||||
|
||||
$migration = bratonien_tools_nc_connector_migration_state($connection);
|
||||
if (empty($migration['ready']))
|
||||
{
|
||||
throw new RuntimeException('Die WebDAV-Migration ist noch nicht bereit. Unter Bearbeiten fehlen: '.implode(', ', $migration['missing']).'.');
|
||||
}
|
||||
|
||||
bratonien_tools_nc_connector_prepare_webdav_wizard_from_connection($connection, 'migrate');
|
||||
return array('message'=>'Die WebDAV-Migration fuer Verbindung #'.$id.' wurde geoeffnet. Die bestehende Legacy-Verbindung bleibt bis zum erfolgreichen Umstieg unveraendert.');
|
||||
}
|
||||
|
||||
function bratonien_tools_nc_connector_update_local_friendly()
|
||||
{
|
||||
$id = (int)($_POST['connection_id'] ?? 0);
|
||||
$connection = bratonien_tools_nc_connector_connection($id, true);
|
||||
if (!$connection) throw new RuntimeException('Connector-Verbindung wurde nicht gefunden.');
|
||||
if ((string)$connection['adapter'] !== 'local') throw new RuntimeException('Diese Bearbeitung ist nur fuer Legacy-Verbindungen vorgesehen.');
|
||||
|
||||
$name = trim((string)($_POST['connection_name'] ?? ''));
|
||||
if ($name === '') throw new RuntimeException('Bitte einen Namen fuer die Verbindung angeben.');
|
||||
|
||||
$config = isset($connection['config']) && is_array($connection['config']) ? $connection['config'] : array();
|
||||
$host = trim((string)($_POST['nc_host'] ?? ''));
|
||||
$port = (int)($_POST['nc_port'] ?? 5432);
|
||||
$database = trim((string)($_POST['nc_database'] ?? ''));
|
||||
$user = trim((string)($_POST['nc_user'] ?? ''));
|
||||
$gallery_root = rtrim(trim((string)($_POST['nc_gallery_root'] ?? '')), '/');
|
||||
$source_view = trim((string)($_POST['nc_source_view'] ?? ''));
|
||||
$activity_view = trim((string)($_POST['nc_activity_view'] ?? ''));
|
||||
|
||||
if ($host === '') throw new RuntimeException('Datenbank-Server fehlt.');
|
||||
if ($port < 1 || $port > 65535) throw new RuntimeException('Der Datenbank-Port ist ungueltig.');
|
||||
if ($database === '') throw new RuntimeException('Datenbankname fehlt.');
|
||||
if ($user === '') throw new RuntimeException('Reader-Benutzer fehlt.');
|
||||
if ($gallery_root === '' || $gallery_root[0] !== '/') throw new RuntimeException('Der Piwigo-Galerieordner muss ein absoluter Pfad sein.');
|
||||
if ($source_view === '' || $activity_view === '') throw new RuntimeException('Die gespeicherten Datenbankansichten duerfen nicht leer sein.');
|
||||
bratonien_tools_nc_connector_view_name($source_view);
|
||||
bratonien_tools_nc_connector_view_name($activity_view);
|
||||
|
||||
$storage_ids = isset($_POST['nc_storage_id']) && is_array($_POST['nc_storage_id']) ? $_POST['nc_storage_id'] : array();
|
||||
$storage_prefixes = isset($_POST['nc_source_prefix']) && is_array($_POST['nc_source_prefix']) ? $_POST['nc_source_prefix'] : array();
|
||||
$storage_mounts = isset($_POST['nc_local_mount']) && is_array($_POST['nc_local_mount']) ? $_POST['nc_local_mount'] : array();
|
||||
$storages = array();
|
||||
$count = max(count($storage_ids), count($storage_prefixes), count($storage_mounts));
|
||||
for ($index = 0; $index < $count; $index++)
|
||||
{
|
||||
$storage_id = trim((string)($storage_ids[$index] ?? ''));
|
||||
$prefix = trim((string)($storage_prefixes[$index] ?? ''), '/');
|
||||
$mount = rtrim(trim((string)($storage_mounts[$index] ?? '')), '/');
|
||||
if ($storage_id === '' && $prefix === '' && $mount === '') continue;
|
||||
if ($storage_id === '') throw new RuntimeException('Bei einem Speicherort fehlt die Storage-ID.');
|
||||
if ($mount === '' || $mount[0] !== '/') throw new RuntimeException('Bei einem Speicherort fehlt ein gueltiger lokaler Pfad.');
|
||||
$storages[] = array('storage_id'=>$storage_id, 'source_prefix'=>$prefix, 'local_mount'=>$mount);
|
||||
}
|
||||
if (!$storages) throw new RuntimeException('Mindestens ein Speicherort muss vorhanden sein.');
|
||||
|
||||
$credentials = bratonien_tools_nc_connector_scoped_secret($connection);
|
||||
$new_db_password = (string)($_POST['nc_db_password'] ?? '');
|
||||
if ($new_db_password !== '') $credentials['db_password'] = $new_db_password;
|
||||
if (trim((string)($credentials['db_password'] ?? '')) === '') throw new RuntimeException('Fuer die Legacy-Verbindung ist kein Datenbankpasswort gespeichert.');
|
||||
|
||||
$nextcloud_url = trim((string)($_POST['nc_nextcloud_url'] ?? ($config['nextcloud_url'] ?? '')));
|
||||
$nextcloud_user = trim((string)($_POST['nc_nextcloud_user'] ?? ($credentials['nextcloud_user'] ?? '')));
|
||||
$new_nextcloud_password = (string)($_POST['nc_nextcloud_password'] ?? '');
|
||||
if ($new_nextcloud_password !== '') $credentials['nextcloud_password'] = $new_nextcloud_password;
|
||||
$nextcloud_password = (string)($credentials['nextcloud_password'] ?? '');
|
||||
|
||||
$api_key_id = trim((string)($_POST['nc_connection_api_key_id'] ?? ($credentials['api_key_id'] ?? '')));
|
||||
$new_api_secret = trim((string)($_POST['nc_connection_api_key_secret'] ?? ''));
|
||||
$old_api_id = trim((string)($credentials['api_key_id'] ?? ''));
|
||||
if ($api_key_id !== $old_api_id && $new_api_secret === '')
|
||||
{
|
||||
throw new RuntimeException('Wenn die API-Schluessel-ID geaendert wird, muss auch das API-Geheimnis neu eingegeben werden.');
|
||||
}
|
||||
if ($new_api_secret !== '') $credentials['api_key_secret'] = $new_api_secret;
|
||||
$api_key_secret = trim((string)($credentials['api_key_secret'] ?? ''));
|
||||
|
||||
if (($nextcloud_url === '' || $nextcloud_user === '' || $nextcloud_password === '') && ($nextcloud_url !== '' || $nextcloud_user !== '' || $nextcloud_password !== ''))
|
||||
{
|
||||
throw new RuntimeException('Nextcloud-Adresse, Nextcloud-Benutzer und Nextcloud-Passwort muessen fuer WebDAV gemeinsam vollstaendig sein.');
|
||||
}
|
||||
if (($api_key_id === '') !== ($api_key_secret === ''))
|
||||
{
|
||||
throw new RuntimeException('Piwigo-API-Schluessel-ID und API-Geheimnis muessen gemeinsam vollstaendig sein.');
|
||||
}
|
||||
|
||||
if ($nextcloud_url !== '')
|
||||
{
|
||||
$validated_nc = bratonien_tools_nc_connector_validate_nextcloud_access($nextcloud_url, $nextcloud_user, $nextcloud_password);
|
||||
$nextcloud_url = $validated_nc['base_url'];
|
||||
$nextcloud_user = $validated_nc['username'];
|
||||
$credentials['nextcloud_user'] = $nextcloud_user;
|
||||
}
|
||||
if ($api_key_id !== '')
|
||||
{
|
||||
bratonien_tools_nc_connector_validate_scoped_api($api_key_id, $api_key_secret);
|
||||
$credentials['api_key_id'] = $api_key_id;
|
||||
}
|
||||
|
||||
$config['host'] = $host;
|
||||
$config['port'] = (string)$port;
|
||||
$config['database'] = $database;
|
||||
$config['user'] = $user;
|
||||
$config['source_view'] = $source_view;
|
||||
$config['activity_view'] = $activity_view;
|
||||
$config['gallery_root'] = $gallery_root;
|
||||
$config['quiet_seconds'] = max(0, (int)($_POST['nc_quiet_seconds'] ?? ($config['quiet_seconds'] ?? 120)));
|
||||
$config['max_wait_seconds'] = max(60, (int)($_POST['nc_max_wait_seconds'] ?? ($config['max_wait_seconds'] ?? 900)));
|
||||
$config['full_sync_seconds'] = max(300, (int)($_POST['nc_full_sync_seconds'] ?? ($config['full_sync_seconds'] ?? 86400)));
|
||||
$config['storages'] = $storages;
|
||||
if ($nextcloud_url !== '')
|
||||
{
|
||||
$config['nextcloud_url'] = $nextcloud_url;
|
||||
$config['access_user'] = $nextcloud_user;
|
||||
$config['nextcloud_access_user'] = $nextcloud_user;
|
||||
}
|
||||
$config['piwigo_auth'] = 'connection-scoped';
|
||||
$config['api_enabled'] = $api_key_id !== '' && $api_key_secret !== '';
|
||||
unset($config['verification']);
|
||||
|
||||
$config_json = json_encode($config, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
||||
if (!is_string($config_json)) throw new RuntimeException('Connector-Konfiguration konnte nicht serialisiert werden.');
|
||||
$secret_payload = json_encode($credentials, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
||||
if (!is_string($secret_payload)) throw new RuntimeException('Connector-Zugangsdaten konnten nicht serialisiert werden.');
|
||||
$secret_blob = bratonien_tools_nc_connector_encrypt_secret($secret_payload);
|
||||
|
||||
$table = bratonien_tools_nc_connector_table();
|
||||
$now = date('Y-m-d H:i:s');
|
||||
pwg_query("UPDATE `$table` SET name='".pwg_db_real_escape_string($name)."', config_json='".pwg_db_real_escape_string($config_json)."', secret_blob='".pwg_db_real_escape_string($secret_blob)."', updated='".pwg_db_real_escape_string($now)."' WHERE id=".$id." LIMIT 1");
|
||||
|
||||
$updated = bratonien_tools_nc_connector_connection($id, true);
|
||||
$migration = $updated ? bratonien_tools_nc_connector_migration_state($updated) : array('ready'=>false);
|
||||
return array(
|
||||
'message'=>'Verbindung #'.$id.' wurde gespeichert. '.(!empty($migration['ready']) ? 'Die WebDAV-Migration ist jetzt bereit.' : 'Die WebDAV-Migration ist noch nicht vollstaendig vorbereitet.'),
|
||||
);
|
||||
}
|
||||
@@ -6,11 +6,6 @@ if (!defined('PHPWG_ROOT_PATH'))
|
||||
|
||||
/**
|
||||
* Return the only existing local connector as migration fallback.
|
||||
*
|
||||
* The 0.9.6.2 migration path is deliberately conservative: automatic pairing
|
||||
* only happens when there is exactly one local connection. Its enabled/state
|
||||
* flags are never changed here, so the proven local path keeps running while
|
||||
* WebDAV is introduced beside it.
|
||||
*/
|
||||
function bratonien_tools_nc_connector_single_local_fallback()
|
||||
{
|
||||
@@ -40,10 +35,7 @@ function bratonien_tools_nc_connector_single_local_fallback()
|
||||
}
|
||||
|
||||
/**
|
||||
* Link the new WebDAV connection with the single existing local connection.
|
||||
*
|
||||
* This is metadata only. The legacy connection is explicitly left untouched
|
||||
* as an always-available fallback until a later, separately approved cutover.
|
||||
* Link a WebDAV connection with the single existing local fallback.
|
||||
*/
|
||||
function bratonien_tools_nc_connector_pair_migration_fallback($webdav_id, array &$webdav_config, $now)
|
||||
{
|
||||
@@ -83,11 +75,11 @@ function bratonien_tools_nc_connector_pair_migration_fallback($webdav_id, array
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a WebDAV-backed connector beside the existing local mode.
|
||||
* Create or update a WebDAV-backed connector from the user-facing wizard.
|
||||
*
|
||||
* Since 0.9.6.2, when exactly one local connection exists, the new WebDAV
|
||||
* connection is automatically paired with it for migration. The local
|
||||
* connection remains untouched and keeps running as fallback.
|
||||
* Remote connections are updated in place. When the editor was opened for a
|
||||
* legacy connection, a WebDAV successor is created and the legacy connection
|
||||
* stays available as fallback.
|
||||
*/
|
||||
function bratonien_tools_nc_connector_create_webdav_placeholder_from_wizard()
|
||||
{
|
||||
@@ -103,7 +95,7 @@ function bratonien_tools_nc_connector_create_webdav_placeholder_from_wizard()
|
||||
$password = (string)($state['_password'] ?? '');
|
||||
if ($base_url === '' || $username === '' || $password === '')
|
||||
{
|
||||
throw new RuntimeException('Für den WebDAV-Testpfad fehlen Nextcloud-Adresse oder Zugangsdaten.');
|
||||
throw new RuntimeException('Für den WebDAV-Zugang fehlen Nextcloud-Adresse oder Zugangsdaten.');
|
||||
}
|
||||
|
||||
$selected = isset($state['directory_selected']) && is_array($state['directory_selected'])
|
||||
@@ -113,7 +105,7 @@ function bratonien_tools_nc_connector_create_webdav_placeholder_from_wizard()
|
||||
? $state['directory_selected_fileids']
|
||||
: array();
|
||||
$selected = array_values(array_filter($selected, function($path) { return $path !== ''; }));
|
||||
if (!$selected) throw new RuntimeException('Bitte mindestens ein Nextcloud-Verzeichnis für den WebDAV-Testpfad auswählen.');
|
||||
if (!$selected) throw new RuntimeException('Bitte mindestens ein Nextcloud-Verzeichnis auswählen.');
|
||||
|
||||
$roots = array();
|
||||
foreach ($selected as $path)
|
||||
@@ -138,6 +130,14 @@ function bratonien_tools_nc_connector_create_webdav_placeholder_from_wizard()
|
||||
$fallback_password = (string)($state['_fallback_password'] ?? '');
|
||||
$api_enabled = $api_key_id !== '' && $api_key_secret !== '';
|
||||
|
||||
$editing_id = (int)($state['editing_connection_id'] ?? 0);
|
||||
$editing_mode = (string)($state['editing_mode'] ?? '');
|
||||
$editing_connection = $editing_id > 0 ? bratonien_tools_nc_connector_connection($editing_id, false) : null;
|
||||
$editing_remote = $editing_connection
|
||||
&& (string)$editing_connection['adapter'] === 'remote'
|
||||
&& (string)($editing_connection['config']['source_mode'] ?? '') === 'webdav-placeholder'
|
||||
&& $editing_mode === 'update';
|
||||
|
||||
$config = array(
|
||||
'origin'=>'native',
|
||||
'source_mode'=>'webdav-placeholder',
|
||||
@@ -157,6 +157,19 @@ function bratonien_tools_nc_connector_create_webdav_placeholder_from_wizard()
|
||||
'api_enabled'=>$api_enabled,
|
||||
);
|
||||
|
||||
if ($editing_remote)
|
||||
{
|
||||
$old_config = is_array($editing_connection['config'] ?? null) ? $editing_connection['config'] : array();
|
||||
foreach (array('state_dir','status_file','parallel_gallery_root','source_fingerprint','runtime','migration') as $preserve)
|
||||
{
|
||||
if (array_key_exists($preserve, $old_config)) $config[$preserve] = $old_config[$preserve];
|
||||
}
|
||||
foreach (array('quiet_seconds','max_wait_seconds','full_sync_seconds') as $preserve)
|
||||
{
|
||||
if (isset($old_config[$preserve])) $config[$preserve] = (int)$old_config[$preserve];
|
||||
}
|
||||
}
|
||||
|
||||
foreach (array('product'=>'nextcloud_product', 'version'=>'nextcloud_version') as $state_key=>$config_key)
|
||||
{
|
||||
$value = trim((string)($state[$state_key] ?? ''));
|
||||
@@ -175,15 +188,31 @@ function bratonien_tools_nc_connector_create_webdav_placeholder_from_wizard()
|
||||
), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
||||
if (!is_string($secret_payload)) throw new RuntimeException('WebDAV-Zugangsdaten konnten nicht serialisiert werden.');
|
||||
|
||||
$config_json = json_encode($config, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
||||
if (!is_string($config_json)) throw new RuntimeException('WebDAV-Konfiguration konnte nicht serialisiert werden.');
|
||||
|
||||
bratonien_tools_nc_connector_ensure_table();
|
||||
$table = bratonien_tools_nc_connector_table();
|
||||
$now = date('Y-m-d H:i:s');
|
||||
$connection_key = 'webdav-'.bin2hex(random_bytes(12));
|
||||
$secret_blob = bratonien_tools_nc_connector_encrypt_secret($secret_payload);
|
||||
|
||||
if ($editing_remote)
|
||||
{
|
||||
$config['state_dir'] = trim((string)($config['state_dir'] ?? '')) !== '' ? $config['state_dir'] : '/var/lib/bratonien-tools/nc-connector/connection-'.$editing_id;
|
||||
$config['status_file'] = trim((string)($config['status_file'] ?? '')) !== '' ? $config['status_file'] : $config['state_dir'].'/connector-status.json';
|
||||
$config_json = json_encode($config, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
||||
if (!is_string($config_json)) throw new RuntimeException('WebDAV-Konfiguration konnte nicht serialisiert werden.');
|
||||
|
||||
pwg_query("UPDATE `$table` SET name='".pwg_db_real_escape_string($name)."', config_json='".pwg_db_real_escape_string($config_json)."', secret_blob='".pwg_db_real_escape_string($secret_blob)."', updated='".pwg_db_real_escape_string($now)."' WHERE id=".$editing_id." LIMIT 1");
|
||||
unset($_SESSION['bratonien_nc_wizard']);
|
||||
|
||||
return array(
|
||||
'connection_id'=>$editing_id,
|
||||
'message'=>'WebDAV-Verbindung #'.$editing_id.' wurde gespeichert. Der nächste Connector-Lauf verwendet die neuen Einstellungen.',
|
||||
);
|
||||
}
|
||||
|
||||
$config_json = json_encode($config, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
||||
if (!is_string($config_json)) throw new RuntimeException('WebDAV-Konfiguration konnte nicht serialisiert werden.');
|
||||
|
||||
$connection_key = 'webdav-'.bin2hex(random_bytes(12));
|
||||
pwg_query("INSERT INTO `$table` (connection_key,name,adapter,enabled,takeover_state,config_json,secret_blob,created,updated) VALUES ('"
|
||||
.pwg_db_real_escape_string($connection_key)."','"
|
||||
.pwg_db_real_escape_string($name)."','remote',0,'disabled','"
|
||||
@@ -193,7 +222,7 @@ function bratonien_tools_nc_connector_create_webdav_placeholder_from_wizard()
|
||||
.pwg_db_real_escape_string($now)."')");
|
||||
|
||||
$id = (int)pwg_db_insert_id();
|
||||
if ($id < 1) throw new RuntimeException('Die WebDAV-Testverbindung konnte nicht eindeutig angelegt werden.');
|
||||
if ($id < 1) throw new RuntimeException('Die WebDAV-Verbindung konnte nicht eindeutig angelegt werden.');
|
||||
|
||||
try
|
||||
{
|
||||
@@ -204,7 +233,7 @@ function bratonien_tools_nc_connector_create_webdav_placeholder_from_wizard()
|
||||
$config_json = json_encode($config, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
||||
if (!is_string($config_json))
|
||||
{
|
||||
throw new RuntimeException('Die WebDAV-Testverbindung konnte nach dem Anlegen nicht serialisiert werden.');
|
||||
throw new RuntimeException('Die WebDAV-Verbindung konnte nach dem Anlegen nicht serialisiert werden.');
|
||||
}
|
||||
pwg_query("UPDATE `$table` SET config_json='".pwg_db_real_escape_string($config_json)."' WHERE id=".$id." LIMIT 1");
|
||||
}
|
||||
@@ -214,17 +243,19 @@ function bratonien_tools_nc_connector_create_webdav_placeholder_from_wizard()
|
||||
throw $e;
|
||||
}
|
||||
|
||||
unset($_SESSION['bratonien_nc_wizard']);
|
||||
|
||||
if ($legacy_fallback_id !== null)
|
||||
{
|
||||
return array(
|
||||
'connection_id'=>$id,
|
||||
'legacy_fallback_connection_id'=>$legacy_fallback_id,
|
||||
'message'=>'WebDAV-Verbindung wurde parallel angelegt. Die bestehende lokale Verbindung #'.$legacy_fallback_id.' bleibt unverändert als laufender Fallback erhalten.',
|
||||
'message'=>'WebDAV-Nachfolger wurde angelegt. Die bestehende lokale Verbindung #'.$legacy_fallback_id.' bleibt als Fallback erhalten.',
|
||||
);
|
||||
}
|
||||
|
||||
return array(
|
||||
'connection_id'=>$id,
|
||||
'message'=>'Parallele WebDAV-Verbindung wurde angelegt. Bestehende Verbindungen blieben unverändert.',
|
||||
'message'=>'WebDAV-Verbindung wurde angelegt.',
|
||||
);
|
||||
}
|
||||
|
||||
@@ -4,6 +4,16 @@ if (!defined('PHPWG_ROOT_PATH'))
|
||||
die('Hacking attempt!');
|
||||
}
|
||||
|
||||
if (isset($GLOBALS['template']) && is_object($GLOBALS['template']) && method_exists($GLOBALS['template'], 'func_combine_script'))
|
||||
{
|
||||
$GLOBALS['template']->func_combine_script(array(
|
||||
'id'=>'bratonien_nc_connector_edit_v2',
|
||||
'path'=>BRATONIEN_TOOLS_PATH.'js/nc_connector_edit_v2.js',
|
||||
'load'=>'footer',
|
||||
'version'=>function_exists('bratonien_tools_current_version') ? bratonien_tools_current_version() : '0.9.6.10',
|
||||
));
|
||||
}
|
||||
|
||||
require_once(BRATONIEN_TOOLS_PATH . 'tools/image_cache.inc.php');
|
||||
require_once(BRATONIEN_TOOLS_PATH . 'tools/watermark.inc.php');
|
||||
require_once(BRATONIEN_TOOLS_PATH . 'tools/watermark_profiles.inc.php');
|
||||
@@ -30,6 +40,7 @@ require_once(BRATONIEN_TOOLS_PATH . 'include/nc_connector_generic_scope.inc.php'
|
||||
require_once(BRATONIEN_TOOLS_PATH . 'include/nc_connector_delete_safe.inc.php');
|
||||
require_once(BRATONIEN_TOOLS_PATH . 'include/nc_connector_webdav.inc.php');
|
||||
require_once(BRATONIEN_TOOLS_PATH . 'include/nc_connector_wizard_webdav_flow.inc.php');
|
||||
require_once(BRATONIEN_TOOLS_PATH . 'include/nc_connector_edit.inc.php');
|
||||
|
||||
function bratonien_tools_get_tools()
|
||||
{
|
||||
@@ -56,6 +67,9 @@ function bratonien_tools_get_tools()
|
||||
'album_share_revoke' => array('handler' => 'bratonien_tools_revoke_album_share'),
|
||||
'nc_connector_create_local' => array('handler' => 'bratonien_tools_nc_connector_create_local_api_first'),
|
||||
'nc_connector_create_webdav_parallel' => array('handler' => 'bratonien_tools_nc_connector_create_webdav_placeholder_from_wizard'),
|
||||
'nc_connector_edit_start' => array('handler' => 'bratonien_tools_nc_connector_edit_start'),
|
||||
'nc_connector_migrate_start' => array('handler' => 'bratonien_tools_nc_connector_migrate_start'),
|
||||
'nc_connector_update_local' => array('handler' => 'bratonien_tools_nc_connector_update_local_friendly'),
|
||||
'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_update_technical' => array('handler' => 'bratonien_tools_nc_connector_update_technical'),
|
||||
|
||||
205
js/nc_connector_edit_v2.js
Normal file
205
js/nc_connector_edit_v2.js
Normal file
@@ -0,0 +1,205 @@
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
function ready(callback) {
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', function () { window.setTimeout(callback, 0); });
|
||||
} else {
|
||||
window.setTimeout(callback, 0);
|
||||
}
|
||||
}
|
||||
|
||||
ready(function () {
|
||||
var section = document.getElementById('nc-connector');
|
||||
if (!section) return;
|
||||
|
||||
var pwgTokenInput = section.querySelector('input[name="pwg_token"]');
|
||||
var pwgToken = pwgTokenInput ? pwgTokenInput.value : '';
|
||||
var modeKey = 'bratonienNcWizardMode';
|
||||
|
||||
function escapeHtml(value) {
|
||||
return String(value == null ? '' : value).replace(/[&<>"']/g, function (c) {
|
||||
return {'&':'&','<':'<','>':'>','"':'"',"'":'''}[c];
|
||||
});
|
||||
}
|
||||
|
||||
function setMode(value) {
|
||||
try { sessionStorage.setItem(modeKey, value); } catch (e) {}
|
||||
}
|
||||
|
||||
function postForm(label, tool, id, mode) {
|
||||
var form = document.createElement('form');
|
||||
form.method = 'post';
|
||||
form.style.display = 'inline';
|
||||
form.dataset.ncV2Action = tool;
|
||||
form.innerHTML = '<input type="hidden" name="pwg_token" value="'+escapeHtml(pwgToken)+'">'
|
||||
+ '<input type="hidden" name="connection_id" value="'+escapeHtml(id)+'">'
|
||||
+ '<button class="buttonLike" type="submit" name="bratonien_tool" value="'+escapeHtml(tool)+'">'+escapeHtml(label)+'</button>';
|
||||
if (mode) form.addEventListener('submit', function () { setMode(mode); }, true);
|
||||
return form;
|
||||
}
|
||||
|
||||
function loadConnection(id) {
|
||||
return fetch('plugins/bratonien_tools/nc-connector-edit-data.php?connection_id='+encodeURIComponent(id)+'&_='+Date.now(), {
|
||||
credentials:'same-origin',
|
||||
cache:'no-store',
|
||||
headers:{'Accept':'application/json'}
|
||||
}).then(function (response) {
|
||||
return response.json().then(function (data) {
|
||||
if (!response.ok) throw new Error(data.error || ('HTTP '+response.status));
|
||||
return data;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function dialog() {
|
||||
var node = document.getElementById('bratonien-nc-connection-edit-v2');
|
||||
if (node) return node;
|
||||
node = document.createElement('dialog');
|
||||
node.id = 'bratonien-nc-connection-edit-v2';
|
||||
node.className = 'bratonien-edit-dialog';
|
||||
node.innerHTML = '<div class="bratonien-edit-dialog__body">'
|
||||
+ '<div style="display:flex;align-items:flex-start;justify-content:space-between;gap:1rem">'
|
||||
+ '<div><h4 style="margin:0">Verbindung bearbeiten</h4><p class="bratonien-base-note" style="margin:.35rem 0 0">Alle Daten dieser Verbindung werden hier gepflegt. Eine Migration ist ein eigener Vorgang.</p></div>'
|
||||
+ '<button type="button" class="buttonLike" data-edit-v2-close>Schließen</button></div>'
|
||||
+ '<div data-edit-v2-content style="margin-top:1rem"></div></div>';
|
||||
document.body.appendChild(node);
|
||||
node.querySelector('[data-edit-v2-close]').addEventListener('click', function () { node.close(); });
|
||||
node.addEventListener('click', function (event) { if (event.target === node) node.close(); });
|
||||
return node;
|
||||
}
|
||||
|
||||
function storageRow(storage) {
|
||||
storage = storage || {};
|
||||
return '<div class="bratonien-storage-row" data-storage-row>'
|
||||
+ '<label>Storage-ID<input name="nc_storage_id[]" value="'+escapeHtml(storage.storage_id || '')+'" required></label>'
|
||||
+ '<label>Quellordner<input name="nc_source_prefix[]" value="'+escapeHtml(storage.source_prefix || '')+'" placeholder="optional"></label>'
|
||||
+ '<label>Lokaler Speicherpfad<input name="nc_local_mount[]" value="'+escapeHtml(storage.local_mount || '')+'" required></label>'
|
||||
+ '<button type="button" class="buttonLike" data-remove-storage>Entfernen</button></div>';
|
||||
}
|
||||
|
||||
function openEditor(id) {
|
||||
var editDialog = dialog();
|
||||
var content = editDialog.querySelector('[data-edit-v2-content]');
|
||||
content.innerHTML = '<p class="bratonien-base-note">Verbindung wird geladen …</p>';
|
||||
if (typeof editDialog.showModal === 'function') editDialog.showModal();
|
||||
else editDialog.setAttribute('open', 'open');
|
||||
|
||||
loadConnection(id).then(function (data) {
|
||||
if (data.adapter !== 'local') throw new Error('Diese Ansicht ist nur für die bestehende Legacy-Verbindung vorgesehen.');
|
||||
var legacy = data.legacy || {};
|
||||
var webdav = data.webdav || {};
|
||||
var storages = Array.isArray(legacy.storages) ? legacy.storages : [];
|
||||
var rows = storages.map(storageRow).join('') || storageRow({});
|
||||
var migrationText = webdav.migration_ready
|
||||
? '<strong>Bereit.</strong> Nextcloud-Zugang und verbindungseigener Piwigo-API-Key sind vollständig gespeichert.'
|
||||
: '<strong>Noch nicht bereit.</strong> Es fehlen: '+escapeHtml((webdav.migration_missing || []).join(', ') || 'WebDAV-Zugangsdaten')+'.';
|
||||
|
||||
content.innerHTML = '<form method="post" data-edit-v2-form>'
|
||||
+ '<input type="hidden" name="pwg_token" value="'+escapeHtml(pwgToken)+'">'
|
||||
+ '<input type="hidden" name="connection_id" value="'+escapeHtml(data.id)+'">'
|
||||
+ '<h5>Verbindung</h5><div class="bratonien-form-grid">'
|
||||
+ '<label class="bratonien-label">Name</label><input name="connection_name" value="'+escapeHtml(data.name)+'" required>'
|
||||
+ '</div>'
|
||||
+ '<h5 style="margin-top:1.2rem">Nextcloud / WebDAV</h5>'
|
||||
+ '<p class="bratonien-base-note">Diese Angaben werden für den neuen WebDAV-Weg benötigt und gehören zu genau dieser Verbindung.</p>'
|
||||
+ '<div class="bratonien-form-grid">'
|
||||
+ '<label class="bratonien-label">Nextcloud-Adresse</label><input name="nc_nextcloud_url" value="'+escapeHtml(webdav.nextcloud_url || '')+'" placeholder="https://cloud.example.de">'
|
||||
+ '<label class="bratonien-label">Nextcloud-Benutzer</label><input name="nc_nextcloud_user" value="'+escapeHtml(webdav.nextcloud_user || '')+'" autocomplete="username">'
|
||||
+ '<label class="bratonien-label">Nextcloud-Passwort</label><input name="nc_nextcloud_password" type="password" autocomplete="current-password" placeholder="'+(webdav.has_nextcloud_password ? 'gespeichert – leer = unverändert' : 'noch nicht gespeichert')+'">'
|
||||
+ '</div>'
|
||||
+ '<h5 style="margin-top:1.2rem">Piwigo API dieser Verbindung</h5>'
|
||||
+ '<p class="bratonien-base-note">Der API-Key wird verbindungseigen gespeichert und beim Speichern geprüft.</p>'
|
||||
+ '<div class="bratonien-form-grid">'
|
||||
+ '<label class="bratonien-label">API-Schlüssel-ID</label><input name="nc_connection_api_key_id" value="'+escapeHtml(webdav.api_key_id || '')+'" autocomplete="off">'
|
||||
+ '<label class="bratonien-label">API-Geheimnis</label><input name="nc_connection_api_key_secret" type="password" autocomplete="new-password" placeholder="'+(webdav.has_api_key_secret ? 'gespeichert – leer = unverändert' : 'noch nicht gespeichert')+'">'
|
||||
+ '</div>'
|
||||
+ '<p class="bratonien-base-note"><strong>WebDAV-Migration:</strong> '+migrationText+'</p>'
|
||||
+ '<h5 style="margin-top:1.2rem">Bestehender Legacy-Weg</h5><div class="bratonien-form-grid">'
|
||||
+ '<label class="bratonien-label">Datenbank-Server</label><input name="nc_host" value="'+escapeHtml(legacy.host)+'" required>'
|
||||
+ '<label class="bratonien-label">Port</label><input name="nc_port" type="number" min="1" max="65535" value="'+escapeHtml(legacy.port || 5432)+'" required>'
|
||||
+ '<label class="bratonien-label">Datenbank</label><input name="nc_database" value="'+escapeHtml(legacy.database)+'" required>'
|
||||
+ '<label class="bratonien-label">Reader-Benutzer</label><input name="nc_user" value="'+escapeHtml(legacy.user)+'" required>'
|
||||
+ '<label class="bratonien-label">Reader-Passwort</label><input name="nc_db_password" type="password" autocomplete="new-password" placeholder="'+(legacy.has_db_password ? 'gespeichert – leer = unverändert' : 'noch nicht gespeichert')+'">'
|
||||
+ '</div>'
|
||||
+ '<h5 style="margin-top:1.2rem">Speicherorte</h5><div data-storage-list>'+rows+'</div>'
|
||||
+ '<button type="button" class="buttonLike" data-add-storage>Speicherort hinzufügen</button>'
|
||||
+ '<details style="margin-top:1rem"><summary>Erweiterte Legacy-Einstellungen</summary><div class="bratonien-form-grid" style="margin-top:.75rem">'
|
||||
+ '<label class="bratonien-label">Source-View</label><input name="nc_source_view" value="'+escapeHtml(legacy.source_view)+'" required>'
|
||||
+ '<label class="bratonien-label">Activity-View</label><input name="nc_activity_view" value="'+escapeHtml(legacy.activity_view)+'" required>'
|
||||
+ '<label class="bratonien-label">Piwigo-Galerieordner</label><input name="nc_gallery_root" value="'+escapeHtml(legacy.gallery_root)+'" required>'
|
||||
+ '<label class="bratonien-label">Ruhezeit (Sek.)</label><input name="nc_quiet_seconds" type="number" min="0" value="'+escapeHtml(legacy.quiet_seconds)+'">'
|
||||
+ '<label class="bratonien-label">Maximale Wartezeit (Sek.)</label><input name="nc_max_wait_seconds" type="number" min="60" value="'+escapeHtml(legacy.max_wait_seconds)+'">'
|
||||
+ '<label class="bratonien-label">Vollprüfung nach (Sek.)</label><input name="nc_full_sync_seconds" type="number" min="300" value="'+escapeHtml(legacy.full_sync_seconds)+'">'
|
||||
+ '</div></details>'
|
||||
+ '<div class="bratonien-actions" style="margin-top:1rem"><button class="buttonLike" type="submit" name="bratonien_tool" value="nc_connector_update_local">Änderungen prüfen und speichern</button><button class="buttonLike" type="button" data-edit-v2-cancel>Abbrechen</button></div>'
|
||||
+ '</form>';
|
||||
|
||||
var form = content.querySelector('[data-edit-v2-form]');
|
||||
form.querySelector('[data-edit-v2-cancel]').addEventListener('click', function () { editDialog.close(); });
|
||||
form.querySelector('[data-add-storage]').addEventListener('click', function () {
|
||||
form.querySelector('[data-storage-list]').insertAdjacentHTML('beforeend', storageRow({}));
|
||||
});
|
||||
form.addEventListener('click', function (event) {
|
||||
var remove = event.target.closest('[data-remove-storage]');
|
||||
if (!remove) return;
|
||||
var row = remove.closest('[data-storage-row]');
|
||||
if (row) row.remove();
|
||||
});
|
||||
}).catch(function (error) {
|
||||
content.innerHTML = '<p class="bratonien-main-cache__warning"><strong>Bearbeiten nicht möglich:</strong> '+escapeHtml(error.message || String(error))+'</p>';
|
||||
});
|
||||
}
|
||||
|
||||
function rebuildLocalActions(deleteForm, id) {
|
||||
var actions = deleteForm.parentElement;
|
||||
if (!actions) return;
|
||||
|
||||
[].slice.call(actions.querySelectorAll('form')).forEach(function (form) {
|
||||
var migrate = form.querySelector('button[value="nc_connector_migrate_start"]');
|
||||
if (migrate) form.remove();
|
||||
});
|
||||
[].slice.call(actions.children).forEach(function (child) {
|
||||
if (child.tagName === 'BUTTON' && (child.textContent || '').trim() === 'Bearbeiten') child.remove();
|
||||
if (child.dataset && child.dataset.ncMigrationInfo) child.remove();
|
||||
});
|
||||
|
||||
var edit = document.createElement('button');
|
||||
edit.type = 'button';
|
||||
edit.className = 'buttonLike';
|
||||
edit.textContent = 'Bearbeiten';
|
||||
edit.addEventListener('click', function () { openEditor(id); });
|
||||
actions.insertBefore(edit, deleteForm);
|
||||
|
||||
var info = document.createElement('span');
|
||||
info.dataset.ncMigrationInfo = '1';
|
||||
info.className = 'bratonien-base-note';
|
||||
info.textContent = 'WebDAV-Migration wird geprüft …';
|
||||
actions.insertBefore(info, deleteForm);
|
||||
|
||||
loadConnection(id).then(function (data) {
|
||||
var webdav = data.webdav || {};
|
||||
if (webdav.migration_ready) {
|
||||
info.remove();
|
||||
actions.insertBefore(postForm('Auf WebDAV migrieren', 'nc_connector_migrate_start', id, 'migrate'), deleteForm);
|
||||
} else {
|
||||
var missing = (webdav.migration_missing || []).join(', ');
|
||||
info.textContent = 'WebDAV-Migration noch nicht bereit: '+(missing || 'Zugangsdaten fehlen')+'. Zuerst „Bearbeiten“.';
|
||||
}
|
||||
}).catch(function (error) {
|
||||
info.textContent = 'WebDAV-Migration kann nicht geprüft werden: '+(error.message || String(error));
|
||||
});
|
||||
}
|
||||
|
||||
[].slice.call(section.querySelectorAll('button[value="nc_connector_delete"]')).forEach(function (deleteButton) {
|
||||
var deleteForm = deleteButton.closest('form');
|
||||
var card = deleteButton.closest('details');
|
||||
if (!deleteForm || !card) return;
|
||||
var idInput = deleteForm.querySelector('input[name="connection_id"]');
|
||||
if (!idInput) return;
|
||||
var text = card.textContent || '';
|
||||
var isLocal = text.indexOf('bestehende Legacy-Konfiguration') !== -1;
|
||||
if (isLocal) rebuildLocalActions(deleteForm, idInput.value);
|
||||
});
|
||||
});
|
||||
})();
|
||||
@@ -1,7 +1,7 @@
|
||||
<?php
|
||||
/*
|
||||
Plugin Name: Bratonien Tools
|
||||
Version: 0.9.6.2
|
||||
Version: 0.9.6.10
|
||||
Description: Erweiterbare Administrationswerkzeuge fuer die Bratonien-Piwigo-Installation.
|
||||
Plugin URI: https://github.com/Terranom674/Piwigo_Bratonien_Tools
|
||||
Author: Bratonien
|
||||
|
||||
100
nc-connector-edit-data.php
Normal file
100
nc-connector-edit-data.php
Normal file
@@ -0,0 +1,100 @@
|
||||
<?php
|
||||
$piwigo_root = realpath(dirname(__DIR__, 2));
|
||||
if ($piwigo_root === false)
|
||||
{
|
||||
http_response_code(500);
|
||||
exit;
|
||||
}
|
||||
define('PHPWG_ROOT_PATH', rtrim($piwigo_root, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR);
|
||||
include_once(PHPWG_ROOT_PATH.'include/common.inc.php');
|
||||
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
header('Cache-Control: no-store, max-age=0');
|
||||
|
||||
if (!defined('BRATONIEN_TOOLS_PATH'))
|
||||
{
|
||||
http_response_code(404);
|
||||
echo json_encode(array('error'=>'Bratonien Tools ist nicht aktiv.'));
|
||||
exit;
|
||||
}
|
||||
if (!function_exists('is_admin') || !is_admin())
|
||||
{
|
||||
http_response_code(403);
|
||||
echo json_encode(array('error'=>'Administratorrechte erforderlich.'));
|
||||
exit;
|
||||
}
|
||||
|
||||
require_once(BRATONIEN_TOOLS_PATH.'include/nc_connector.inc.php');
|
||||
require_once(BRATONIEN_TOOLS_PATH.'include/nc_connector_manage.inc.php');
|
||||
require_once(BRATONIEN_TOOLS_PATH.'include/nc_connector_connection_scope.inc.php');
|
||||
require_once(BRATONIEN_TOOLS_PATH.'include/nc_connector_edit.inc.php');
|
||||
|
||||
$id = (int)($_GET['connection_id'] ?? 0);
|
||||
$connection = bratonien_tools_nc_connector_connection($id, true);
|
||||
if (!$connection)
|
||||
{
|
||||
http_response_code(404);
|
||||
echo json_encode(array('error'=>'Connector-Verbindung wurde nicht gefunden.'));
|
||||
exit;
|
||||
}
|
||||
|
||||
$config = isset($connection['config']) && is_array($connection['config']) ? $connection['config'] : array();
|
||||
$credentials = array();
|
||||
$migration = array('ready'=>false, 'missing'=>array());
|
||||
try
|
||||
{
|
||||
$credentials = bratonien_tools_nc_connector_scoped_secret($connection);
|
||||
if ((string)$connection['adapter'] === 'local')
|
||||
{
|
||||
$migration = bratonien_tools_nc_connector_migration_state($connection);
|
||||
}
|
||||
}
|
||||
catch (Throwable $e)
|
||||
{
|
||||
$credentials = array();
|
||||
$migration = array('ready'=>false, 'missing'=>array('gespeicherte Zugangsdaten konnten nicht gelesen werden'));
|
||||
}
|
||||
|
||||
$storages = array();
|
||||
foreach ((array)($config['storages'] ?? array()) as $storage)
|
||||
{
|
||||
$storages[] = array(
|
||||
'storage_id'=>(string)($storage['storage_id'] ?? ''),
|
||||
'source_prefix'=>(string)($storage['source_prefix'] ?? ''),
|
||||
'local_mount'=>(string)($storage['local_mount'] ?? ''),
|
||||
);
|
||||
}
|
||||
|
||||
$payload = array(
|
||||
'id'=>(int)$connection['id'],
|
||||
'name'=>(string)$connection['name'],
|
||||
'adapter'=>(string)$connection['adapter'],
|
||||
'enabled'=>(bool)$connection['enabled'],
|
||||
'takeover_state'=>(string)$connection['takeover_state'],
|
||||
'source_mode'=>(string)($config['source_mode'] ?? ''),
|
||||
'legacy'=>array(
|
||||
'host'=>(string)($config['host'] ?? ''),
|
||||
'port'=>(string)($config['port'] ?? '5432'),
|
||||
'database'=>(string)($config['database'] ?? ''),
|
||||
'user'=>(string)($config['user'] ?? ''),
|
||||
'has_db_password'=>trim((string)($credentials['db_password'] ?? '')) !== '',
|
||||
'source_view'=>(string)($config['source_view'] ?? ''),
|
||||
'activity_view'=>(string)($config['activity_view'] ?? ''),
|
||||
'gallery_root'=>(string)($config['gallery_root'] ?? ''),
|
||||
'quiet_seconds'=>(int)($config['quiet_seconds'] ?? 120),
|
||||
'max_wait_seconds'=>(int)($config['max_wait_seconds'] ?? 900),
|
||||
'full_sync_seconds'=>(int)($config['full_sync_seconds'] ?? 86400),
|
||||
'storages'=>$storages,
|
||||
),
|
||||
'webdav'=>array(
|
||||
'nextcloud_url'=>(string)($config['nextcloud_url'] ?? ''),
|
||||
'nextcloud_user'=>(string)($credentials['nextcloud_user'] ?? $config['nextcloud_access_user'] ?? $config['access_user'] ?? ''),
|
||||
'has_nextcloud_password'=>(string)($credentials['nextcloud_password'] ?? '') !== '',
|
||||
'api_key_id'=>(string)($credentials['api_key_id'] ?? ''),
|
||||
'has_api_key_secret'=>trim((string)($credentials['api_key_secret'] ?? '')) !== '',
|
||||
'migration_ready'=>!empty($migration['ready']),
|
||||
'migration_missing'=>array_values((array)($migration['missing'] ?? array())),
|
||||
),
|
||||
);
|
||||
|
||||
echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
||||
@@ -36,6 +36,11 @@ $latest = array(
|
||||
'api'=>array('state'=>'not_run','message'=>''),
|
||||
'fallback'=>array('state'=>'not_run','message'=>''),
|
||||
'error_detail'=>'',
|
||||
'route'=>'',
|
||||
'route_label'=>'Noch kein Datenweg erfasst',
|
||||
'route_timestamp'=>0,
|
||||
'route_time_label'=>'Nicht verfügbar',
|
||||
'route_detail'=>'',
|
||||
);
|
||||
|
||||
if (is_dir($dir))
|
||||
@@ -57,6 +62,54 @@ if (is_dir($dir))
|
||||
$latest['connection_file'] = basename($file);
|
||||
}
|
||||
}
|
||||
|
||||
$route_file = $dir.'/route-status.json';
|
||||
if (is_readable($route_file))
|
||||
{
|
||||
$route = json_decode((string)@file_get_contents($route_file), true);
|
||||
if (is_array($route))
|
||||
{
|
||||
$route_name = (string)($route['route'] ?? '');
|
||||
$route_timestamp = (int)($route['timestamp'] ?? 0);
|
||||
$route_label = (string)($route['label'] ?? '');
|
||||
|
||||
if ($route_name === 'webdav')
|
||||
{
|
||||
$route_label = 'WEBDAV PRIMÄR';
|
||||
}
|
||||
elseif ($route_name === 'legacy_fallback')
|
||||
{
|
||||
$route_label = 'LEGACY-FALLBACK AKTIV';
|
||||
}
|
||||
elseif ($route_name === 'failed')
|
||||
{
|
||||
$route_label = 'FEHLER - KEIN ERFOLGREICHER DATENWEG';
|
||||
}
|
||||
elseif ($route_label === '')
|
||||
{
|
||||
$route_label = 'UNBEKANNTER DATENWEG';
|
||||
}
|
||||
|
||||
$route_detail = trim((string)($route['detail'] ?? ''));
|
||||
$latest['route'] = $route_name;
|
||||
$latest['route_label'] = $route_label;
|
||||
$latest['route_timestamp'] = $route_timestamp;
|
||||
$latest['route_time_label'] = $route_timestamp > 0 ? date('d.m.Y H:i:s', $route_timestamp) : 'Nicht verfügbar';
|
||||
$latest['route_detail'] = $route_detail;
|
||||
|
||||
$base_message = trim((string)($latest['message'] ?? ''));
|
||||
$message_parts = array($route_label);
|
||||
if ($route_name !== 'webdav' && $route_detail !== '')
|
||||
{
|
||||
$message_parts[] = $route_detail;
|
||||
}
|
||||
if ($base_message !== '')
|
||||
{
|
||||
$message_parts[] = $base_message;
|
||||
}
|
||||
$latest['message'] = implode(' · ', $message_parts);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ((int)$latest['timestamp'] > 0)
|
||||
|
||||
@@ -17,6 +17,57 @@ read_config_value() {
|
||||
printf '%s' "$value"
|
||||
}
|
||||
|
||||
compact_text() {
|
||||
printf '%s\n' "$1" | tail -n 20 | tr '\n' ' ' | sed 's/[[:space:]]\+/ /g; s/^[[:space:]]//; s/[[:space:]]$//'
|
||||
}
|
||||
|
||||
read_webdav_failure_detail() {
|
||||
local config="$1"
|
||||
local captured_output="${2:-}"
|
||||
local connection_id piwigo_root status_file status_detail
|
||||
|
||||
connection_id="$(read_config_value CONNECTION_ID "$config")"
|
||||
piwigo_root="$(read_config_value PIWIGO_ROOT "$config")"
|
||||
[[ -n "$piwigo_root" ]] || piwigo_root="/var/www/piwigo"
|
||||
|
||||
status_detail=""
|
||||
if [[ -n "$connection_id" ]]; then
|
||||
status_file="${piwigo_root%/}/_data/bratonien-tools/nc-connector-status/connection-${connection_id}.json"
|
||||
if [[ -r "$status_file" ]]; then
|
||||
status_detail="$(php -r '
|
||||
$file = $argv[1];
|
||||
$data = json_decode((string)@file_get_contents($file), true);
|
||||
if (!is_array($data)) exit(0);
|
||||
$message = trim((string)($data["message"] ?? ""));
|
||||
$detail = trim((string)($data["error_detail"] ?? ""));
|
||||
$parts = array();
|
||||
if ($message !== "") $parts[] = $message;
|
||||
if ($detail !== "") $parts[] = $detail;
|
||||
if ($parts) {
|
||||
$text = preg_replace("/\\s+/u", " ", implode(" - ", $parts));
|
||||
echo trim((string)$text);
|
||||
}
|
||||
' "$status_file")"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [[ -n "$captured_output" ]]; then
|
||||
captured_output="$(compact_text "$captured_output")"
|
||||
fi
|
||||
|
||||
if [[ -n "$status_detail" && -n "$captured_output" ]]; then
|
||||
printf '%s' "$status_detail | Prozessausgabe: $captured_output"
|
||||
elif [[ -n "$status_detail" ]]; then
|
||||
printf '%s' "$status_detail"
|
||||
elif [[ -n "$captured_output" ]]; then
|
||||
printf '%s' "$captured_output"
|
||||
elif [[ -z "$connection_id" ]]; then
|
||||
printf '%s' 'WebDAV-Prozess wurde gestartet, aber die Verbindungs-ID fehlt in der Runtime-Konfiguration.'
|
||||
else
|
||||
printf '%s' "WebDAV-Prozess fuer Verbindung ${connection_id} endete mit Fehler, lieferte aber weder Statusdatei noch Prozessausgabe."
|
||||
fi
|
||||
}
|
||||
|
||||
write_route_status() {
|
||||
local route="$1"
|
||||
local label="$2"
|
||||
@@ -84,17 +135,31 @@ ROUTE_STATUS_FILE="${route_piwigo_root%/}/_data/bratonien-tools/nc-connector-sta
|
||||
|
||||
webdav_success=0
|
||||
webdav_failed=0
|
||||
webdav_failure_detail=""
|
||||
|
||||
for config in "${webdav_configs[@]}"; do
|
||||
name="$(basename "$config")"
|
||||
echo "NC Connector WebDAV primaer: $name"
|
||||
if env PIWIGO_CONFIG="$config" bash "$SCRIPT_DIR/sync-webdav.sh"; then
|
||||
webdav_success=1
|
||||
else
|
||||
webdav_failed=1
|
||||
echo "NC Connector: WebDAV-Lauf fehlgeschlagen; Legacy-Fallback bleibt verfuegbar." >&2
|
||||
fi
|
||||
done
|
||||
if [[ ${#webdav_configs[@]} -eq 0 ]]; then
|
||||
webdav_failed=1
|
||||
webdav_failure_detail="Keine WebDAV-Runtime-Verbindung ist konfiguriert. Es existiert aktuell nur die Legacy-Verbindung; deshalb kann WebDAV nicht primaer laufen."
|
||||
echo "NC Connector: $webdav_failure_detail" >&2
|
||||
else
|
||||
for config in "${webdav_configs[@]}"; do
|
||||
name="$(basename "$config")"
|
||||
echo "NC Connector WebDAV primaer: $name"
|
||||
webdav_output=""
|
||||
if webdav_output="$(env PIWIGO_CONFIG="$config" bash "$SCRIPT_DIR/sync-webdav.sh" 2>&1)"; then
|
||||
webdav_success=1
|
||||
[[ -z "$webdav_output" ]] || printf '%s\n' "$webdav_output"
|
||||
else
|
||||
webdav_exit=$?
|
||||
webdav_failed=1
|
||||
[[ -z "$webdav_output" ]] || printf '%s\n' "$webdav_output" >&2
|
||||
webdav_failure_detail="$(read_webdav_failure_detail "$config" "$webdav_output")"
|
||||
webdav_failure_detail="Exit-Code ${webdav_exit}: ${webdav_failure_detail}"
|
||||
echo "NC Connector: WebDAV-Lauf fehlgeschlagen: $webdav_failure_detail" >&2
|
||||
echo "NC Connector: Legacy-Fallback bleibt verfuegbar." >&2
|
||||
fi
|
||||
done
|
||||
fi
|
||||
|
||||
if [[ "$webdav_success" -eq 1 ]]; then
|
||||
write_route_status \
|
||||
@@ -108,10 +173,11 @@ if [[ "$webdav_success" -eq 1 ]]; then
|
||||
fi
|
||||
|
||||
if [[ ${#configs[@]} -eq 0 ]]; then
|
||||
[[ -n "$webdav_failure_detail" ]] || webdav_failure_detail="WebDAV ist fehlgeschlagen; Ursache konnte nicht ermittelt werden."
|
||||
write_route_status \
|
||||
"failed" \
|
||||
"FEHLER - kein Datenweg" \
|
||||
"WebDAV ist fehlgeschlagen und es ist keine Legacy-Fallback-Verbindung vorhanden." \
|
||||
"WebDAV-Fehler: $webdav_failure_detail Keine Legacy-Fallback-Verbindung vorhanden." \
|
||||
"0" \
|
||||
"0"
|
||||
echo "NC Connector: WebDAV ist fehlgeschlagen und es ist keine Legacy-Fallback-Verbindung vorhanden." >&2
|
||||
@@ -150,20 +216,22 @@ for config in "${configs[@]}"; do
|
||||
done
|
||||
|
||||
if [[ "$legacy_result" -eq 0 ]]; then
|
||||
[[ -n "$webdav_failure_detail" ]] || webdav_failure_detail="WebDAV war nicht erfolgreich; Ursache konnte nicht ermittelt werden."
|
||||
write_route_status \
|
||||
"legacy_fallback" \
|
||||
"LEGACY-FALLBACK AKTIV" \
|
||||
"WebDAV war nicht erfolgreich. Der alte lokale Datenweg wurde als Fallback ausgefuehrt." \
|
||||
"WebDAV-Fehler: $webdav_failure_detail Legacy-Fallback wurde erfolgreich ausgefuehrt." \
|
||||
"1" \
|
||||
"1"
|
||||
echo "NC Connector: Legacy-Fallback erfolgreich."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
[[ -n "$webdav_failure_detail" ]] || webdav_failure_detail="WebDAV war nicht erfolgreich; Ursache konnte nicht ermittelt werden."
|
||||
write_route_status \
|
||||
"failed" \
|
||||
"FEHLER - WebDAV und Fallback" \
|
||||
"WebDAV und Legacy-Fallback sind fehlgeschlagen." \
|
||||
"WebDAV-Fehler: $webdav_failure_detail Legacy-Fallback ist ebenfalls fehlgeschlagen." \
|
||||
"1" \
|
||||
"0"
|
||||
|
||||
|
||||
@@ -9,7 +9,13 @@
|
||||
.bratonien-tab-panel { width:100%; max-width:none; margin-left:0 !important; margin-right:0 !important; }
|
||||
.bratonien-tab-panel[hidden] { display:none !important; }
|
||||
.bratonien-card { margin-left:0; margin-right:0; }
|
||||
@media (max-width:760px) { .bratonien-tabs{gap:5px}.bratonien-tab{border-bottom:1px solid rgba(255,255,255,.16);border-radius:4px;margin-bottom:0;padding:9px 11px} }
|
||||
.bratonien-edit-dialog { width:min(920px,calc(100vw - 3rem)); max-height:88vh; overflow:auto; background:#444; color:inherit; border:1px solid #777; border-radius:4px; padding:0; box-shadow:0 18px 60px rgba(0,0,0,.55); }
|
||||
.bratonien-edit-dialog::backdrop { background:rgba(0,0,0,.55); }
|
||||
.bratonien-edit-dialog__body { padding:1.25rem 1.5rem; }
|
||||
.bratonien-storage-row { display:grid; grid-template-columns:minmax(120px,.7fr) minmax(150px,1fr) minmax(240px,1.5fr) auto; gap:.5rem; align-items:end; margin:.5rem 0; }
|
||||
.bratonien-storage-row label { display:flex; flex-direction:column; gap:.25rem; }
|
||||
.bratonien-storage-row input { width:100%; box-sizing:border-box; }
|
||||
@media (max-width:760px) { .bratonien-tabs{gap:5px}.bratonien-tab{border-bottom:1px solid rgba(255,255,255,.16);border-radius:4px;margin-bottom:0;padding:9px 11px}.bratonien-storage-row{grid-template-columns:1fr} }
|
||||
</style>
|
||||
<div id="bratonien-tabs-anchor"></div>
|
||||
<script>
|
||||
@@ -48,12 +54,31 @@
|
||||
var openButton=document.getElementById('bratonien-nc-wizard-open');
|
||||
var closeButton=document.getElementById('bratonien-nc-wizard-close');
|
||||
var storageKey='bratonienNcWizardOpen';
|
||||
var modeKey='bratonienNcWizardMode';
|
||||
var resetBusy=false;
|
||||
|
||||
function token(){var input=section.querySelector('input[name="pwg_token"]');return input?input.value:'';}
|
||||
function setOpen(value){try{if(value)sessionStorage.setItem(storageKey,'1');else sessionStorage.removeItem(storageKey);}catch(e){}}
|
||||
function mode(){try{return sessionStorage.getItem(modeKey)||'';}catch(e){return '';}}
|
||||
function clearMode(){try{sessionStorage.removeItem(modeKey);}catch(e){}}
|
||||
function applyMode(){
|
||||
if(!dialog)return;
|
||||
var current=mode();
|
||||
var heading=dialog.querySelector('h4');
|
||||
var finish=dialog.querySelector('button[value="nc_connector_wizard_finish"]');
|
||||
if(current==='edit'){
|
||||
if(heading)heading.textContent='Verbindung bearbeiten';
|
||||
if(finish)finish.textContent='Änderungen speichern';
|
||||
}else if(current==='migrate'){
|
||||
if(heading)heading.textContent='Auf WebDAV migrieren';
|
||||
if(finish)finish.textContent='Migration starten';
|
||||
}else{
|
||||
if(heading)heading.textContent='Neue Verbindung';
|
||||
if(finish)finish.textContent='Verbindung anlegen';
|
||||
}
|
||||
}
|
||||
function showWizard(){
|
||||
setOpen(true);
|
||||
setOpen(true);applyMode();
|
||||
if(!dialog)return;
|
||||
if(typeof dialog.showModal==='function'&&!dialog.open)dialog.showModal();
|
||||
else dialog.setAttribute('open','open');
|
||||
@@ -65,13 +90,13 @@
|
||||
return fetch(window.location.href,{method:'POST',credentials:'same-origin',cache:'no-store',headers:{'Content-Type':'application/x-www-form-urlencoded;charset=UTF-8'},body:body.toString()});
|
||||
}
|
||||
function closeAfterReset(){
|
||||
if(resetBusy)return;resetBusy=true;setOpen(false);
|
||||
if(resetBusy)return;resetBusy=true;setOpen(false);clearMode();
|
||||
resetServer().catch(function(){}).finally(function(){resetBusy=false;if(dialog){if(typeof dialog.close==='function'&&dialog.open)dialog.close();else dialog.removeAttribute('open');}});
|
||||
}
|
||||
|
||||
if(openButton){
|
||||
openButton.addEventListener('click',function(event){
|
||||
event.preventDefault();event.stopImmediatePropagation();showWizard();
|
||||
event.preventDefault();event.stopImmediatePropagation();clearMode();showWizard();
|
||||
},true);
|
||||
}
|
||||
if(closeButton){
|
||||
@@ -80,18 +105,111 @@
|
||||
if(dialog){
|
||||
dialog.addEventListener('cancel',function(event){event.preventDefault();event.stopImmediatePropagation();closeAfterReset();},true);
|
||||
dialog.addEventListener('click',function(event){if(event.target===dialog){event.preventDefault();event.stopImmediatePropagation();closeAfterReset();}},true);
|
||||
|
||||
// Every wizard POST explicitly preserves the open state before the
|
||||
// browser leaves the page. Validation errors therefore return to the
|
||||
// same wizard step instead of closing/resetting the dialog.
|
||||
[].slice.call(dialog.querySelectorAll('form[data-bratonien-wizard-form]')).forEach(function(form){
|
||||
form.addEventListener('submit',function(){setOpen(true);},true);
|
||||
form.addEventListener('submit',function(event){
|
||||
var submitter=event.submitter;
|
||||
setOpen(true);
|
||||
if(submitter&&submitter.hasAttribute('data-bratonien-wizard-end')){
|
||||
setOpen(false);
|
||||
if(submitter.value==='nc_connector_wizard_reset')clearMode();
|
||||
}
|
||||
},true);
|
||||
});
|
||||
|
||||
try{if(sessionStorage.getItem(storageKey)==='1')showWizard();}catch(e){}
|
||||
applyMode();
|
||||
}
|
||||
}
|
||||
|
||||
function initNCConnectionEditing(){
|
||||
var section=document.getElementById('nc-connector');if(!section)return;
|
||||
var modeKey='bratonienNcWizardMode';
|
||||
var pwgTokenInput=section.querySelector('input[name="pwg_token"]');
|
||||
var pwgToken=pwgTokenInput?pwgTokenInput.value:'';
|
||||
|
||||
function setMode(value){try{sessionStorage.setItem(modeKey,value);}catch(e){}}
|
||||
function makePostButton(label,tool,id,modeValue){
|
||||
var form=document.createElement('form');form.method='post';form.style.display='inline';
|
||||
var token=document.createElement('input');token.type='hidden';token.name='pwg_token';token.value=pwgToken;form.appendChild(token);
|
||||
var connection=document.createElement('input');connection.type='hidden';connection.name='connection_id';connection.value=String(id);form.appendChild(connection);
|
||||
var button=document.createElement('button');button.type='submit';button.className='buttonLike';button.name='bratonien_tool';button.value=tool;button.textContent=label;
|
||||
if(modeValue)form.addEventListener('submit',function(){setMode(modeValue);});
|
||||
form.appendChild(button);return form;
|
||||
}
|
||||
function escapeHtml(value){return String(value==null?'':value).replace(/[&<>"']/g,function(c){return {'&':'&','<':'<','>':'>','"':'"',"'":'''}[c];});}
|
||||
function localEditorDialog(){
|
||||
var dialog=document.getElementById('bratonien-nc-local-edit-dialog');
|
||||
if(dialog)return dialog;
|
||||
dialog=document.createElement('dialog');dialog.id='bratonien-nc-local-edit-dialog';dialog.className='bratonien-edit-dialog';
|
||||
dialog.innerHTML='<div class="bratonien-edit-dialog__body"><div style="display:flex;align-items:center;justify-content:space-between;gap:1rem"><div><h4 style="margin:0">Verbindung bearbeiten</h4><p class="bratonien-base-note" style="margin:.35rem 0 0">Bestehende Legacy-Verbindung. Änderungen werden in derselben Verbindung gespeichert.</p></div><button type="button" class="buttonLike" data-local-edit-close>Schließen</button></div><div data-local-edit-content style="margin-top:1rem"></div></div>';
|
||||
document.body.appendChild(dialog);
|
||||
dialog.querySelector('[data-local-edit-close]').addEventListener('click',function(){dialog.close();});
|
||||
dialog.addEventListener('click',function(event){if(event.target===dialog)dialog.close();});
|
||||
return dialog;
|
||||
}
|
||||
function storageRow(storage){
|
||||
return '<div class="bratonien-storage-row" data-storage-row>'+
|
||||
'<label>Storage-ID<input name="nc_storage_id[]" value="'+escapeHtml(storage.storage_id||'')+'" required></label>'+
|
||||
'<label>Quellordner<input name="nc_source_prefix[]" value="'+escapeHtml(storage.source_prefix||'')+'" placeholder="optional"></label>'+
|
||||
'<label>Lokaler Speicherpfad<input name="nc_local_mount[]" value="'+escapeHtml(storage.local_mount||'')+'" required></label>'+
|
||||
'<button type="button" class="buttonLike" data-remove-storage>Entfernen</button></div>';
|
||||
}
|
||||
function openLocalEditor(id){
|
||||
var dialog=localEditorDialog();
|
||||
var content=dialog.querySelector('[data-local-edit-content]');
|
||||
content.innerHTML='<p class="bratonien-base-note">Verbindung wird geladen …</p>';
|
||||
if(typeof dialog.showModal==='function')dialog.showModal();else dialog.setAttribute('open','open');
|
||||
fetch('plugins/bratonien_tools/nc-connector-edit-data.php?connection_id='+encodeURIComponent(id)+'&_='+Date.now(),{credentials:'same-origin',cache:'no-store',headers:{'Accept':'application/json'}})
|
||||
.then(function(response){return response.json().then(function(data){if(!response.ok)throw new Error(data.error||('HTTP '+response.status));return data;});})
|
||||
.then(function(data){
|
||||
if(data.adapter!=='local')throw new Error('Diese Verbindung ist keine Legacy-Verbindung.');
|
||||
var legacy=data.legacy||{};var storages=Array.isArray(legacy.storages)?legacy.storages:[];
|
||||
var rows=storages.map(storageRow).join('');
|
||||
if(!rows)rows=storageRow({});
|
||||
content.innerHTML='<form method="post" data-local-edit-form>'+
|
||||
'<input type="hidden" name="pwg_token" value="'+escapeHtml(pwgToken)+'">'+
|
||||
'<input type="hidden" name="connection_id" value="'+escapeHtml(data.id)+'">'+
|
||||
'<div class="bratonien-form-grid">'+
|
||||
'<label class="bratonien-label">Name</label><input name="connection_name" value="'+escapeHtml(data.name)+'" required>'+
|
||||
'<label class="bratonien-label">Datenbank-Server</label><input name="nc_host" value="'+escapeHtml(legacy.host)+'" required>'+
|
||||
'<label class="bratonien-label">Port</label><input name="nc_port" type="number" min="1" max="65535" value="'+escapeHtml(legacy.port||5432)+'" required>'+
|
||||
'<label class="bratonien-label">Datenbank</label><input name="nc_database" value="'+escapeHtml(legacy.database)+'" required>'+
|
||||
'<label class="bratonien-label">Reader-Benutzer</label><input name="nc_user" value="'+escapeHtml(legacy.user)+'" required>'+
|
||||
'<label class="bratonien-label">Reader-Passwort</label><input name="nc_db_password" type="password" autocomplete="new-password" placeholder="leer = unverändert">'+
|
||||
'</div>'+
|
||||
'<h5 style="margin-top:1rem">Speicherorte</h5><p class="bratonien-base-note">Jeder Speicherort wird einzeln bearbeitet. Es ist kein Pipe-/Textformat erforderlich.</p><div data-storage-list>'+rows+'</div><button type="button" class="buttonLike" data-add-storage>Speicherort hinzufügen</button>'+
|
||||
'<details style="margin-top:1rem"><summary>Erweiterte Legacy-Einstellungen</summary><div class="bratonien-form-grid" style="margin-top:.75rem">'+
|
||||
'<label class="bratonien-label">Source-View</label><input name="nc_source_view" value="'+escapeHtml(legacy.source_view)+'" required>'+
|
||||
'<label class="bratonien-label">Activity-View</label><input name="nc_activity_view" value="'+escapeHtml(legacy.activity_view)+'" required>'+
|
||||
'<label class="bratonien-label">Piwigo-Galerieordner</label><input name="nc_gallery_root" value="'+escapeHtml(legacy.gallery_root)+'" required>'+
|
||||
'<label class="bratonien-label">Ruhezeit (Sek.)</label><input name="nc_quiet_seconds" type="number" min="0" value="'+escapeHtml(legacy.quiet_seconds)+'">'+
|
||||
'<label class="bratonien-label">Maximale Wartezeit (Sek.)</label><input name="nc_max_wait_seconds" type="number" min="60" value="'+escapeHtml(legacy.max_wait_seconds)+'">'+
|
||||
'<label class="bratonien-label">Vollprüfung nach (Sek.)</label><input name="nc_full_sync_seconds" type="number" min="300" value="'+escapeHtml(legacy.full_sync_seconds)+'">'+
|
||||
'</div></details>'+
|
||||
'<div class="bratonien-actions" style="margin-top:1rem"><button class="buttonLike" type="submit" name="bratonien_tool" value="nc_connector_update_local">Änderungen speichern</button><button class="buttonLike" type="button" data-local-edit-cancel>Abbrechen</button></div></form>';
|
||||
var form=content.querySelector('[data-local-edit-form]');
|
||||
form.querySelector('[data-local-edit-cancel]').addEventListener('click',function(){dialog.close();});
|
||||
form.querySelector('[data-add-storage]').addEventListener('click',function(){form.querySelector('[data-storage-list]').insertAdjacentHTML('beforeend',storageRow({}));});
|
||||
form.addEventListener('click',function(event){var remove=event.target.closest('[data-remove-storage]');if(remove){var row=remove.closest('[data-storage-row]');if(row)row.remove();}});
|
||||
})
|
||||
.catch(function(error){content.innerHTML='<p class="bratonien-main-cache__warning"><strong>Bearbeiten nicht möglich:</strong> '+escapeHtml(error.message||String(error))+'</p>';});
|
||||
}
|
||||
|
||||
[].slice.call(section.querySelectorAll('button[value="nc_connector_edit_start"]')).forEach(function(button){var form=button.closest('form');if(form)form.remove();});
|
||||
|
||||
[].slice.call(section.querySelectorAll('button[value="nc_connector_delete"]')).forEach(function(deleteButton){
|
||||
var deleteForm=deleteButton.closest('form');var card=deleteButton.closest('details');if(!deleteForm||!card)return;
|
||||
var idInput=deleteForm.querySelector('input[name="connection_id"]');if(!idInput)return;var id=idInput.value;
|
||||
var actions=deleteForm.parentElement;if(!actions)return;
|
||||
var text=card.textContent||'';var isLocal=text.indexOf('bestehende Legacy-Konfiguration')!==-1;
|
||||
if(isLocal){
|
||||
var edit=document.createElement('button');edit.type='button';edit.className='buttonLike';edit.textContent='Bearbeiten';edit.addEventListener('click',function(){openLocalEditor(id);});actions.insertBefore(edit,deleteForm);
|
||||
actions.insertBefore(makePostButton('Auf WebDAV migrieren','nc_connector_migrate_start',id,'migrate'),deleteForm);
|
||||
}else{
|
||||
actions.insertBefore(makePostButton('Bearbeiten','nc_connector_edit_start',id,'edit'),deleteForm);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function initNCConnectorPolling(){
|
||||
var section=document.getElementById('nc-connector');if(!section)return;
|
||||
var endpoint='plugins/bratonien_tools/nc-connector-status.php';
|
||||
@@ -144,7 +262,7 @@
|
||||
poll();schedule();
|
||||
}
|
||||
|
||||
function initAll(){initBratonienTabs();initNCWizardLifecycle();initNCConnectorPolling();}
|
||||
function initAll(){initBratonienTabs();initNCWizardLifecycle();initNCConnectionEditing();initNCConnectorPolling();}
|
||||
if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',initAll);else initAll();
|
||||
})();
|
||||
</script>
|
||||
|
||||
Reference in New Issue
Block a user