mirror of
https://github.com/Terranom674/Piwigo_Bratonien_Tools.git
synced 2026-09-19 19:54:31 +00:00
Compare commits
72 Commits
bf03fea647
...
fix/edit-w
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
26af1b3019 | ||
|
|
b1b75676a8 | ||
|
|
12880b6c41 | ||
|
|
32abc7250d | ||
|
|
76de2b037c | ||
|
|
e2e82162c6 | ||
|
|
7a9eb1baa6 | ||
|
|
e800f11f64 | ||
|
|
4808f08590 | ||
|
|
6fd89df5d0 | ||
|
|
99126088e7 | ||
|
|
e53a3848bb | ||
|
|
0f0c71acaf | ||
|
|
9847690f50 | ||
|
|
a2f5dc3919 | ||
|
|
cd3bf7c8ee | ||
|
|
79ea403555 | ||
|
|
33783dd30f | ||
|
|
ca6a5cf96f | ||
|
|
62ada617fb | ||
|
|
898f9b1bc9 | ||
|
|
5b48e1f6f2 | ||
|
|
fdf4584028 | ||
|
|
880744a8b7 | ||
|
|
2ed84ad089 | ||
|
|
60c0a51f01 | ||
|
|
84d263b16b | ||
|
|
94c81789ed | ||
|
|
e3b1f06be3 | ||
|
|
15a3ceb01c | ||
|
|
0f5812a179 | ||
|
|
377b29a127 | ||
|
|
d9696172c5 | ||
|
|
3f2a85fb0b | ||
|
|
c882ba994b | ||
|
|
cd2c9e350b | ||
|
|
394f375e91 | ||
|
|
3b1ccd99a5 | ||
|
|
04d88cd40f | ||
|
|
a4f953551c | ||
|
|
b4161471ca | ||
|
|
71fdadb7f8 | ||
|
|
98134b5ab8 | ||
|
|
5f82f2ad71 | ||
|
|
494f8bf192 | ||
|
|
c46f9bb5bd | ||
|
|
992cb55714 | ||
|
|
46782ea9a3 | ||
|
|
d03410c9ef | ||
|
|
aa2a6e4c02 | ||
|
|
ebdd77fb0a | ||
|
|
6c36aaeb8a | ||
|
|
2c7cd9e780 | ||
|
|
6155955eee | ||
|
|
5179c1cc33 | ||
|
|
facb270b13 | ||
|
|
b4f56ac04b | ||
|
|
16571f9322 | ||
|
|
d7fd99eb7c | ||
|
|
207c2ae502 | ||
|
|
4d04f115e1 | ||
|
|
ed9088a8e2 | ||
|
|
8c7476a5d2 | ||
|
|
bc9d378bfd | ||
|
|
3da61079f2 | ||
|
|
f380ee4aec | ||
|
|
96dda18fc9 | ||
|
|
3767620867 | ||
|
|
d18e7108dd | ||
|
|
450f9a0ac5 | ||
|
|
47182a86a2 | ||
|
|
907fba8c8f |
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: |
|
||||
|
||||
@@ -1,187 +1,139 @@
|
||||
# Aktueller Entwicklungsstand
|
||||
|
||||
Stand: 18.08.2026
|
||||
Stand: 19.08.2026
|
||||
|
||||
## Plugin
|
||||
|
||||
- Aktuelle Plugin-Version: **0.9.5.7**
|
||||
- Aktueller Entwicklungsblock: **NC Connector – WebDAV-basierter Parallelweg bei vollständigem Erhalt des bestehenden produktiven Wegs**
|
||||
- Aktuelle Plugin-Version: **0.9.6.1**
|
||||
- Aktueller Entwicklungsblock: **NC Connector – WebDAV-End-to-End-Pfad mit Piwigo-Registrierung, Preview-/Derivatstrecke und sauberem Verbindungs-Lebenszyklus**
|
||||
- GitHub ist das führende Repository.
|
||||
- Das private Gitea-System bleibt Mirror/Fallback.
|
||||
- Der bestehende lokale Connector bleibt vollständig erhalten und wird nicht automatisch migriert.
|
||||
|
||||
## Nicht verhandelbare Migrationsregel
|
||||
## Nicht verhandelbare Architekturregeln
|
||||
|
||||
Der bestehende lokale NC Connector bleibt vollständig erhalten, bis der neue WebDAV-Weg End-to-End funktioniert.
|
||||
- Nextcloud bleibt die Quelle der Originalbilder.
|
||||
- Originalbilder werden **nicht dauerhaft nach Piwigo kopiert**.
|
||||
- Der bestehende lokale Produktionsweg bleibt funktionsfähig.
|
||||
- WebDAV benötigt nur Nextcloud-Adresse, Benutzer/App-Passwort und normale WebDAV-Berechtigungen des Benutzers.
|
||||
- Kein Nextcloud-PostgreSQL-Zugriff, kein `occ`, keine Storage-IDs, keine Host-Mounts, kein FUSE, davfs oder rclone als Voraussetzung.
|
||||
- WebDAV-Verbindungen werden voneinander isoliert verarbeitet.
|
||||
- Fehler der WebDAV-Bildverarbeitung dürfen keinen normalen Piwigo-Seitenaufruf zum Absturz bringen.
|
||||
|
||||
Bestehende Quellenmodi:
|
||||
## Bestehende Quellenmodi
|
||||
|
||||
Weiterhin vorhanden:
|
||||
|
||||
- `legacy-view`
|
||||
- `user-shares`
|
||||
- `selected-fileids`
|
||||
|
||||
Sie werden nicht automatisch migriert, deaktiviert oder auf den neuen Weg umgestellt.
|
||||
|
||||
Der neue Weg entsteht zusätzlich als eigener Modus:
|
||||
Neuer WebDAV-Modus:
|
||||
|
||||
- `webdav-placeholder`
|
||||
|
||||
## Ziel des neuen Wegs
|
||||
Es gibt keine automatische Migration bestehender Verbindungen auf WebDAV.
|
||||
|
||||
Benötigt werden sollen nur:
|
||||
## WebDAV-Ablauf in 0.9.6.1
|
||||
|
||||
- normale Piwigo-Installation;
|
||||
- bereits vorhandene Linux-/PHP-Umgebung;
|
||||
- Nextcloud-Adresse;
|
||||
- Nextcloud-Benutzer bzw. App-Passwort;
|
||||
- WebDAV-Zugriff auf die Inhalte dieses Benutzers.
|
||||
1. Der Assistent prüft Nextcloud über WebDAV und lässt sichtbare Verzeichnisse auswählen.
|
||||
2. `runtime/reconcile-webdav.php` erzeugt die verbindungseigene Runtime-Konfiguration.
|
||||
3. `runtime/lib/build_webdav_placeholder_source.py` liest die ausgewählten Verzeichnisse rekursiv per PROPFIND.
|
||||
4. Ordner, Dateinamen, Nextcloud-Datei-ID, MIME-Typ, Größe, ETag und WebDAV-Pfad werden erfasst.
|
||||
5. Eine lokale Platzhalterquelle wird erzeugt, ohne Originalbilder dauerhaft zu speichern.
|
||||
6. `runtime/lib/shadow_tree.py` baut daraus den verbindungseigenen Shadow Tree.
|
||||
7. Der WebDAV-Galeriebaum liegt unter `_data/bratonien-tools/nc-webdav-gallery/connection-ID` und wird als eigene physische Piwigo-Site registriert.
|
||||
8. Dadurch erscheint die ausgewählte Nextcloud-Wurzel als normales Piwigo-Album; technische `bratonien-webdav-ID`-Wrapper werden nicht angezeigt.
|
||||
9. Vorbereitete Arbeitsbilder liegen unter `_data/bratonien-tools/nc-webdav-preview/connection-ID`.
|
||||
10. Arbeitsbilder werden als JPEG beziehungsweise PNG erzeugt und maximal auf 4096 px Kantenlänge begrenzt, damit Piwigos Bildbibliothek sie zuverlässig verarbeiten kann.
|
||||
11. Der CLI-Derivat-Builder korrigiert die Piwigo-Bildabmessungen anhand des Arbeitsbilds und erzeugt die aktuell konfigurierten Standard- und Custom-Derivate.
|
||||
12. Der normale Frontend-Aufruf erzeugt **keine** Derivate. Fehlt ein Derivat, wird das vorbereitete Bild als sicherer Fallback ausgeliefert.
|
||||
13. Originalbilder werden bei echtem Originalabruf serverseitig über `webdav-image.php` aus Nextcloud gestreamt; Nextcloud-Zugangsdaten erscheinen nicht im Browser.
|
||||
|
||||
Nicht vorausgesetzt werden dürfen:
|
||||
## Piwigo-Synchronisierung
|
||||
|
||||
- PostgreSQL-Zugriff auf Nextcloud;
|
||||
- `occ`-Adminzugriff;
|
||||
- Rootzugriff des Betreibers;
|
||||
- Storage-IDs oder Backend-Pfade;
|
||||
- zusätzliche Host-Mounts;
|
||||
- FUSE;
|
||||
- davfs;
|
||||
- rclone;
|
||||
- zusätzliche Connector-Systempakete.
|
||||
WebDAV verwendet denselben Piwigo-Synchronisationspfad wie der bestehende Connector, aber mit einer verbindungseigenen physischen Site.
|
||||
|
||||
Originalbilder werden nicht dauerhaft nach Piwigo kopiert.
|
||||
Nach der Dateisynchronisierung laufen die vorhandenen Piwigo-Nacharbeiten, darunter Metadaten-, Integritäts-, Kategorie-, Pfad-, Rang- und Cache-Aktualisierungen sowie der Orphan-Abgleich.
|
||||
|
||||
## Architektur des WebDAV-Parallelwegs
|
||||
Die direkte produktive Synchronisierung ist derzeit ausdrücklich auf **Piwigo 16.4.0** abgestimmt.
|
||||
|
||||
1. Ausgewählte Nextcloud-Verzeichnisse werden über WebDAV/PROPFIND gelesen.
|
||||
2. Das Plugin erfasst Ordner, Dateinamen, Datei-ID, MIME-Typ, Größe, ETag und WebDAV-Pfad.
|
||||
3. Für jedes Bild wird nur ein winziger lokaler Platzhalter bereitgestellt.
|
||||
4. Der bestehende Shadow Tree bleibt die physische Piwigo-Quelle.
|
||||
5. Der Shadow Tree bildet die reale Ordner- und Dateinamensstruktur ab, seine Bildziele zeigen jedoch auf Platzhalter statt auf Originale.
|
||||
6. Ein separates Mapping verbindet Shadow-Tree-Pfad, Connection-ID, Nextcloud-Datei-ID und WebDAV-Pfad.
|
||||
7. Piwigo soll Album und Bild über diese Struktur registrieren.
|
||||
8. Wenn echte Bilddaten benötigt werden, wird das Original bei Bedarf über WebDAV gelesen.
|
||||
9. Piwigo-Derivate werden normal lokal unter `_data/i/` gecacht.
|
||||
10. Das Original bleibt ausschließlich in Nextcloud.
|
||||
## WebDAV-Bildausgabe und Derivate
|
||||
|
||||
## Bereits vorhandene Bausteine
|
||||
Wichtige Dateien:
|
||||
|
||||
### `runtime/lib/build_webdav_placeholder_source.py`
|
||||
- `include/webdav_image_runtime.inc.php` – Zuordnung Piwigo-Bild ↔ WebDAV-Quelle, Preview-/Derivat-Helfer und URL-Filter.
|
||||
- `webdav-image.php` – berechtigungsgeprüfter serverseitiger Original-/Preview-Abruf.
|
||||
- `runtime/lib/precache-webdav-previews.php` – vorbereitete JPEG-/PNG-Arbeitsbilder ohne dauerhafte Originalkopie.
|
||||
- `runtime/lib/build-webdav-derivatives.php` – CLI-Aufbau der konfigurierten Piwigo-Derivate.
|
||||
|
||||
- liest WebDAV rekursiv;
|
||||
- lädt keine Originalbilder herunter;
|
||||
- erzeugt eine lokale Platzhalterquelle;
|
||||
- erzeugt Manifest und WebDAV-Mapping;
|
||||
- verwendet einen nur wenige Dutzend Byte großen Platzhalter.
|
||||
Der Frontend-Hook führt keine Bildgenerierung mehr aus. Damit bleibt ein Fehler in GD/Imagick/External ImageMagick auf den Hintergrundlauf begrenzt.
|
||||
|
||||
### 0.9.5.6 – Verbindungsschicht
|
||||
## Löschen einer WebDAV-Verbindung seit 0.9.6.1
|
||||
|
||||
Der Parallelweg wurde als eigener Connection-Typ im Plugin angelegt.
|
||||
Eine gelöschte WebDAV-Verbindung darf keine weiterhin sichtbaren oder über alte Piwigo-Datensätze erreichbaren Bilder hinterlassen.
|
||||
|
||||
- `include/nc_connector_webdav.inc.php`
|
||||
- Backend-Aktion `nc_connector_create_webdav_parallel`
|
||||
- `source_mode=webdav-placeholder`
|
||||
- `adapter=remote`
|
||||
- ausgewählte WebDAV-Wurzeln werden verbindungseigen gespeichert;
|
||||
- Nextcloud-Basis-URL und Benutzer werden verbindungseigen gespeichert;
|
||||
- Secret v3 enthält `nextcloud_user` und `nextcloud_password` rückwärtskompatibel zu älteren Secrets.
|
||||
Beim Löschen über die Oberfläche:
|
||||
|
||||
## 0.9.5.7 – parallele Runtime angelegt
|
||||
- werden die zur Verbindung gehörende Piwigo-Site, ihre Alben und Bilddatensätze entfernt;
|
||||
- werden zugehörige Piwigo-Derivate entfernt;
|
||||
- bleiben die Nextcloud-Originaldateien unangetastet;
|
||||
- werden Laufzeit- und Preview-Daten anschließend bereinigt.
|
||||
|
||||
Der neue Weg besitzt jetzt eine eigene Runtime neben dem bestehenden produktiven Connector.
|
||||
Zusätzlich läuft `runtime/cleanup-webdav-piwigo.php` im gemeinsamen Runner. Er erkennt verwaiste WebDAV-Piwigo-Sites, für die keine Connector-Verbindung mehr existiert, und entfernt deren Piwigo-Inhalte sowie Gallery-, Source-, Preview-, State-, Status- und Runtime-Reste. Damit werden auch bereits vor 0.9.6.1 gelöschte Verbindungen nachträglich bereinigt.
|
||||
|
||||
Neu:
|
||||
## Gemeinsamer Runner
|
||||
|
||||
- `runtime/reconcile-webdav.php`
|
||||
- `runtime/sync-webdav.sh`
|
||||
- `runtime/run-all.sh` verarbeitet lokale und WebDAV-Verbindungen getrennt.
|
||||
`runtime/run-all.sh` verarbeitet die Schritte in kontrollierter Reihenfolge:
|
||||
|
||||
Wesentliche Regeln:
|
||||
1. lokale Verbindungen reconciliieren;
|
||||
2. WebDAV-Verbindungen reconciliieren;
|
||||
3. verwaiste WebDAV-Piwigo-Inhalte bereinigen;
|
||||
4. verwaiste allgemeine Runtime-Dateien bereinigen;
|
||||
5. aktive WebDAV-Verbindungen synchronisieren;
|
||||
6. aktive lokale Verbindungen synchronisieren.
|
||||
|
||||
- `runtime/reconcile.php` für die bestehenden lokalen Modi bleibt unverändert.
|
||||
- `runtime/sync.sh` für die bestehenden lokalen Modi bleibt unverändert.
|
||||
- WebDAV-Verbindungen erhalten eigene Runtime-Dateien `webdav-connection-ID.*`.
|
||||
- Es werden keine PostgreSQL-/View-/Storage-Mapping-Werte für WebDAV verlangt.
|
||||
- Nextcloud-Zugang wird aus dem verschlüsselten Connection-Secret in eine Runtime-Passwortdatei mit restriktiven Rechten geschrieben.
|
||||
- WebDAV-Wurzeln werden getrennt als Runtime-Konfiguration gespeichert.
|
||||
- Der Platzhalter-Builder erzeugt die lokale Platzhalterquelle, Manifest und WebDAV-Mapping.
|
||||
- Das Manifest wird anschließend durch den bestehenden `shadow_tree.py` verarbeitet.
|
||||
- Der parallele Shadow Tree liegt absichtlich unter `galleries/bratonien-webdav-ID` und kann deshalb den bestehenden Galeriebaum nicht ersetzen oder überschreiben.
|
||||
- Die Platzhalterquelle liegt unter Piwigo `_data/bratonien-tools/nc-webdav-source/connection-ID`, damit Piwigo den Symlink-Zielen später folgen kann.
|
||||
- **Piwigo-Synchronisierung ist in dieser Stufe hart auf `PIWIGO_SYNC_ENABLED=0` gesetzt.** Die Runtime darf aktuell nur den parallelen Shadow Tree bauen. Die Registrierung in Piwigo wird erst nach Sichtprüfung bewusst freigeschaltet.
|
||||
Der vorhandene systemd-Timer ruft direkt die Runtime aus dem installierten Plugin auf.
|
||||
|
||||
Damit existieren lokaler Produktivweg und WebDAV-Testweg jetzt gleichzeitig, ohne dass ein Umzug stattgefunden hat.
|
||||
## Status- und UI-Regeln
|
||||
|
||||
## Bestehender produktiver Weg
|
||||
- Hintergrund-Polling lädt die Admin-Seite nicht neu.
|
||||
- Ein geöffneter Verbindungsassistent bleibt bei Statusaktualisierungen geöffnet.
|
||||
- Fehlgeschlagene Fallback-/Credential-Prüfungen schließen den Assistenten nicht.
|
||||
- Laufzeitfehler unterscheiden WebDAV-Lesen, Piwigo-Synchronisierung, Preview- und Derivatfehler.
|
||||
|
||||
Unverändert:
|
||||
## Sicherheit
|
||||
|
||||
- PostgreSQL-/View-/Storage-Mapping-Logik;
|
||||
- lokale Symlinks auf bereits vorhandene Originalpfade;
|
||||
- `runtime/reconcile.php` für bestehende lokale Adapter;
|
||||
- `runtime/sync.sh` mit `legacy-view`, `user-shares` und `selected-fileids`;
|
||||
- API-first-Piwigo-Sync;
|
||||
- gemeinsame Runtime für aktive bestehende Verbindungen.
|
||||
- Connector-Zugangsdaten werden verschlüsselt gespeichert.
|
||||
- WebDAV-Credentials werden nur serverseitig verwendet.
|
||||
- Bildzugriffe über `webdav-image.php` werden gegen Piwigos Zugriffsrechte geprüft.
|
||||
- Nextcloud-Originale werden weder beim Sync noch beim Löschen einer Verbindung verändert.
|
||||
- Derivate und Arbeitsbilder sind lokale Cache-/Arbeitsdaten und dürfen entfernt beziehungsweise neu aufgebaut werden.
|
||||
|
||||
## Gemessene WebDAV-Performance
|
||||
## Aktueller Prüfstand
|
||||
|
||||
Testbild: 16.091.204 Byte.
|
||||
Bereits umgesetzt:
|
||||
|
||||
Intern:
|
||||
|
||||
- 1,829 s
|
||||
- 8.796.915 Byte/s
|
||||
|
||||
Extern:
|
||||
|
||||
- 1,865 s
|
||||
- 8.627.524 Byte/s
|
||||
|
||||
Die externe Verbindung war im Test nur ungefähr 2 % langsamer. Der Ansatz bleibt deshalb für bedarfsweisen Originalzugriff geeignet, solange Piwigo-Derivate lokal gecacht werden.
|
||||
|
||||
## Löschverhalten seit 0.9.5.5
|
||||
|
||||
Das Löschen einer Connector-Verbindung darf nicht an Dateirechten Root-eigener Runtime-Dateien scheitern.
|
||||
|
||||
- Datenbankeintrag wird entfernt;
|
||||
- verwaiste Runtime-Dateien werden vor einem späteren Sync bereinigt;
|
||||
- andere Verbindungen bleiben unangetastet;
|
||||
- Nextcloud-Originale und vorhandene Piwigo-Bilder werden nicht gelöscht.
|
||||
|
||||
## Nächster Testschritt
|
||||
|
||||
Die parallele Runtime ist jetzt vorbereitet. Der nächste Schritt ist bewusst klein und kontrolliert:
|
||||
|
||||
1. Plugin auf 0.9.5.7 aktualisieren.
|
||||
2. Eine kleine neue WebDAV-Testverbindung mit einem überschaubaren Verzeichnis anlegen.
|
||||
3. Gemeinsamen Runner einmal ausführen lassen.
|
||||
4. Prüfen, ob unter `galleries/bratonien-webdav-ID` ausschließlich die erwartete Ordnerstruktur und Platzhalter-Symlinks entstehen.
|
||||
5. WebDAV-Mapping und Manifest im Connection-State prüfen.
|
||||
6. Bestehende produktive Galerie und bestehende Verbindungen dabei auf Unverändertheit prüfen.
|
||||
|
||||
Erst wenn dieser Test sauber ist, wird `PIWIGO_SYNC_ENABLED` für WebDAV separat freigeschaltet und die Piwigo-Registrierung getestet.
|
||||
|
||||
## Danach – noch nicht umsetzen
|
||||
|
||||
Erst wenn die Registrierung mit Platzhaltern funktioniert:
|
||||
|
||||
- echte Bilddaten über WebDAV anfordern;
|
||||
- Piwigo-Derivate aus echten Originalen erzeugen;
|
||||
- normalen Derivat-Cache weiterverwenden;
|
||||
- ETag-basierte Änderungserkennung ergänzen;
|
||||
- Fehlerfälle und Parallelität testen.
|
||||
|
||||
## Voraussetzung vor irgendeinem Umzug
|
||||
|
||||
Erfolgreich getestet sein müssen mindestens:
|
||||
|
||||
- Verbindungsanlage;
|
||||
- WebDAV-Verzeichnisauswahl;
|
||||
- WebDAV-Verbindungsassistent;
|
||||
- Verzeichnisauswahl;
|
||||
- rekursiver WebDAV-Scan;
|
||||
- Shadow Tree;
|
||||
- Piwigo-Registrierung;
|
||||
- echte Bildausgabe;
|
||||
- Derivat-Cache;
|
||||
- Änderungserkennung;
|
||||
- Löschen/Deaktivieren;
|
||||
- Fehlerbehandlung;
|
||||
- Verhalten bei vielen noch ungecachten Bildern.
|
||||
- separate Piwigo-Site je WebDAV-Verbindung;
|
||||
- sichtbare Albumstruktur ohne technische Wrapper;
|
||||
- echte Bildausgabe aus Nextcloud;
|
||||
- lokale vorbereitete Arbeitsbilder;
|
||||
- CLI-Derivatstrecke;
|
||||
- Piwigo-Nacharbeiten und Orphan-Abgleich;
|
||||
- ETag-basierte Wiederverwendung vorbereiteter Bilder;
|
||||
- Löschen einer Verbindung einschließlich Piwigo-Inhalten;
|
||||
- nachträgliche Bereinigung bereits verwaister WebDAV-Piwigo-Sites.
|
||||
|
||||
Erst danach kann eine freiwillige Migration bestehender Verbindungen überhaupt diskutiert werden.
|
||||
Weiter zu prüfen beziehungsweise unter realer Last zu härten:
|
||||
|
||||
- vollständiger Derivataufbau für alle in der Installation vorkommenden Standard- und Custom-Größen;
|
||||
- Verhalten bei großen Bildmengen und vielen gleichzeitig noch nicht vorbereiteten Bildern;
|
||||
- Fehlerfälle verschiedener Bildformate und Bild-Backends;
|
||||
- langfristige Änderungserkennung und Performance im produktiven Einsatz.
|
||||
|
||||
## Versionsregel
|
||||
|
||||
Die aktuelle Versionslinie ist **0.9.6.x**. Weitere Sprünge auf eine neue Minor-/Major-Linie erfolgen nur bewusst und ausdrücklich.
|
||||
|
||||
263
README.md
263
README.md
@@ -2,7 +2,7 @@
|
||||
|
||||
Modulares Piwigo-Plugin für Administration, Bildverarbeitung, geschützte Freigaben, Fotoauswahl und die Anbindung von Nextcloud an Piwigo.
|
||||
|
||||
Aktuelle Plugin-Version: **0.9.5.6**
|
||||
Aktuelle Plugin-Version: **0.9.6.1**
|
||||
|
||||
## Grundprinzip
|
||||
|
||||
@@ -17,166 +17,126 @@ Der NC Connector synchronisiert ausdrücklich ausgewählte Nextcloud-Inhalte mit
|
||||
### Datenmodell
|
||||
|
||||
- Nextcloud bleibt die Quelle der Originaldateien.
|
||||
- Originalbilder werden nicht in eine zweite dauerhafte Bibliothek kopiert.
|
||||
- Ein Shadow Tree erzeugt die für Piwigo benötigte Verzeichnisstruktur.
|
||||
- Der bestehende produktive Weg verwendet lokale bereits vorhandene Speicherpfade und Symlinks auf die Originale.
|
||||
- Originalbilder werden nicht dauerhaft in eine zweite Bibliothek unter Piwigo kopiert.
|
||||
- Ein Shadow Tree erzeugt die für Piwigo benötigte Ordnerstruktur.
|
||||
- Ordner werden als physische Piwigo-Alben synchronisiert.
|
||||
- Root-Dateien können als echte Piwigo-Orphans ohne Albumzuordnung registriert werden.
|
||||
- Entfernte Quellen werden aus Shadow Tree und Piwigo entfernt, das Nextcloud-Original bleibt erhalten.
|
||||
- Root-Dateien können als Piwigo-Orphans registriert werden.
|
||||
- Neu importierte physische Connector-Alben werden privat angelegt.
|
||||
- Entfernte Quellen werden aus Shadow Tree und Piwigo entfernt; die Nextcloud-Originale bleiben erhalten.
|
||||
|
||||
### Bestehende produktive Quellenmodi
|
||||
### Bestehende lokale Quellenmodi
|
||||
|
||||
Der bestehende Connector unterstützt weiterhin getrennte Quellenmodi:
|
||||
Der bestehende Connector unterstützt weiterhin:
|
||||
|
||||
- `legacy-view`
|
||||
- `user-shares`
|
||||
- `selected-fileids`
|
||||
|
||||
Diese Modi bleiben während der Entwicklung des neuen WebDAV-Wegs vollständig erhalten. Es gibt keine automatische Migration bestehender Verbindungen.
|
||||
Diese Modi bleiben erhalten. Es gibt keine automatische Migration auf WebDAV.
|
||||
|
||||
### Verbindungsassistent
|
||||
### WebDAV-Modus
|
||||
|
||||
Neue Verbindungen werden bevorzugt mit einem Endnutzer-Assistenten angelegt.
|
||||
Der neue Endnutzerpfad verwendet `source_mode=webdav-placeholder` und `adapter=remote`.
|
||||
|
||||
Der aktuelle Assistent kann Nextcloud per HTTP/HTTPS und OCS prüfen und Verzeichnisse per WebDAV anzeigen. Für den bestehenden produktiven lokalen Weg existieren weiterhin PostgreSQL-/View-/Storage-Mapping-Schritte, sofern sie benötigt werden.
|
||||
Benötigt werden nur:
|
||||
|
||||
Wizard-Geheimnisse werden während der Einrichtung serverseitig in der Sitzung gehalten. Ein fehlgeschlagener Test leert die Eingaben nicht. Ein API-Test verändert die dauerhafte API-Konfiguration erst beim erfolgreichen Abschluss des Assistenten.
|
||||
- Nextcloud-Adresse;
|
||||
- Nextcloud-Benutzer bzw. App-Passwort;
|
||||
- normaler WebDAV-Zugriff auf die Inhalte dieses Benutzers;
|
||||
- eine normale Piwigo-Installation mit ihrer vorhandenen PHP-/Bildverarbeitungsumgebung.
|
||||
|
||||
Die vollständige technische Maske bleibt weiterhin über **Ohne Assistent anlegen** sowie bei bestehenden Verbindungen unter **Technische Einstellungen** erreichbar.
|
||||
Nicht vorausgesetzt werden:
|
||||
|
||||
### Lokaler produktiver Adapter
|
||||
- PostgreSQL-Zugriff auf Nextcloud;
|
||||
- `occ`-Adminzugriff;
|
||||
- Storage-IDs oder Backend-Pfade;
|
||||
- zusätzliche Host-Mounts;
|
||||
- FUSE;
|
||||
- davfs;
|
||||
- rclone.
|
||||
|
||||
Der derzeit produktive Adapter verwendet je nach bestehender Verbindung:
|
||||
### WebDAV-Ablauf
|
||||
|
||||
- PostgreSQL-Reader;
|
||||
- Source-/Activity-Views;
|
||||
- explizite Storage-Zuordnungen auf bereits vorhandene lokale Mounts;
|
||||
- Plugin-eigene Runtime und getrennten State pro Verbindung.
|
||||
|
||||
Dieser Weg bleibt erhalten, bis der neue WebDAV-Weg vollständig End-to-End funktioniert.
|
||||
|
||||
### Neuer WebDAV-Weg
|
||||
|
||||
Der neue Quellenmodus wird zusätzlich zu den bestehenden Modi entwickelt als `webdav-placeholder`.
|
||||
|
||||
Ziel:
|
||||
|
||||
- nur normale Nextcloud-Anmeldung bzw. App-Passwort und WebDAV benötigen;
|
||||
- keine Nextcloud-PostgreSQL-Rechte voraussetzen;
|
||||
- keine Storage-IDs oder Backend-Pfade voraussetzen;
|
||||
- keine zusätzlichen Host-Mounts voraussetzen;
|
||||
- kein FUSE, davfs oder rclone voraussetzen;
|
||||
- keine Originalbilder dauerhaft nach Piwigo kopieren.
|
||||
|
||||
Grundidee:
|
||||
|
||||
1. Nextcloud-Verzeichnisse werden über WebDAV/PROPFIND gelesen.
|
||||
2. Ordner, Dateinamen, Datei-ID, MIME-Typ, Größe, ETag und WebDAV-Pfad werden erfasst.
|
||||
3. Für Bilder wird nur eine winzige lokale Platzhalterquelle erzeugt.
|
||||
4. Der bestehende Shadow Tree bildet daraus die reale Ordner-/Dateinamensstruktur für Piwigo.
|
||||
5. Ein Mapping verbindet den Piwigo-/Shadow-Tree-Pfad mit der WebDAV-Quelle.
|
||||
6. Wenn Piwigo echte Bilddaten benötigt, wird das Original bei Bedarf über WebDAV gelesen.
|
||||
7. Piwigo-Derivate werden normal in `_data/i/` gecacht.
|
||||
8. Das Original bleibt ausschließlich in Nextcloud.
|
||||
|
||||
Vorhandene Bausteine:
|
||||
|
||||
- `runtime/lib/build_webdav_placeholder_source.py` – rekursiver WebDAV-Scan, Platzhalterquelle, Manifest und Mapping;
|
||||
- `include/nc_connector_webdav.inc.php` – paralleler, zunächst deaktivierter Connection-Typ `webdav-placeholder`;
|
||||
- Secret-Format v3 mit verbindungseigenem `nextcloud_user` und `nextcloud_password`.
|
||||
|
||||
Neue WebDAV-Testverbindungen werden als `adapter=remote` und deaktiviert gespeichert. Sie verändern keine bestehenden Verbindungen und werden noch nicht von der produktiven Runtime aktiviert.
|
||||
|
||||
### Gemessene WebDAV-Performance
|
||||
|
||||
Ein realer Test mit einem 16.091.204-Byte-Bild ergab vom Piwigo-System:
|
||||
|
||||
- interne Nextcloud-Adresse: 1,829 s bei 8.796.915 Byte/s;
|
||||
- externe Nextcloud-Adresse: 1,865 s bei 8.627.524 Byte/s.
|
||||
|
||||
Damit war die externe Verbindung in diesem Test nur ungefähr 2 % langsamer. Der WebDAV-Ansatz wird deshalb weiterverfolgt. Wichtig bleibt, dass Piwigo-Derivate lokal gecacht werden und WebDAV nicht bei jedem Thumbnail-Aufruf erneut verwendet wird.
|
||||
|
||||
### Activity Gate
|
||||
|
||||
Der bestehende regelmäßige Lauf berücksichtigt:
|
||||
|
||||
- Nextcloud-Aktivität;
|
||||
- Signatur der sichtbaren Quellen;
|
||||
- Quiet-Time;
|
||||
- maximale Wartezeit;
|
||||
- periodischen Full-Sync;
|
||||
- notwendigen Reparaturlauf bei beschädigtem Shadow Tree oder fehlenden Piwigo-Alben.
|
||||
|
||||
Der neue WebDAV-Modus erhält später eine eigene Änderungserkennung, insbesondere über WebDAV-Metadaten wie ETag.
|
||||
1. Der Assistent prüft Nextcloud und liest die sichtbaren Verzeichnisse per WebDAV.
|
||||
2. Ausgewählte Verzeichnisse werden rekursiv per PROPFIND eingelesen.
|
||||
3. Ordner, Dateiname, Nextcloud-Datei-ID, MIME-Typ, Größe, ETag und WebDAV-Pfad werden erfasst.
|
||||
4. `runtime/lib/build_webdav_placeholder_source.py` erzeugt eine lokale Platzhalterquelle ohne dauerhafte Originalkopie.
|
||||
5. `runtime/lib/shadow_tree.py` baut daraus den verbindungseigenen Shadow Tree.
|
||||
6. Der WebDAV-Galeriebaum liegt unter `_data/bratonien-tools/nc-webdav-gallery/connection-ID`.
|
||||
7. Jede WebDAV-Verbindung wird als eigene physische Piwigo-Site registriert. Die ausgewählte Nextcloud-Wurzel erscheint dadurch direkt als Album; technische `bratonien-webdav-ID`-Wrapper bleiben unsichtbar.
|
||||
8. `runtime/lib/precache-webdav-previews.php` erzeugt vorbereitete Arbeitsbilder als JPEG beziehungsweise PNG mit maximal 4096 px Kantenlänge.
|
||||
9. `runtime/lib/build-webdav-derivatives.php` korrigiert die Piwigo-Bildabmessungen und erzeugt die konfigurierten Standard- und Custom-Derivate im Hintergrundlauf.
|
||||
10. Der Frontend-Aufruf erzeugt keine Derivate. Fehlt eines, wird das vorbereitete Arbeitsbild als sicherer Fallback ausgeliefert.
|
||||
11. Wenn das Original benötigt wird, streamt `webdav-image.php` es serverseitig direkt aus Nextcloud. Zugangsdaten werden dem Browser nicht offengelegt.
|
||||
|
||||
### Piwigo-Synchronisierung
|
||||
|
||||
Der produktive Lauf ist API-first:
|
||||
Der WebDAV-Pfad nutzt die vorhandene Piwigo-Synchronisationslogik mit einer verbindungseigenen Site.
|
||||
|
||||
1. `bratonien.nc.syncProductive` für physische Alben und Bilder;
|
||||
2. `bratonien.nc.syncOrphans` für Root-Dateien;
|
||||
3. Benutzername/Passwort nur als optionaler Fallback.
|
||||
Nach dem Dateiabgleich laufen die vorhandenen Nacharbeiten, darunter:
|
||||
|
||||
Die produktive direkte API-Synchronisierung ist aktuell ausdrücklich für **Piwigo 16.4.0** freigegeben. Bei einer anderen Piwigo-Version wird sie nicht stillschweigend als kompatibel angenommen.
|
||||
- Metadaten-Synchronisierung;
|
||||
- Bild- und Kategorieintegrität;
|
||||
- Uppercats/Kategoriestruktur;
|
||||
- globale Ränge;
|
||||
- Pfadpflege;
|
||||
- Rating-Score;
|
||||
- Benutzer-Cache-Invalidierung;
|
||||
- Orphan-Abgleich.
|
||||
|
||||
Der direkte produktive Sync führt außerdem die für den normalen Piwigo-Import relevanten Nacharbeiten aus, darunter Albuminformationen, globale Ränge, Bildinformationen, Pfade und Cache-Invalidierung. Er ruft dafür keine Admin-Seite fernsteuernd auf.
|
||||
Die direkte produktive Synchronisierung ist aktuell ausdrücklich auf **Piwigo 16.4.0** abgestimmt.
|
||||
|
||||
### Fallback-Zugang
|
||||
|
||||
Piwigo wird API-first angesprochen. Ist für eine Verbindung keine API konfiguriert, kann Benutzername/Passwort als Fallback verwendet werden.
|
||||
|
||||
Der Assistent prüft Fallback-Zugangsdaten vor dem Speichern. Eine fehlgeschlagene Prüfung schließt oder leert den Assistenten nicht.
|
||||
|
||||
### Statusanzeige
|
||||
|
||||
Die Administration zeigt den Laufzeitstatus regelmäßig im Hintergrund an. Dafür wird die Admin-Seite nicht neu geladen; offene Dialoge, Assistenten und aufgeklappte Bereiche bleiben erhalten.
|
||||
|
||||
Fehler werden nach Prozessschritt getrennt dargestellt, unter anderem für WebDAV-Einlesen, Piwigo-Synchronisierung, Preview-Erzeugung und Derivat-Erzeugung.
|
||||
|
||||
### Löschen einer Verbindung
|
||||
|
||||
Seit **0.9.6.1** besitzt der WebDAV-Pfad einen vollständigen Lösch-Lebenszyklus:
|
||||
|
||||
- Beim Löschen einer WebDAV-Verbindung werden ihre Piwigo-Site, Alben und Bilddatensätze entfernt.
|
||||
- Zugehörige Piwigo-Derivate werden entfernt.
|
||||
- Nextcloud-Originale bleiben unverändert.
|
||||
- Runtime-, Shadowtree-, Source-, Preview- und Statusdaten werden bereinigt.
|
||||
- `runtime/cleanup-webdav-piwigo.php` erkennt zusätzlich bereits verwaiste WebDAV-Piwigo-Sites, für die keine Connector-Verbindung mehr existiert, und bereinigt sie im gemeinsamen Runner nachträglich.
|
||||
|
||||
### Runtime
|
||||
|
||||
Aktive bestehende Verbindungen werden über einen gemeinsamen systemd-Timer verarbeitet:
|
||||
Aktive Verbindungen werden über den gemeinsamen Runner verarbeitet:
|
||||
|
||||
- `bratonien-nc-connector.timer`
|
||||
- `bratonien-nc-connector.service`
|
||||
- `runtime/run-all.sh`
|
||||
- `runtime/sync.sh`
|
||||
|
||||
Verbindungsspezifische Konfigurationen liegen unter `/etc/bratonien-tools/nc-connector/`, State-Daten unter `/var/lib/bratonien-tools/nc-connector/connection-ID`.
|
||||
|
||||
Der Shadow-Tree-Austausch besitzt einen Rollback: Scheitert der Wechsel auf den neuen Baum, wird der vorherige Galeriebaum wiederhergestellt.
|
||||
Die Reihenfolge des gemeinsamen Laufs ist:
|
||||
|
||||
Der WebDAV-Parallelweg wird in der nächsten Bauphase mit einem eigenen Reconcile-/Sync-Zweig ergänzt. Bis dahin bleibt er deaktiviert und kann keine bestehende Runtime beeinflussen.
|
||||
|
||||
### Statusanzeige
|
||||
|
||||
Die Administration zeigt letzten und nächsten Lauf. Der Status wird regelmäßig im Hintergrund abgefragt. Dafür wird die Admin-Seite **nicht** neu geladen; offene Dialoge, Assistenten und aufgeklappte Bereiche bleiben erhalten.
|
||||
|
||||
### Bestehende Verbindungen
|
||||
|
||||
Bestehende Verbindungen können:
|
||||
|
||||
- umbenannt;
|
||||
- geprüft;
|
||||
- technisch bearbeitet, solange sie nicht aktiv sind;
|
||||
- deaktiviert und anschließend gelöscht werden.
|
||||
|
||||
Seit 0.9.5.5 hängt das Löschen einer Verbindung nicht mehr davon ab, dass der Webserver in Root-eigene Runtime-Verzeichnisse schreiben kann. Die Datenbankverbindung wird entfernt; verwaiste Runtime-Dateien werden vor einem späteren Sync bereinigt.
|
||||
|
||||
Das Löschen einer Connector-Verbindung entfernt keine Nextcloud-Originale und keine Piwigo-Bilder.
|
||||
|
||||
### Migrationsregel für WebDAV
|
||||
|
||||
Der bestehende lokale Weg bleibt so lange vollständig erhalten, bis `webdav-placeholder` End-to-End funktioniert.
|
||||
|
||||
Vor einer freiwilligen Migration bestehender Verbindungen müssen mindestens erfolgreich getestet sein:
|
||||
|
||||
- Verbindungsanlage;
|
||||
- Verzeichnisauswahl;
|
||||
- Shadow Tree;
|
||||
- Piwigo-Registrierung;
|
||||
- echte Bildausgabe;
|
||||
- Derivat-Cache;
|
||||
- Änderungserkennung;
|
||||
- Löschen/Deaktivieren;
|
||||
- Fehlerbehandlung.
|
||||
1. lokale Verbindungen reconciliieren;
|
||||
2. WebDAV-Verbindungen reconciliieren;
|
||||
3. verwaiste WebDAV-Piwigo-Inhalte bereinigen;
|
||||
4. allgemeine verwaiste Runtime-Dateien bereinigen;
|
||||
5. WebDAV-Verbindungen synchronisieren;
|
||||
6. lokale Verbindungen synchronisieren.
|
||||
|
||||
## Bildcache
|
||||
|
||||
Bratonien Tools kann:
|
||||
|
||||
- Piwigo-Bildderivate gezielt leeren;
|
||||
- vorhandene Bildgrößen neu erzeugen;
|
||||
- Cache-Aufbau als Worker-Prozess starten und abbrechen;
|
||||
- Worker-Zahl automatisch oder manuell konfigurieren;
|
||||
- Originalbilder bleiben unangetastet.
|
||||
- den Cache-Aufbau als Worker-Prozess starten und abbrechen;
|
||||
- die Worker-Zahl automatisch oder manuell konfigurieren.
|
||||
|
||||
Originalbilder bleiben unangetastet.
|
||||
|
||||
## Wasserzeichenverwaltung
|
||||
|
||||
@@ -186,7 +146,7 @@ Vor einer freiwilligen Migration bestehender Verbindungen müssen mindestens erf
|
||||
- Album-Ausnahmen und Vererbung;
|
||||
- Position, Transparenz und Skalierung;
|
||||
- eigener Runtime-Filter für Piwigo-Derivate;
|
||||
- bisherige Piwigo-Wasserzeichenkonfiguration wird beim Aktivieren gesichert.
|
||||
- Sicherung der bisherigen Piwigo-Wasserzeichenkonfiguration beim Aktivieren.
|
||||
|
||||
## Bilddateien und Pfade
|
||||
|
||||
@@ -229,37 +189,34 @@ Die Piwigo-Bilddetailseite erhält responsive Navigationszonen für vorheriges B
|
||||
Der integrierte Updater:
|
||||
|
||||
- liest den Zielstand aus GitHub;
|
||||
- bindet ein Update an einen konkreten Commit statt an einen während des Updates beweglichen Branch-Stand;
|
||||
- bindet ein Update an einen konkreten Commit;
|
||||
- prüft Version und SHA-256 des Zielstands;
|
||||
- erstellt vor dem Austausch ein Backup;
|
||||
- nutzt Post/Redirect/Get, damit ein Browser-Reload keine schreibende Aktion erneut ausführt;
|
||||
- nutzt Post/Redirect/Get;
|
||||
- verlangt Webmaster-Rechte, `ZipArchive` und ausreichende Schreibrechte.
|
||||
|
||||
## Architektur
|
||||
|
||||
Wichtige Dateien und Verzeichnisse:
|
||||
## Wichtige Dateien und Verzeichnisse
|
||||
|
||||
- `main.inc.php` – Plugin-Einstieg und Runtime-Hooks
|
||||
- `admin.php` – zentraler Admin-Controller mit Post/Redirect/Get
|
||||
- `include/tool_registry.inc.php` – Registry administrativer Aktionen
|
||||
- `admin.php` – zentraler Admin-Controller
|
||||
- `include/nc_connector.inc.php` – Datenmodell und gemeinsame Connector-Funktionen
|
||||
- `include/nc_connector_wizard.inc.php` – Endnutzer-Assistent und Connection-Bearbeitung
|
||||
- `include/nc_connector_manage.inc.php` – Credential-Format, Storage-Mappings, Verifikation und Löschen
|
||||
- `include/nc_connector_connection_scope.inc.php` – verbindungseigene Authentifizierung
|
||||
- `include/nc_connector_create_api.inc.php` – API-first-Verbindungserstellung und Secret v3
|
||||
- `include/nc_connector_webdav.inc.php` – paralleler WebDAV-Connection-Typ
|
||||
- `include/nc_connector_piwigo_api.inc.php` – API-Zugang und Fallback-Verwaltung
|
||||
- `include/nc_connector_system.inc.php` – Timer- und Laufzeitstatus
|
||||
- `include/nc_connector_wizard.inc.php` – Verbindungsassistent
|
||||
- `include/nc_connector_wizard_webdav_flow.inc.php` – WebDAV-first-Wizardablauf
|
||||
- `include/nc_connector_delete_safe.inc.php` – sicheres Löschen einschließlich WebDAV-Piwigo-Inhalten
|
||||
- `include/nc_productive_ws.inc.php` – produktiver Piwigo-Dateisync
|
||||
- `include/nc_orphan_ws.inc.php` – Orphan-Synchronisierung
|
||||
- `runtime/lib/activity_gate.py` – Activity Gate
|
||||
- `runtime/lib/build_manifest.py` – bestehende Auflösung der Nextcloud-Quellen auf Storage-Mounts
|
||||
- `runtime/lib/build_selected_manifest.py` – ausgewählte Nextcloud-Datei-IDs auf bestehende Storage-Pfade auflösen
|
||||
- `runtime/lib/build_webdav_placeholder_source.py` – experimentelle WebDAV-Platzhalterquelle
|
||||
- `runtime/lib/shadow_tree.py` – atomarer Shadow Tree mit Rollback
|
||||
- `runtime/lib/piwigo-sync.php` – API-first-Piwigo-Sync mit Fallback
|
||||
- `runtime/run-all.sh` – Multi-Connection-Runner und Bereinigung verwaister Runtime-Dateien
|
||||
- `runtime/sync.sh` – Ablauf einer bestehenden lokalen Verbindung
|
||||
- `include/webdav_image_runtime.inc.php` – WebDAV-Bildzuordnung, Preview-/Derivathilfen und URL-Filter
|
||||
- `webdav-image.php` – berechtigungsgeprüfter WebDAV-Bildstream
|
||||
- `runtime/reconcile-webdav.php` – WebDAV-Runtime-Reconcile
|
||||
- `runtime/cleanup-webdav-piwigo.php` – Bereinigung gelöschter/verwaister WebDAV-Verbindungen in Piwigo
|
||||
- `runtime/sync-webdav.sh` – Ablauf einer WebDAV-Verbindung
|
||||
- `runtime/run-all.sh` – gemeinsamer Multi-Connection-Runner
|
||||
- `runtime/lib/build_webdav_placeholder_source.py` – rekursiver WebDAV-Scan und Platzhalterquelle
|
||||
- `runtime/lib/precache-webdav-previews.php` – vorbereitete JPEG-/PNG-Arbeitsbilder
|
||||
- `runtime/lib/build-webdav-derivatives.php` – CLI-Derivat-Builder
|
||||
- `runtime/lib/shadow_tree.py` – atomarer Shadow Tree
|
||||
- `runtime/lib/piwigo-sync.php` – Piwigo-Sync mit API/Fallback
|
||||
- `main-cache-build.php` – allgemeiner Piwigo-Derivat-/Cache-Builder
|
||||
- `include/self_update.inc.php` – Self-Updater
|
||||
- `include/album_shares.inc.php` – geschützte Albumfreigaben
|
||||
- `include/public_selection.inc.php` – Fotoauswahl
|
||||
@@ -272,20 +229,18 @@ Wichtige Dateien und Verzeichnisse:
|
||||
|
||||
- administrative Schreibaktionen verwenden Piwigos CSRF-Schutz;
|
||||
- Connector-Zugangsdaten werden verschlüsselt gespeichert;
|
||||
- Secret v3 speichert Nextcloud-Zugangsdaten verbindungseigen und verschlüsselt;
|
||||
- Wizard-Geheimnisse werden nicht in Browser-Web-Storage persistiert;
|
||||
- bestehende lokale Storage-Mounts werden explizit zugeordnet und validiert;
|
||||
- Nextcloud-Zugangsdaten werden verbindungseigen gespeichert und nur serverseitig verwendet;
|
||||
- Wizard-Geheimnisse werden nicht im Browser-Web-Storage persistiert;
|
||||
- SQL-View-Namen werden vor Verwendung validiert;
|
||||
- produktive Piwigo-API ist versionsgebunden;
|
||||
- Originalbilder werden vom Connector nicht gelöscht;
|
||||
- der neue WebDAV-Weg soll Originalbilder nicht dauerhaft lokal speichern;
|
||||
- Update-Pakete werden an Commit und Hash gebunden;
|
||||
- bestehende Verbindungen bleiben während der WebDAV-Entwicklung unangetastet.
|
||||
- WebDAV-Originalbilder werden nicht dauerhaft lokal gespeichert;
|
||||
- Update-Pakete werden an Commit und Hash gebunden.
|
||||
|
||||
## Entwicklungsstand
|
||||
|
||||
`0.9.5.x` ist der aktuelle Entwicklungsblock. Der bestehende lokale NC Connector bleibt produktiv und wird nicht durch den experimentellen WebDAV-Weg ersetzt.
|
||||
`0.9.6.x` ist die aktuelle Versionslinie.
|
||||
|
||||
Mit 0.9.5.6 ist die parallele Verbindungsschicht angelegt: Secret v3 kann Nextcloud-Zugangsdaten speichern und `webdav-placeholder` existiert als eigener deaktivierter Connection-Typ. Der nächste Schritt ist ein strikt getrennter Reconcile-/Runtime-Zweig für diesen Modus und danach der erste Platzhalter-PoC durch den bestehenden Shadow Tree und Piwigo-Sync.
|
||||
Mit **0.9.6.1** ist der WebDAV-Pfad einschließlich Piwigo-Registrierung, vorbereiteter Bildquelle, CLI-Derivatstrecke und Lösch-/Cleanup-Lebenszyklus im Repository umgesetzt. Der bestehende lokale Connector bleibt parallel erhalten.
|
||||
|
||||
Den detaillierten aktuellen Plan enthält `CURRENT_STATUS.md`.
|
||||
Der jeweils detaillierte Prüf- und Entwicklungsstand steht in [`CURRENT_STATUS.md`](CURRENT_STATUS.md).
|
||||
|
||||
@@ -5,6 +5,11 @@ if (!defined('PHPWG_ROOT_PATH'))
|
||||
}
|
||||
|
||||
function bratonien_tools_nc_connector_create_local_api_first()
|
||||
{
|
||||
throw new RuntimeException('Neue Verbindungen über die alte lokale PostgreSQL-/Storage-Struktur sind ab 0.9.6.2 gesperrt. Bestehende lokale Verbindungen bleiben für die schrittweise Migration weiterhin aktiv. Neue Verbindungen müssen über den WebDAV-Assistenten angelegt werden.');
|
||||
}
|
||||
|
||||
function bratonien_tools_nc_connector_create_local_api_first_legacy()
|
||||
{
|
||||
$required = array(
|
||||
'nc_name' => 'Name',
|
||||
|
||||
@@ -4,12 +4,90 @@ if (!defined('PHPWG_ROOT_PATH'))
|
||||
die('Hacking attempt!');
|
||||
}
|
||||
|
||||
function bratonien_tools_nc_connector_webdav_site_id(array $connection)
|
||||
{
|
||||
$config = isset($connection['config']) && is_array($connection['config']) ? $connection['config'] : array();
|
||||
if ((string)($connection['adapter'] ?? '') !== 'remote') return 0;
|
||||
if ((string)($config['source_mode'] ?? '') !== 'webdav-placeholder') return 0;
|
||||
|
||||
$gallery_root = rtrim((string)($config['parallel_gallery_root'] ?? ''), '/');
|
||||
$piwigo_root = rtrim(PHPWG_ROOT_PATH, '/');
|
||||
if ($gallery_root === '' || strpos($gallery_root, $piwigo_root.'/') !== 0) return 0;
|
||||
|
||||
$relative = ltrim(substr($gallery_root, strlen($piwigo_root)), '/');
|
||||
if ($relative === '') return 0;
|
||||
$site_url = './'.rtrim($relative, '/').'/';
|
||||
|
||||
$result = pwg_query(
|
||||
"SELECT id FROM ".SITES_TABLE.
|
||||
" WHERE galleries_url='".pwg_db_real_escape_string($site_url)."' LIMIT 1"
|
||||
);
|
||||
if (!pwg_db_num_rows($result)) return 0;
|
||||
|
||||
$row = pwg_db_fetch_assoc($result);
|
||||
return (int)$row['id'];
|
||||
}
|
||||
|
||||
function bratonien_tools_nc_connector_remove_webdav_piwigo_content(array $connection)
|
||||
{
|
||||
$site_id = bratonien_tools_nc_connector_webdav_site_id($connection);
|
||||
if ($site_id < 1) return array('site_id'=>0, 'images'=>0);
|
||||
|
||||
include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
|
||||
|
||||
$image_rows = array();
|
||||
$query = '
|
||||
SELECT DISTINCT i.id, i.path, i.representative_ext
|
||||
FROM '.IMAGES_TABLE.' AS i
|
||||
LEFT JOIN '.CATEGORIES_TABLE.' AS sc ON sc.id = i.storage_category_id
|
||||
LEFT JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON ic.image_id = i.id
|
||||
LEFT JOIN '.CATEGORIES_TABLE.' AS vc ON vc.id = ic.category_id
|
||||
WHERE sc.site_id = '.$site_id.' OR vc.site_id = '.$site_id.'
|
||||
;';
|
||||
$result = pwg_query($query);
|
||||
while ($row = pwg_db_fetch_assoc($result))
|
||||
{
|
||||
$row['id'] = (int)$row['id'];
|
||||
$image_rows[$row['id']] = $row;
|
||||
}
|
||||
|
||||
foreach ($image_rows as $row)
|
||||
{
|
||||
try
|
||||
{
|
||||
delete_element_derivatives($row);
|
||||
}
|
||||
catch (Throwable $e)
|
||||
{
|
||||
error_log('Bratonien WebDAV delete derivative cleanup #'.(int)$row['id'].': '.$e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
delete_site($site_id);
|
||||
|
||||
if ($image_rows)
|
||||
{
|
||||
$ids = array_keys($image_rows);
|
||||
$remaining = query2array(
|
||||
'SELECT id FROM '.IMAGES_TABLE.' WHERE id IN ('.implode(',', array_map('intval', $ids)).')',
|
||||
null,
|
||||
'id'
|
||||
);
|
||||
if ($remaining)
|
||||
{
|
||||
delete_elements(array_map('intval', $remaining), false);
|
||||
}
|
||||
}
|
||||
|
||||
invalidate_user_cache(true);
|
||||
return array('site_id'=>$site_id, 'images'=>count($image_rows));
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a connector connection from Piwigo without depending on the web
|
||||
* server being allowed to write into root-owned runtime directories.
|
||||
*
|
||||
* Runtime files are removed by runtime/cleanup-stale.php on the next runner
|
||||
* cycle before any connector sync is started.
|
||||
* WebDAV-managed Piwigo records are removed before the connection itself so
|
||||
* deleted remote content cannot remain visible or addressable in Piwigo.
|
||||
*/
|
||||
function bratonien_tools_nc_connector_delete_safe()
|
||||
{
|
||||
@@ -20,12 +98,18 @@ function bratonien_tools_nc_connector_delete_safe()
|
||||
throw new RuntimeException('Connector-Verbindung wurde nicht gefunden.');
|
||||
}
|
||||
|
||||
$cleanup = array('site_id'=>0, 'images'=>0);
|
||||
if (
|
||||
(string)($connection['adapter'] ?? '') === 'remote'
|
||||
&& (string)($connection['config']['source_mode'] ?? '') === 'webdav-placeholder'
|
||||
)
|
||||
{
|
||||
$cleanup = bratonien_tools_nc_connector_remove_webdav_piwigo_content($connection);
|
||||
}
|
||||
|
||||
$table = bratonien_tools_nc_connector_table();
|
||||
pwg_query("DELETE FROM `$table` WHERE id=".$id." LIMIT 1");
|
||||
|
||||
// Public status data is only cache/runtime information. Remove it when PHP
|
||||
// has permission, but never make successful DB deletion depend on ownership
|
||||
// of files previously created by the root-run connector service.
|
||||
$status_dir = rtrim(PHPWG_ROOT_PATH, '/').'/_data/bratonien-tools/nc-connector-status';
|
||||
$public_status = $status_dir.'/connection-'.$id.'.json';
|
||||
if (is_file($public_status))
|
||||
@@ -33,15 +117,19 @@ function bratonien_tools_nc_connector_delete_safe()
|
||||
@unlink($public_status);
|
||||
}
|
||||
|
||||
// Keep the old tombstone mechanism as a best-effort fast path for systems
|
||||
// where the web server can write here. cleanup-stale.php is the authoritative
|
||||
// fallback and does not require this file.
|
||||
if (is_dir($status_dir) || @mkdir($status_dir, 0755, true))
|
||||
{
|
||||
@file_put_contents($status_dir.'/deleted-'.$id, date('c')."\n", LOCK_EX);
|
||||
}
|
||||
|
||||
if ((int)$cleanup['site_id'] > 0)
|
||||
{
|
||||
return array(
|
||||
'message'=>'Connector-Verbindung wurde gelöscht. Die zugehörigen Piwigo-Alben und '.(int)$cleanup['images'].' Bilder wurden aus Piwigo entfernt. Nextcloud-Dateien blieben unverändert. Laufzeit- und Vorschaudaten werden automatisch bereinigt.',
|
||||
);
|
||||
}
|
||||
|
||||
return array(
|
||||
'message'=>'Connector-Verbindung wurde gelöscht. Verbliebene Laufzeitdateien werden vor dem nächsten Connector-Lauf automatisch entfernt. Nextcloud- und Piwigo-Bilder blieben unverändert.',
|
||||
'message'=>'Connector-Verbindung wurde gelöscht. Verbliebene Laufzeitdateien werden vor dem nächsten Connector-Lauf automatisch entfernt. Quelldateien blieben unverändert.',
|
||||
);
|
||||
}
|
||||
|
||||
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.'),
|
||||
);
|
||||
}
|
||||
@@ -5,10 +5,81 @@ if (!defined('PHPWG_ROOT_PATH'))
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a disabled WebDAV-backed connector beside the existing local modes.
|
||||
* Return the only existing local connector as migration fallback.
|
||||
*/
|
||||
function bratonien_tools_nc_connector_single_local_fallback()
|
||||
{
|
||||
bratonien_tools_nc_connector_ensure_table();
|
||||
$table = bratonien_tools_nc_connector_table();
|
||||
$result = pwg_query("SELECT id, enabled, takeover_state, config_json FROM `$table` WHERE adapter='local' ORDER BY id");
|
||||
$rows = array();
|
||||
|
||||
while ($row = pwg_db_fetch_assoc($result))
|
||||
{
|
||||
$rows[] = $row;
|
||||
if (count($rows) > 1) return null;
|
||||
}
|
||||
|
||||
if (count($rows) !== 1) return null;
|
||||
|
||||
$row = $rows[0];
|
||||
$config = json_decode((string)$row['config_json'], true);
|
||||
if (!is_array($config)) $config = array();
|
||||
|
||||
return array(
|
||||
'id'=>(int)$row['id'],
|
||||
'enabled'=>(bool)$row['enabled'],
|
||||
'takeover_state'=>(string)$row['takeover_state'],
|
||||
'config'=>$config,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Link a WebDAV connection with the single existing local fallback.
|
||||
*/
|
||||
function bratonien_tools_nc_connector_pair_migration_fallback($webdav_id, array &$webdav_config, $now)
|
||||
{
|
||||
$legacy = bratonien_tools_nc_connector_single_local_fallback();
|
||||
if (!$legacy) return null;
|
||||
|
||||
$legacy_id = (int)$legacy['id'];
|
||||
if ($legacy_id < 1 || $legacy_id === (int)$webdav_id) return null;
|
||||
|
||||
$webdav_config['migration'] = array(
|
||||
'role'=>'webdav-primary-candidate',
|
||||
'legacy_fallback_connection_id'=>$legacy_id,
|
||||
'fallback_policy'=>'keep-running',
|
||||
'paired_at'=>(string)$now,
|
||||
'cutover_state'=>'parallel',
|
||||
);
|
||||
|
||||
$legacy_config = $legacy['config'];
|
||||
$legacy_config['migration'] = array(
|
||||
'role'=>'legacy-fallback',
|
||||
'webdav_successor_connection_id'=>(int)$webdav_id,
|
||||
'fallback_policy'=>'keep-running',
|
||||
'paired_at'=>(string)$now,
|
||||
'cutover_state'=>'parallel',
|
||||
);
|
||||
|
||||
$legacy_json = json_encode($legacy_config, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
||||
if (!is_string($legacy_json))
|
||||
{
|
||||
throw new RuntimeException('Die bestehende Verbindung konnte nicht als Migrations-Fallback markiert werden.');
|
||||
}
|
||||
|
||||
$table = bratonien_tools_nc_connector_table();
|
||||
pwg_query("UPDATE `$table` SET config_json='".pwg_db_real_escape_string($legacy_json)."', updated='".pwg_db_real_escape_string((string)$now)."' WHERE id=".$legacy_id." LIMIT 1");
|
||||
|
||||
return $legacy_id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create or update a WebDAV-backed connector from the user-facing wizard.
|
||||
*
|
||||
* This deliberately does not activate, migrate or modify any existing
|
||||
* connection. It only persists the data required for the parallel WebDAV path.
|
||||
* 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()
|
||||
{
|
||||
@@ -24,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'])
|
||||
@@ -34,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)
|
||||
@@ -59,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',
|
||||
@@ -78,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] ?? ''));
|
||||
@@ -96,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','"
|
||||
@@ -114,20 +222,40 @@ 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.');
|
||||
|
||||
$config['state_dir'] = '/var/lib/bratonien-tools/nc-connector/connection-'.$id;
|
||||
$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))
|
||||
try
|
||||
{
|
||||
$config['state_dir'] = '/var/lib/bratonien-tools/nc-connector/connection-'.$id;
|
||||
$config['status_file'] = $config['state_dir'].'/connector-status.json';
|
||||
$legacy_fallback_id = bratonien_tools_nc_connector_pair_migration_fallback($id, $config, $now);
|
||||
|
||||
$config_json = json_encode($config, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
||||
if (!is_string($config_json))
|
||||
{
|
||||
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");
|
||||
}
|
||||
catch (Throwable $e)
|
||||
{
|
||||
pwg_query("DELETE FROM `$table` WHERE id=".$id." LIMIT 1");
|
||||
throw new RuntimeException('Die WebDAV-Testverbindung konnte nach dem Anlegen nicht serialisiert werden.');
|
||||
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-Nachfolger wurde angelegt. Die bestehende lokale Verbindung #'.$legacy_fallback_id.' bleibt als Fallback erhalten.',
|
||||
);
|
||||
}
|
||||
pwg_query("UPDATE `$table` SET config_json='".pwg_db_real_escape_string($config_json)."' WHERE id=".$id." LIMIT 1");
|
||||
|
||||
return array(
|
||||
'connection_id'=>$id,
|
||||
'message'=>'Parallele WebDAV-Testverbindung wurde deaktiviert angelegt. Bestehende Verbindungen blieben unverändert.',
|
||||
'message'=>'WebDAV-Verbindung wurde angelegt.',
|
||||
);
|
||||
}
|
||||
|
||||
@@ -4,6 +4,23 @@ if (!defined('PHPWG_ROOT_PATH'))
|
||||
die('Hacking attempt!');
|
||||
}
|
||||
|
||||
if (isset($GLOBALS['template']) && is_object($GLOBALS['template']) && method_exists($GLOBALS['template'], 'func_combine_script'))
|
||||
{
|
||||
$script_version = function_exists('bratonien_tools_current_version') ? bratonien_tools_current_version() : '0.9.6.15';
|
||||
$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'=>$script_version,
|
||||
));
|
||||
$GLOBALS['template']->func_combine_script(array(
|
||||
'id'=>'bratonien_nc_connector_source_ui',
|
||||
'path'=>BRATONIEN_TOOLS_PATH.'js/nc_connector_source_ui.js',
|
||||
'load'=>'footer',
|
||||
'version'=>$script_version,
|
||||
));
|
||||
}
|
||||
|
||||
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 +47,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 +74,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'),
|
||||
|
||||
@@ -65,7 +65,6 @@ function bratonien_tools_webdav_image_source_info($image_id)
|
||||
$size = 0;
|
||||
$etag = '';
|
||||
|
||||
// Metadata is optional. Routing must not depend on the root-owned runtime map.
|
||||
$state_dir = rtrim((string)($config['state_dir'] ?? ''), '/');
|
||||
if ($state_dir !== '')
|
||||
{
|
||||
@@ -102,6 +101,7 @@ function bratonien_tools_webdav_image_url($image_id, $preview=false)
|
||||
{
|
||||
$info = bratonien_tools_webdav_image_source_info($image_id);
|
||||
if (!$info) return null;
|
||||
|
||||
$url = get_root_url().'plugins/'.BRATONIEN_TOOLS_ID.'/webdav-image.php?id='.(int)$image_id;
|
||||
if ($preview) $url .= '&preview=1';
|
||||
if ($info['etag'] !== '') $url .= '&v='.rawurlencode(substr(sha1($info['etag']), 0, 12));
|
||||
@@ -113,8 +113,22 @@ function bratonien_tools_webdav_preview_path(array $info)
|
||||
$connection_id = (int)($info['connection_id'] ?? 0);
|
||||
$webdav_path = trim((string)($info['webdav_path'] ?? ''), '/');
|
||||
if ($connection_id < 1 || $webdav_path === '') return null;
|
||||
$path = PHPWG_ROOT_PATH.'_data/bratonien-tools/nc-webdav-preview/connection-'.$connection_id.'/'.sha1($webdav_path).'.webp';
|
||||
return is_file($path) && is_readable($path) ? $path : null;
|
||||
|
||||
$base = PHPWG_ROOT_PATH.'_data/bratonien-tools/nc-webdav-preview/connection-'.$connection_id.'/'.sha1($webdav_path);
|
||||
foreach (array('jpg', 'png', 'webp') as $ext)
|
||||
{
|
||||
$path = $base.'.'.$ext;
|
||||
if (is_file($path) && is_readable($path)) return $path;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function bratonien_tools_webdav_preview_content_type($path)
|
||||
{
|
||||
$ext = strtolower(pathinfo((string)$path, PATHINFO_EXTENSION));
|
||||
if ($ext === 'png') return 'image/png';
|
||||
if ($ext === 'webp') return 'image/webp';
|
||||
return 'image/jpeg';
|
||||
}
|
||||
|
||||
function bratonien_tools_webdav_custom_derivative_params($key)
|
||||
@@ -177,13 +191,37 @@ function bratonien_tools_webdav_derivative_variants()
|
||||
return $variants;
|
||||
}
|
||||
|
||||
function bratonien_tools_webdav_generate_derivative($params, $src_image)
|
||||
function bratonien_tools_webdav_generate_derivative($params, $src_image, &$detail=null)
|
||||
{
|
||||
if (!is_object($src_image) || empty($src_image->id)) return false;
|
||||
global $conf;
|
||||
|
||||
$detail = '';
|
||||
if (!is_object($src_image) || empty($src_image->id))
|
||||
{
|
||||
$detail = 'SrcImage fehlt.';
|
||||
return false;
|
||||
}
|
||||
|
||||
$info = bratonien_tools_webdav_image_source_info((int)$src_image->id);
|
||||
if (!$info) return false;
|
||||
if (!$info)
|
||||
{
|
||||
$detail = 'WebDAV-Quellzuordnung fehlt.';
|
||||
return false;
|
||||
}
|
||||
|
||||
$preview = bratonien_tools_webdav_preview_path($info);
|
||||
if (!$preview) return false;
|
||||
if (!$preview)
|
||||
{
|
||||
$detail = 'Vorbereitetes WebDAV-Preview fehlt.';
|
||||
return false;
|
||||
}
|
||||
|
||||
$preview_ext = strtolower(pathinfo($preview, PATHINFO_EXTENSION));
|
||||
if (!in_array($preview_ext, array('jpg', 'jpeg', 'png', 'gif'), true))
|
||||
{
|
||||
$detail = 'Preview-Format '.$preview_ext.' ist für die Piwigo-Bildbibliothek nicht sicher nutzbar.';
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!class_exists('DerivativeImage')) require_once(PHPWG_ROOT_PATH.'include/derivative.inc.php');
|
||||
if (!class_exists('pwg_image')) require_once(PHPWG_ROOT_PATH.'admin/include/image.class.php');
|
||||
@@ -191,50 +229,177 @@ function bratonien_tools_webdav_generate_derivative($params, $src_image)
|
||||
$derivative = new DerivativeImage($params, $src_image);
|
||||
if ($derivative->same_as_source())
|
||||
{
|
||||
$detail = 'Identisch mit Quelle; kein eigenes Derivat erforderlich.';
|
||||
return true;
|
||||
}
|
||||
|
||||
$target = $derivative->get_path();
|
||||
if ($target === '' || strpos($target, PHPWG_ROOT_PATH.PWG_DERIVATIVE_DIR) !== 0) return false;
|
||||
$derivative_root = PHPWG_ROOT_PATH.PWG_DERIVATIVE_DIR;
|
||||
if ($target === '' || strpos($target, $derivative_root) !== 0)
|
||||
{
|
||||
$detail = 'Ungültiger Derivat-Zielpfad: '.$target;
|
||||
return false;
|
||||
}
|
||||
|
||||
$preview_mtime = @filemtime($preview) ?: 0;
|
||||
if (is_file($target) && is_readable($target) && (@filemtime($target) ?: 0) >= $preview_mtime)
|
||||
if (is_file($target) && is_readable($target) && (@filemtime($target) ?: 0) >= max($preview_mtime, (int)($params->last_mod_time ?? 0)))
|
||||
{
|
||||
$detail = 'Bereits vorhanden.';
|
||||
return true;
|
||||
}
|
||||
|
||||
$directory = dirname($target);
|
||||
if (!is_dir($directory) && !mkdir($directory, 0755, true) && !is_dir($directory)) return false;
|
||||
$dir_ok = function_exists('mkgetdir') ? mkgetdir($directory) : (is_dir($directory) || @mkdir($directory, 0755, true));
|
||||
if (!$dir_ok || !is_dir($directory))
|
||||
{
|
||||
$detail = 'Derivat-Verzeichnis konnte nicht angelegt werden: '.$directory;
|
||||
return false;
|
||||
}
|
||||
|
||||
$image = new pwg_image($preview);
|
||||
$image = null;
|
||||
try
|
||||
{
|
||||
$original_size = array($image->get_width(), $image->get_height());
|
||||
$image = new pwg_image($preview);
|
||||
$original_size = array((int)$image->get_width(), (int)$image->get_height());
|
||||
if ($original_size[0] < 1 || $original_size[1] < 1)
|
||||
{
|
||||
$detail = 'Preview-Abmessungen sind ungültig.';
|
||||
return false;
|
||||
}
|
||||
|
||||
$crop_rect = null;
|
||||
$scaled_size = null;
|
||||
$params->sizing->compute($original_size, $info['coi'] ?? null, $crop_rect, $scaled_size);
|
||||
|
||||
if ($crop_rect)
|
||||
{
|
||||
$image->crop($crop_rect->width(), $crop_rect->height(), $crop_rect->l, $crop_rect->t);
|
||||
if (!$image->crop($crop_rect->width(), $crop_rect->height(), $crop_rect->l, $crop_rect->t))
|
||||
{
|
||||
$detail = 'Crop fehlgeschlagen.';
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
$final_size = $original_size;
|
||||
if ($crop_rect)
|
||||
{
|
||||
$final_size = array($crop_rect->width(), $crop_rect->height());
|
||||
}
|
||||
if ($scaled_size)
|
||||
{
|
||||
$image->resize($scaled_size[0], $scaled_size[1]);
|
||||
if (!$image->resize($scaled_size[0], $scaled_size[1]))
|
||||
{
|
||||
$detail = 'Resize fehlgeschlagen.';
|
||||
return false;
|
||||
}
|
||||
$final_size = array((int)$scaled_size[0], (int)$scaled_size[1]);
|
||||
}
|
||||
if (!empty($params->sharpen))
|
||||
|
||||
if (!empty($params->sharpen) && !$image->sharpen($params->sharpen))
|
||||
{
|
||||
$image->sharpen($params->sharpen);
|
||||
$detail = 'Sharpen fehlgeschlagen.';
|
||||
return false;
|
||||
}
|
||||
$image->write($target);
|
||||
|
||||
if ($params->will_watermark($final_size))
|
||||
{
|
||||
$wm = ImageStdParams::get_watermark();
|
||||
if (!empty($wm->file))
|
||||
{
|
||||
$wm_path = PHPWG_ROOT_PATH.$wm->file;
|
||||
if (!is_file($wm_path) || !is_readable($wm_path))
|
||||
{
|
||||
$detail = 'Wasserzeichen-Datei fehlt: '.$wm_path;
|
||||
return false;
|
||||
}
|
||||
|
||||
$wm_image = new pwg_image($wm_path);
|
||||
try
|
||||
{
|
||||
$wm_size = array((int)$wm_image->get_width(), (int)$wm_image->get_height());
|
||||
if ($final_size[0] < $wm_size[0] || $final_size[1] < $wm_size[1])
|
||||
{
|
||||
$wm_scaling = SizingParams::classic($final_size[0], $final_size[1]);
|
||||
$tmp = null;
|
||||
$wm_scaled = null;
|
||||
$wm_scaling->compute($wm_size, null, $tmp, $wm_scaled);
|
||||
if ($wm_scaled)
|
||||
{
|
||||
$wm_image->resize($wm_scaled[0], $wm_scaled[1]);
|
||||
$wm_size = array((int)$wm_scaled[0], (int)$wm_scaled[1]);
|
||||
}
|
||||
}
|
||||
|
||||
$x = (int)round(($wm->xpos / 100) * ($final_size[0] - $wm_size[0]));
|
||||
$y = (int)round(($wm->ypos / 100) * ($final_size[1] - $wm_size[1]));
|
||||
$image->compose($wm_image, $x, $y, $wm->opacity);
|
||||
|
||||
if ($wm->xrepeat || $wm->yrepeat)
|
||||
{
|
||||
$xpad = $wm_size[0] + max(30, (int)round($wm_size[0] / 4));
|
||||
$ypad = $wm_size[1] + max(30, (int)round($wm_size[1] / 4));
|
||||
for ($i = -$wm->xrepeat; $i <= $wm->xrepeat; $i++)
|
||||
{
|
||||
for ($j = -$wm->yrepeat; $j <= $wm->yrepeat; $j++)
|
||||
{
|
||||
if (!$i && !$j) continue;
|
||||
$x2 = $x + $i * $xpad;
|
||||
$y2 = $y + $j * $ypad;
|
||||
if ($x2 >= 0 && $x2 + $wm_size[0] < $final_size[0] && $y2 >= 0 && $y2 + $wm_size[1] < $final_size[1])
|
||||
{
|
||||
$image->compose($wm_image, $x2, $y2, $wm->opacity);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
$wm_image->destroy();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($conf['derivatives_strip_metadata_threshold']) && $final_size[0] * $final_size[1] < (int)$conf['derivatives_strip_metadata_threshold'])
|
||||
{
|
||||
$image->strip();
|
||||
}
|
||||
|
||||
$quality = (int)ImageStdParams::$quality;
|
||||
if (isset($params->type) && in_array($params->type, array(IMG_3XLARGE, IMG_4XLARGE), true))
|
||||
{
|
||||
$quality = min($quality, 75);
|
||||
}
|
||||
$image->set_compression_quality($quality);
|
||||
|
||||
$written = $image->write($target);
|
||||
if ($written === false)
|
||||
{
|
||||
$detail = 'Bildbibliothek konnte das Derivat nicht schreiben.';
|
||||
return false;
|
||||
}
|
||||
}
|
||||
catch (Throwable $e)
|
||||
{
|
||||
$detail = get_class($e).': '.$e->getMessage();
|
||||
return false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
$image->destroy();
|
||||
if (is_object($image)) $image->destroy();
|
||||
}
|
||||
|
||||
@chmod($target, 0644);
|
||||
clearstatcache(true, $target);
|
||||
return is_file($target) && is_readable($target);
|
||||
$size = @getimagesize($target);
|
||||
if (!is_file($target) || !is_readable($target) || !is_array($size) || empty($size[0]) || empty($size[1]))
|
||||
{
|
||||
$detail = 'Derivatdatei wurde nicht gültig erzeugt: '.$target;
|
||||
return false;
|
||||
}
|
||||
|
||||
$detail = 'Erzeugt: '.$target.' ('.$size[0].'x'.$size[1].').';
|
||||
return true;
|
||||
}
|
||||
|
||||
function bratonien_tools_filter_webdav_src_url($url, $src_image)
|
||||
@@ -252,16 +417,18 @@ function bratonien_tools_filter_webdav_derivative_url($url, $params, $src_image,
|
||||
|
||||
try
|
||||
{
|
||||
if (bratonien_tools_webdav_generate_derivative($params, $src_image))
|
||||
$derivative = new DerivativeImage($params, $src_image);
|
||||
if (!$derivative->same_as_source())
|
||||
{
|
||||
return $url;
|
||||
$path = $derivative->get_path();
|
||||
if ($path !== '' && is_file($path) && is_readable($path)) return $url;
|
||||
}
|
||||
}
|
||||
catch (Throwable $e)
|
||||
{
|
||||
error_log('Bratonien WebDAV derivative #'.(int)$src_image->id.': '.$e->getMessage());
|
||||
error_log('Bratonien WebDAV derivative lookup #'.(int)$src_image->id.': '.$e->getMessage());
|
||||
}
|
||||
|
||||
$webdav_url = bratonien_tools_webdav_image_url((int)$src_image->id, true);
|
||||
return $webdav_url ?: $url;
|
||||
$preview_url = bratonien_tools_webdav_image_url((int)$src_image->id, true);
|
||||
return $preview_url ?: $url;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,94 @@
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
function initNcRouteStatus() {
|
||||
var section = document.getElementById('nc-connector');
|
||||
if (!section) return;
|
||||
|
||||
var statusCard = section.querySelector('.bratonien-grid .bratonien-card');
|
||||
if (!statusCard) return;
|
||||
|
||||
var grid = statusCard.querySelector('.bratonien-form-grid');
|
||||
if (!grid) return;
|
||||
|
||||
var routeLabel = document.createElement('span');
|
||||
routeLabel.className = 'bratonien-label';
|
||||
routeLabel.textContent = 'Aktiver Datenweg';
|
||||
|
||||
var routeValue = document.createElement('strong');
|
||||
routeValue.setAttribute('data-nc-route-status', '');
|
||||
routeValue.textContent = 'Noch kein Lauf erfasst';
|
||||
|
||||
var routeTimeLabel = document.createElement('span');
|
||||
routeTimeLabel.className = 'bratonien-label';
|
||||
routeTimeLabel.textContent = 'Datenweg zuletzt';
|
||||
|
||||
var routeTimeValue = document.createElement('strong');
|
||||
routeTimeValue.setAttribute('data-nc-route-time', '');
|
||||
routeTimeValue.textContent = 'Nicht verfügbar';
|
||||
|
||||
grid.appendChild(routeLabel);
|
||||
grid.appendChild(routeValue);
|
||||
grid.appendChild(routeTimeLabel);
|
||||
grid.appendChild(routeTimeValue);
|
||||
|
||||
var detail = document.createElement('p');
|
||||
detail.className = 'bratonien-base-note';
|
||||
detail.setAttribute('data-nc-route-detail', '');
|
||||
detail.textContent = 'Der Datenweg wird nach dem nächsten Connector-Lauf angezeigt.';
|
||||
statusCard.appendChild(detail);
|
||||
|
||||
var basePath = window.location.pathname.replace(/admin\.php.*$/, '');
|
||||
var statusUrl = basePath + '_data/bratonien-tools/nc-connector-status/route-status.json';
|
||||
|
||||
function formatTime(timestamp) {
|
||||
if (!timestamp) return 'Nicht verfügbar';
|
||||
var date = new Date(Number(timestamp) * 1000);
|
||||
if (Number.isNaN(date.getTime())) return 'Nicht verfügbar';
|
||||
return date.toLocaleString('de-DE');
|
||||
}
|
||||
|
||||
function render(data) {
|
||||
var label = data && data.label ? String(data.label) : 'Unbekannt';
|
||||
var route = data && data.route ? String(data.route) : '';
|
||||
routeValue.textContent = label;
|
||||
routeTimeValue.textContent = formatTime(data && data.timestamp);
|
||||
|
||||
if (route === 'webdav') {
|
||||
routeValue.textContent = 'WEBDAV PRIMÄR';
|
||||
detail.textContent = 'Portierung läuft über WebDAV. Legacy wurde in diesem Lauf nicht benutzt.';
|
||||
} else if (route === 'legacy_fallback') {
|
||||
routeValue.textContent = 'LEGACY-FALLBACK AKTIV';
|
||||
detail.textContent = 'WebDAV war nicht erfolgreich. Dieser Lauf wurde über die alte Struktur abgefangen.';
|
||||
} else if (route === 'failed') {
|
||||
routeValue.textContent = 'FEHLER - KEIN ERFOLGREICHER DATENWEG';
|
||||
detail.textContent = data && data.detail ? String(data.detail) : 'WebDAV und Fallback sind fehlgeschlagen.';
|
||||
} else {
|
||||
detail.textContent = data && data.detail ? String(data.detail) : 'Unbekannter Datenweg.';
|
||||
}
|
||||
}
|
||||
|
||||
function refresh() {
|
||||
fetch(statusUrl + '?t=' + Date.now(), {
|
||||
cache: 'no-store',
|
||||
credentials: 'same-origin'
|
||||
})
|
||||
.then(function (response) {
|
||||
if (!response.ok) throw new Error('status unavailable');
|
||||
return response.json();
|
||||
})
|
||||
.then(render)
|
||||
.catch(function () {
|
||||
routeValue.textContent = 'Noch kein Lauf erfasst';
|
||||
routeTimeValue.textContent = 'Nicht verfügbar';
|
||||
detail.textContent = 'Nach dem nächsten Connector-Lauf wird hier WebDAV oder Legacy-Fallback angezeigt.';
|
||||
});
|
||||
}
|
||||
|
||||
refresh();
|
||||
window.setInterval(refresh, 10000);
|
||||
}
|
||||
|
||||
function initBratonienTabs() {
|
||||
var admin = document.querySelector('.bratonien-admin');
|
||||
if (!admin) return;
|
||||
@@ -113,9 +201,14 @@
|
||||
activate(initial, false);
|
||||
}
|
||||
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', initBratonienTabs);
|
||||
} else {
|
||||
function init() {
|
||||
initBratonienTabs();
|
||||
initNcRouteStatus();
|
||||
}
|
||||
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', init);
|
||||
} else {
|
||||
init();
|
||||
}
|
||||
})();
|
||||
|
||||
324
js/nc_connector_edit_v2.js
Normal file
324
js/nc_connector_edit_v2.js
Normal file
@@ -0,0 +1,324 @@
|
||||
(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 clearValidation(form) {
|
||||
[].slice.call(form.querySelectorAll('[aria-invalid="true"]')).forEach(function (field) {
|
||||
field.removeAttribute('aria-invalid');
|
||||
field.style.borderColor = '';
|
||||
field.style.boxShadow = '';
|
||||
});
|
||||
[].slice.call(form.querySelectorAll('[data-edit-v2-field-error]')).forEach(function (node) { node.remove(); });
|
||||
var box = form.querySelector('[data-edit-v2-error-summary]');
|
||||
if (box) box.remove();
|
||||
}
|
||||
|
||||
function fieldNodes(form, fieldName) {
|
||||
return [].slice.call(form.querySelectorAll('[name="'+fieldName.replace(/"/g, '\\"')+'"]'));
|
||||
}
|
||||
|
||||
function showValidation(form, data) {
|
||||
clearValidation(form);
|
||||
var message = (data && data.message) ? data.message : 'Die Verbindung konnte nicht gespeichert werden.';
|
||||
var summary = document.createElement('div');
|
||||
summary.dataset.editV2ErrorSummary = '1';
|
||||
summary.className = 'bratonien-main-cache__warning';
|
||||
summary.style.margin = '0 0 1rem';
|
||||
summary.style.padding = '.75rem';
|
||||
summary.style.border = '1px solid currentColor';
|
||||
summary.innerHTML = '<strong>Speichern fehlgeschlagen:</strong> '+escapeHtml(message);
|
||||
form.insertBefore(summary, form.firstChild);
|
||||
|
||||
var first = null;
|
||||
var fields = data && Array.isArray(data.fields) ? data.fields : [];
|
||||
fields.forEach(function (fieldName) {
|
||||
fieldNodes(form, fieldName).forEach(function (field) {
|
||||
field.setAttribute('aria-invalid', 'true');
|
||||
field.style.borderColor = '#d65a5a';
|
||||
field.style.boxShadow = '0 0 0 1px #d65a5a';
|
||||
if (!first) first = field;
|
||||
var note = document.createElement('span');
|
||||
note.dataset.editV2FieldError = '1';
|
||||
note.className = 'bratonien-main-cache__warning';
|
||||
note.style.display = 'block';
|
||||
note.style.marginTop = '.25rem';
|
||||
note.textContent = message;
|
||||
field.insertAdjacentElement('afterend', note);
|
||||
});
|
||||
});
|
||||
|
||||
if (first) {
|
||||
first.scrollIntoView({block:'center', behavior:'smooth'});
|
||||
window.setTimeout(function () { first.focus(); }, 150);
|
||||
} else {
|
||||
summary.scrollIntoView({block:'center', behavior:'smooth'});
|
||||
}
|
||||
}
|
||||
|
||||
function submitEditor(form, editDialog) {
|
||||
clearValidation(form);
|
||||
if (!form.reportValidity()) return;
|
||||
|
||||
var submit = form.querySelector('button[type="submit"]');
|
||||
if (submit) submit.disabled = true;
|
||||
|
||||
var body = new FormData(form);
|
||||
fetch('plugins/bratonien_tools/nc-connector-edit-save.php', {
|
||||
method:'POST',
|
||||
credentials:'same-origin',
|
||||
cache:'no-store',
|
||||
headers:{'Accept':'application/json'},
|
||||
body:body
|
||||
}).then(function (response) {
|
||||
return response.json().then(function (data) {
|
||||
if (!response.ok || !data.ok) {
|
||||
showValidation(form, data);
|
||||
return;
|
||||
}
|
||||
editDialog.close();
|
||||
window.location.reload();
|
||||
});
|
||||
}).catch(function (error) {
|
||||
showValidation(form, {message:error.message || String(error), fields:[]});
|
||||
}).finally(function () {
|
||||
if (submit) submit.disabled = false;
|
||||
});
|
||||
}
|
||||
|
||||
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">Ä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();
|
||||
});
|
||||
form.addEventListener('submit', function (event) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
submitEditor(form, editDialog);
|
||||
});
|
||||
}).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, connectionData) {
|
||||
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"]');
|
||||
var editStart = form.querySelector('button[value="nc_connector_edit_start"]');
|
||||
if (migrate || editStart) 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);
|
||||
|
||||
var dataPromise = connectionData ? Promise.resolve(connectionData) : loadConnection(id);
|
||||
dataPromise.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));
|
||||
});
|
||||
}
|
||||
|
||||
function rebuildRemoteActions(deleteForm, id) {
|
||||
var actions = deleteForm.parentElement;
|
||||
if (!actions) return;
|
||||
[].slice.call(actions.querySelectorAll('form')).forEach(function (form) {
|
||||
var oldEdit = form.querySelector('button[value="nc_connector_edit_start"]');
|
||||
var oldMigrate = form.querySelector('button[value="nc_connector_migrate_start"]');
|
||||
if (oldEdit || oldMigrate) 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();
|
||||
});
|
||||
actions.insertBefore(postForm('Bearbeiten', 'nc_connector_edit_start', id, 'edit'), deleteForm);
|
||||
}
|
||||
|
||||
[].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');
|
||||
if (!deleteForm) return;
|
||||
var idInput = deleteForm.querySelector('input[name="connection_id"]');
|
||||
if (!idInput) return;
|
||||
var id = idInput.value;
|
||||
|
||||
loadConnection(id).then(function (data) {
|
||||
if (data.adapter === 'local') rebuildLocalActions(deleteForm, id, data);
|
||||
else rebuildRemoteActions(deleteForm, id);
|
||||
}).catch(function (error) {
|
||||
var actions = deleteForm.parentElement;
|
||||
if (!actions) return;
|
||||
var info = document.createElement('span');
|
||||
info.className = 'bratonien-main-cache__warning';
|
||||
info.textContent = 'Verbindungstyp konnte nicht geladen werden: '+(error.message || String(error));
|
||||
actions.insertBefore(info, deleteForm);
|
||||
});
|
||||
});
|
||||
});
|
||||
})();
|
||||
217
js/nc_connector_source_ui.js
Normal file
217
js/nc_connector_source_ui.js
Normal file
@@ -0,0 +1,217 @@
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
function escapeHtml(value) {
|
||||
return String(value == null ? '' : value).replace(/[&<>"']/g, function (c) {
|
||||
return {'&':'&','<':'<','>':'>','"':'"',"'":'''}[c];
|
||||
});
|
||||
}
|
||||
|
||||
function fieldNodes(form, fieldName) {
|
||||
return [].slice.call(form.querySelectorAll('[name="'+fieldName.replace(/"/g, '\\"')+'"]'));
|
||||
}
|
||||
|
||||
function clearPickerErrors(form) {
|
||||
[].slice.call(form.querySelectorAll('[data-source-picker-error]')).forEach(function (node) { node.remove(); });
|
||||
[].slice.call(form.querySelectorAll('[data-source-picker-invalid="1"]')).forEach(function (field) {
|
||||
field.removeAttribute('data-source-picker-invalid');
|
||||
if (field.getAttribute('aria-invalid') === 'true') field.removeAttribute('aria-invalid');
|
||||
field.style.borderColor = '';
|
||||
field.style.boxShadow = '';
|
||||
});
|
||||
}
|
||||
|
||||
function showPickerError(form, data) {
|
||||
clearPickerErrors(form);
|
||||
var message = data && data.message ? data.message : 'Die Nextcloud-Ordnerauswahl konnte nicht gestartet werden.';
|
||||
var fields = data && Array.isArray(data.fields) ? data.fields : [];
|
||||
|
||||
var summary = document.createElement('div');
|
||||
summary.dataset.sourcePickerError = '1';
|
||||
summary.className = 'bratonien-main-cache__warning';
|
||||
summary.style.margin = '0 0 1rem';
|
||||
summary.style.padding = '.75rem';
|
||||
summary.style.border = '1px solid currentColor';
|
||||
summary.innerHTML = '<strong>Ordnerauswahl nicht möglich:</strong> '+escapeHtml(message);
|
||||
form.insertBefore(summary, form.firstChild);
|
||||
|
||||
var first = null;
|
||||
fields.forEach(function (fieldName) {
|
||||
fieldNodes(form, fieldName).forEach(function (field) {
|
||||
field.dataset.sourcePickerInvalid = '1';
|
||||
field.setAttribute('aria-invalid', 'true');
|
||||
field.style.borderColor = '#d65a5a';
|
||||
field.style.boxShadow = '0 0 0 1px #d65a5a';
|
||||
if (!first) first = field;
|
||||
});
|
||||
});
|
||||
|
||||
if (first) {
|
||||
first.scrollIntoView({block:'center', behavior:'smooth'});
|
||||
window.setTimeout(function () { first.focus(); }, 150);
|
||||
} else {
|
||||
summary.scrollIntoView({block:'center', behavior:'smooth'});
|
||||
}
|
||||
}
|
||||
|
||||
function jsonResponse(response) {
|
||||
return response.json().then(function (data) {
|
||||
if (!response.ok || !data.ok) throw data;
|
||||
return data;
|
||||
});
|
||||
}
|
||||
|
||||
function startSourcePicker(form, button) {
|
||||
clearPickerErrors(form);
|
||||
if (!form.reportValidity()) return;
|
||||
|
||||
button.disabled = true;
|
||||
var originalText = button.textContent;
|
||||
button.textContent = 'Verbindung prüfen …';
|
||||
|
||||
var saveBody = new FormData(form);
|
||||
fetch('plugins/bratonien_tools/nc-connector-edit-save.php', {
|
||||
method:'POST',
|
||||
credentials:'same-origin',
|
||||
cache:'no-store',
|
||||
headers:{'Accept':'application/json'},
|
||||
body:saveBody
|
||||
})
|
||||
.then(jsonResponse)
|
||||
.then(function () {
|
||||
button.textContent = 'Nextcloud-Ordner laden …';
|
||||
var pickerBody = new FormData();
|
||||
var token = form.querySelector('input[name="pwg_token"]');
|
||||
var id = form.querySelector('input[name="connection_id"]');
|
||||
pickerBody.append('pwg_token', token ? token.value : '');
|
||||
pickerBody.append('connection_id', id ? id.value : '');
|
||||
return fetch('plugins/bratonien_tools/nc-connector-source-picker-start.php', {
|
||||
method:'POST',
|
||||
credentials:'same-origin',
|
||||
cache:'no-store',
|
||||
headers:{'Accept':'application/json'},
|
||||
body:pickerBody
|
||||
}).then(jsonResponse);
|
||||
})
|
||||
.then(function () {
|
||||
try {
|
||||
sessionStorage.setItem('bratonienNcWizardMode', 'migrate');
|
||||
sessionStorage.setItem('bratonienNcWizardOpen', '1');
|
||||
} catch (e) {}
|
||||
window.location.reload();
|
||||
})
|
||||
.catch(function (error) {
|
||||
showPickerError(form, error && typeof error === 'object' ? error : {message:String(error), fields:[]});
|
||||
button.disabled = false;
|
||||
button.textContent = originalText;
|
||||
});
|
||||
}
|
||||
|
||||
function enhanceMigrationButtons(root) {
|
||||
[].slice.call(root.querySelectorAll('button[value="nc_connector_migrate_start"]')).forEach(function (button) {
|
||||
button.textContent = 'Nextcloud-Ordner auswählen & migrieren';
|
||||
button.title = 'Die WebDAV-Quelle wird im Nextcloud-Ordnerbrowser ausgewählt. Der bestehende SMB-/Legacy-Speicher wird nicht als WebDAV-Quelle übernommen.';
|
||||
});
|
||||
}
|
||||
|
||||
function enhanceEditor(root) {
|
||||
var form = root.querySelector('[data-edit-v2-form]');
|
||||
if (!form || form.dataset.sourceUiEnhanced === '1') return;
|
||||
form.dataset.sourceUiEnhanced = '1';
|
||||
|
||||
var headings = [].slice.call(form.querySelectorAll('h5'));
|
||||
var webdavHeading = headings.find(function (node) {
|
||||
return (node.textContent || '').trim() === 'Nextcloud / WebDAV';
|
||||
});
|
||||
var legacyHeading = headings.find(function (node) {
|
||||
return (node.textContent || '').trim() === 'Bestehender Legacy-Weg';
|
||||
});
|
||||
var storageHeading = headings.find(function (node) {
|
||||
return (node.textContent || '').trim() === 'Speicherorte';
|
||||
});
|
||||
var storageList = form.querySelector('[data-storage-list]');
|
||||
var addStorage = form.querySelector('[data-add-storage]');
|
||||
|
||||
if (webdavHeading && !form.querySelector('[data-webdav-source-picker]')) {
|
||||
var webdavGrid = webdavHeading.nextElementSibling;
|
||||
while (webdavGrid && !webdavGrid.classList.contains('bratonien-form-grid')) webdavGrid = webdavGrid.nextElementSibling;
|
||||
if (webdavGrid) {
|
||||
var picker = document.createElement('div');
|
||||
picker.dataset.webdavSourcePicker = '1';
|
||||
picker.style.margin = '.8rem 0 1rem';
|
||||
picker.innerHTML = '<p class="bratonien-base-note" style="margin:.25rem 0 .5rem"><strong>WebDAV-Quelle:</strong> Du musst keinen Pfad kennen. Die Ordner des oben eingetragenen Nextcloud-Benutzers werden automatisch geladen und können anschließend ausgewählt werden.</p>';
|
||||
var button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.className = 'buttonLike';
|
||||
button.textContent = 'Nextcloud-Ordner automatisch auswählen';
|
||||
button.addEventListener('click', function () { startSourcePicker(form, button); });
|
||||
picker.appendChild(button);
|
||||
webdavGrid.insertAdjacentElement('afterend', picker);
|
||||
}
|
||||
}
|
||||
|
||||
if (legacyHeading && !form.querySelector('[data-webdav-source-note]')) {
|
||||
var note = document.createElement('p');
|
||||
note.dataset.webdavSourceNote = '1';
|
||||
note.className = 'bratonien-main-cache__warning';
|
||||
note.innerHTML = '<strong>Wichtig:</strong> Der folgende SMB-/lokale Speicher gehört ausschließlich zum bisherigen Legacy-Fallback. Er wird <strong>nicht</strong> als WebDAV-Quelle übernommen.';
|
||||
legacyHeading.insertAdjacentElement('beforebegin', note);
|
||||
}
|
||||
|
||||
if (storageHeading && storageList && addStorage) {
|
||||
storageHeading.textContent = 'Legacy-Speicher (nur Fallback)';
|
||||
|
||||
var details = document.createElement('details');
|
||||
details.dataset.legacyStorageTechnical = '1';
|
||||
details.style.marginTop = '.75rem';
|
||||
var summary = document.createElement('summary');
|
||||
summary.textContent = 'Technische Legacy-Speicherzuordnung bearbeiten';
|
||||
details.appendChild(summary);
|
||||
|
||||
var info = document.createElement('p');
|
||||
info.className = 'bratonien-base-note';
|
||||
info.textContent = 'Diese Felder betreffen nur den alten Fallback-Weg. Für WebDAV werden keine SMB-Adressen oder lokalen Mount-Pfade eingegeben.';
|
||||
details.appendChild(info);
|
||||
|
||||
storageHeading.insertAdjacentElement('beforebegin', details);
|
||||
details.appendChild(storageHeading);
|
||||
details.appendChild(storageList);
|
||||
details.appendChild(addStorage);
|
||||
|
||||
addStorage.textContent = 'Legacy-Speicher manuell hinzufügen';
|
||||
addStorage.title = 'Nur für den alten Legacy-Fallback. WebDAV-Ordner werden im Nextcloud-Ordnerbrowser ausgewählt.';
|
||||
}
|
||||
}
|
||||
|
||||
function enhance(root) {
|
||||
if (!root || root.nodeType !== 1) return;
|
||||
enhanceMigrationButtons(root);
|
||||
if (root.matches && root.matches('#bratonien-nc-connection-edit-v2')) enhanceEditor(root);
|
||||
var dialog = root.querySelector ? root.querySelector('#bratonien-nc-connection-edit-v2') : null;
|
||||
if (dialog) enhanceEditor(dialog);
|
||||
}
|
||||
|
||||
function start() {
|
||||
var section = document.getElementById('nc-connector');
|
||||
if (!section) return;
|
||||
|
||||
enhance(section);
|
||||
enhanceMigrationButtons(document);
|
||||
|
||||
var observer = new MutationObserver(function (mutations) {
|
||||
mutations.forEach(function (mutation) {
|
||||
[].slice.call(mutation.addedNodes || []).forEach(function (node) {
|
||||
if (node && node.nodeType === 1) enhance(node);
|
||||
});
|
||||
});
|
||||
var dialog = document.getElementById('bratonien-nc-connection-edit-v2');
|
||||
if (dialog) enhanceEditor(dialog);
|
||||
enhanceMigrationButtons(document);
|
||||
});
|
||||
|
||||
observer.observe(document.body, {childList:true, subtree:true});
|
||||
}
|
||||
|
||||
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', start);
|
||||
else start();
|
||||
})();
|
||||
@@ -1,7 +1,7 @@
|
||||
<?php
|
||||
/*
|
||||
Plugin Name: Bratonien Tools
|
||||
Version: 0.9.5.21
|
||||
Version: 0.9.6.16
|
||||
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);
|
||||
312
nc-connector-edit-save.php
Normal file
312
nc-connector-edit-save.php
Normal file
@@ -0,0 +1,312 @@
|
||||
<?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');
|
||||
|
||||
function bratonien_tools_nc_edit_json($status, array $payload)
|
||||
{
|
||||
http_response_code((int)$status);
|
||||
echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
||||
exit;
|
||||
}
|
||||
|
||||
function bratonien_tools_nc_edit_fail($message, array $fields = array(), $stage = '', $detail = '')
|
||||
{
|
||||
$visible = trim((string)$message);
|
||||
if ($stage !== '') $visible = 'Bereich: '.$stage.' — '.$visible;
|
||||
if ($detail !== '') $visible .= ' Technische Ursache: '.$detail;
|
||||
|
||||
bratonien_tools_nc_edit_json(422, array(
|
||||
'ok'=>false,
|
||||
'message'=>$visible,
|
||||
'stage'=>(string)$stage,
|
||||
'detail'=>(string)$detail,
|
||||
'fields'=>array_values(array_unique($fields)),
|
||||
));
|
||||
}
|
||||
|
||||
function bratonien_tools_nc_edit_probe($url, $username = '', $password = '', array $headers = array())
|
||||
{
|
||||
if (!function_exists('curl_init'))
|
||||
{
|
||||
return array('ok'=>false, 'http'=>0, 'errno'=>-1, 'error'=>'cURL ist in PHP nicht verfügbar.', 'body'=>'');
|
||||
}
|
||||
|
||||
$ch = curl_init($url);
|
||||
$options = array(
|
||||
CURLOPT_RETURNTRANSFER=>true,
|
||||
CURLOPT_FOLLOWLOCATION=>true,
|
||||
CURLOPT_MAXREDIRS=>3,
|
||||
CURLOPT_CONNECTTIMEOUT=>8,
|
||||
CURLOPT_TIMEOUT=>15,
|
||||
CURLOPT_HTTPHEADER=>array_merge(array('Accept: application/json'), $headers),
|
||||
CURLOPT_USERAGENT=>'Bratonien-Tools-NC-Editor/'.(function_exists('bratonien_tools_current_version') ? bratonien_tools_current_version() : 'dev'),
|
||||
);
|
||||
if ($username !== '')
|
||||
{
|
||||
$options[CURLOPT_HTTPAUTH] = CURLAUTH_BASIC;
|
||||
$options[CURLOPT_USERPWD] = $username.':'.$password;
|
||||
}
|
||||
curl_setopt_array($ch, $options);
|
||||
$body = curl_exec($ch);
|
||||
$errno = curl_errno($ch);
|
||||
$error = curl_error($ch);
|
||||
$http = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
curl_close($ch);
|
||||
|
||||
return array(
|
||||
'ok'=>$body !== false && $errno === 0,
|
||||
'http'=>$http,
|
||||
'errno'=>$errno,
|
||||
'error'=>$error,
|
||||
'body'=>$body === false ? '' : (string)$body,
|
||||
);
|
||||
}
|
||||
|
||||
if (!defined('BRATONIEN_TOOLS_PATH'))
|
||||
{
|
||||
bratonien_tools_nc_edit_json(404, array('ok'=>false, 'message'=>'Bratonien Tools ist nicht aktiv.', 'fields'=>array()));
|
||||
}
|
||||
if (!function_exists('is_admin') || !is_admin())
|
||||
{
|
||||
bratonien_tools_nc_edit_json(403, array('ok'=>false, 'message'=>'Administratorrechte erforderlich.', 'fields'=>array()));
|
||||
}
|
||||
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST')
|
||||
{
|
||||
bratonien_tools_nc_edit_json(405, array('ok'=>false, 'message'=>'Nur POST ist erlaubt.', 'fields'=>array()));
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
check_pwg_token();
|
||||
require_once(BRATONIEN_TOOLS_PATH.'include/tool_registry.inc.php');
|
||||
|
||||
$id = (int)($_POST['connection_id'] ?? 0);
|
||||
$connection = bratonien_tools_nc_connector_connection($id, true);
|
||||
if (!$connection)
|
||||
{
|
||||
bratonien_tools_nc_edit_fail('Die zu bearbeitende Verbindung wurde nicht gefunden.', array(), 'Verbindung');
|
||||
}
|
||||
|
||||
$config = isset($connection['config']) && is_array($connection['config']) ? $connection['config'] : array();
|
||||
$credentials = bratonien_tools_nc_connector_scoped_secret($connection);
|
||||
|
||||
$nextcloud_input = trim((string)($_POST['nc_nextcloud_url'] ?? ($config['nextcloud_url'] ?? '')));
|
||||
$nextcloud_user = trim((string)($_POST['nc_nextcloud_user'] ?? ($credentials['nextcloud_user'] ?? '')));
|
||||
$submitted_nc_password = (string)($_POST['nc_nextcloud_password'] ?? '');
|
||||
$nextcloud_password = $submitted_nc_password !== '' ? $submitted_nc_password : (string)($credentials['nextcloud_password'] ?? '');
|
||||
|
||||
$has_any_nextcloud = $nextcloud_input !== '' || $nextcloud_user !== '' || $nextcloud_password !== '';
|
||||
if ($has_any_nextcloud)
|
||||
{
|
||||
$missing = array();
|
||||
if ($nextcloud_input === '') $missing[] = 'nc_nextcloud_url';
|
||||
if ($nextcloud_user === '') $missing[] = 'nc_nextcloud_user';
|
||||
if ($nextcloud_password === '') $missing[] = 'nc_nextcloud_password';
|
||||
if ($missing)
|
||||
{
|
||||
bratonien_tools_nc_edit_fail(
|
||||
'Die WebDAV-Daten sind unvollständig. Adresse, Benutzer und Passwort werden gemeinsam benötigt.',
|
||||
$missing,
|
||||
'Nextcloud / WebDAV'
|
||||
);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
$candidate_urls = bratonien_tools_nc_wizard_candidate_urls($nextcloud_input);
|
||||
}
|
||||
catch (Throwable $e)
|
||||
{
|
||||
bratonien_tools_nc_edit_fail($e->getMessage(), array('nc_nextcloud_url'), 'Nextcloud / WebDAV');
|
||||
}
|
||||
|
||||
$nextcloud_url = '';
|
||||
$last_probe = null;
|
||||
$last_status_url = '';
|
||||
foreach ($candidate_urls as $candidate_url)
|
||||
{
|
||||
$status_url = $candidate_url.'/status.php';
|
||||
$probe = bratonien_tools_nc_edit_probe($status_url);
|
||||
$last_probe = $probe;
|
||||
$last_status_url = $status_url;
|
||||
|
||||
if (!$probe['ok'] || $probe['http'] < 200 || $probe['http'] >= 300)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
$status = json_decode($probe['body'], true);
|
||||
if (!is_array($status) || empty($status['installed']))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
$nextcloud_url = $candidate_url;
|
||||
break;
|
||||
}
|
||||
|
||||
if ($nextcloud_url === '')
|
||||
{
|
||||
$attempts = array();
|
||||
foreach ($candidate_urls as $candidate_url)
|
||||
{
|
||||
$attempts[] = $candidate_url.'/status.php';
|
||||
}
|
||||
if (is_array($last_probe) && !$last_probe['ok'])
|
||||
{
|
||||
$technical = $last_probe['errno'] >= 0
|
||||
? 'cURL '.$last_probe['errno'].($last_probe['error'] !== '' ? ': '.$last_probe['error'] : '')
|
||||
: $last_probe['error'];
|
||||
bratonien_tools_nc_edit_fail(
|
||||
'Die Nextcloud-Adresse ist vom Piwigo-Server aus nicht erreichbar. Ohne angegebenes Protokoll wurden HTTPS und HTTP geprüft.',
|
||||
array('nc_nextcloud_url'),
|
||||
'Nextcloud / WebDAV – Erreichbarkeit',
|
||||
$technical.' · Geprüft: '.implode(' ; ', $attempts)
|
||||
);
|
||||
}
|
||||
|
||||
bratonien_tools_nc_edit_fail(
|
||||
'Unter der angegebenen Adresse wurde keine erreichbare installierte Nextcloud gefunden. Ohne angegebenes Protokoll wurden HTTPS und HTTP geprüft.',
|
||||
array('nc_nextcloud_url'),
|
||||
'Nextcloud / WebDAV – Erkennung',
|
||||
'Geprüft: '.implode(' ; ', $attempts).($last_probe ? ' · Letzter HTTP-Status: '.$last_probe['http'] : '')
|
||||
);
|
||||
}
|
||||
|
||||
$_POST['nc_nextcloud_url'] = $nextcloud_url;
|
||||
|
||||
$user_url = $nextcloud_url.'/ocs/v2.php/cloud/user?format=json';
|
||||
$user_probe = bratonien_tools_nc_edit_probe($user_url, $nextcloud_user, $nextcloud_password, array('OCS-APIRequest: true'));
|
||||
if (!$user_probe['ok'])
|
||||
{
|
||||
$technical = $user_probe['errno'] >= 0
|
||||
? 'cURL '.$user_probe['errno'].($user_probe['error'] !== '' ? ': '.$user_probe['error'] : '')
|
||||
: $user_probe['error'];
|
||||
bratonien_tools_nc_edit_fail(
|
||||
'Die Nextcloud-Anmeldung konnte technisch nicht geprüft werden.',
|
||||
array('nc_nextcloud_url','nc_nextcloud_user','nc_nextcloud_password'),
|
||||
'Nextcloud / WebDAV – Anmeldung',
|
||||
$technical.' · Ziel: '.$user_url
|
||||
);
|
||||
}
|
||||
if ($user_probe['http'] === 401 || $user_probe['http'] === 403)
|
||||
{
|
||||
bratonien_tools_nc_edit_fail(
|
||||
'Nextcloud hat Benutzername oder Passwort abgelehnt.',
|
||||
array('nc_nextcloud_user','nc_nextcloud_password'),
|
||||
'Nextcloud / WebDAV – Anmeldung',
|
||||
'HTTP '.$user_probe['http']
|
||||
);
|
||||
}
|
||||
if ($user_probe['http'] < 200 || $user_probe['http'] >= 300)
|
||||
{
|
||||
bratonien_tools_nc_edit_fail(
|
||||
'Nextcloud ist erreichbar, aber die Benutzerprüfung wurde vom Server abgelehnt.',
|
||||
array('nc_nextcloud_user','nc_nextcloud_password'),
|
||||
'Nextcloud / WebDAV – Anmeldung',
|
||||
'HTTP '.$user_probe['http'].' · Ziel: '.$user_url
|
||||
);
|
||||
}
|
||||
try
|
||||
{
|
||||
bratonien_tools_nc_wizard_ocs_data($user_probe['body']);
|
||||
}
|
||||
catch (Throwable $e)
|
||||
{
|
||||
bratonien_tools_nc_edit_fail(
|
||||
'Nextcloud antwortet auf die Benutzerprüfung, die Antwort ist aber nicht gültig: '.$e->getMessage(),
|
||||
array('nc_nextcloud_user','nc_nextcloud_password'),
|
||||
'Nextcloud / WebDAV – Anmeldung'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
$api_key_id = trim((string)($_POST['nc_connection_api_key_id'] ?? ($credentials['api_key_id'] ?? '')));
|
||||
$submitted_api_secret = trim((string)($_POST['nc_connection_api_key_secret'] ?? ''));
|
||||
$api_key_secret = $submitted_api_secret !== '' ? $submitted_api_secret : trim((string)($credentials['api_key_secret'] ?? ''));
|
||||
if (($api_key_id === '') !== ($api_key_secret === ''))
|
||||
{
|
||||
$missing = $api_key_id === '' ? array('nc_connection_api_key_id') : array('nc_connection_api_key_secret');
|
||||
bratonien_tools_nc_edit_fail(
|
||||
'API-Schlüssel-ID und API-Geheimnis müssen gemeinsam vollständig sein.',
|
||||
$missing,
|
||||
'Piwigo API'
|
||||
);
|
||||
}
|
||||
if ($api_key_id !== '')
|
||||
{
|
||||
try
|
||||
{
|
||||
bratonien_tools_nc_connector_validate_scoped_api($api_key_id, $api_key_secret);
|
||||
}
|
||||
catch (Throwable $e)
|
||||
{
|
||||
bratonien_tools_nc_edit_fail(
|
||||
'Der Piwigo-API-Zugang konnte nicht bestätigt werden: '.$e->getMessage(),
|
||||
array('nc_connection_api_key_id','nc_connection_api_key_secret'),
|
||||
'Piwigo API'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
$result = bratonien_tools_nc_connector_update_local_friendly();
|
||||
bratonien_tools_nc_edit_json(200, array(
|
||||
'ok'=>true,
|
||||
'message'=>(string)($result['message'] ?? 'Verbindung wurde gespeichert.'),
|
||||
'fields'=>array(),
|
||||
));
|
||||
}
|
||||
catch (Throwable $e)
|
||||
{
|
||||
$message = trim($e->getMessage());
|
||||
if ($message === '') $message = 'Die Verbindung konnte nicht gespeichert werden.';
|
||||
|
||||
$fields = array();
|
||||
$stage = 'Verbindung';
|
||||
$add = function($name) use (&$fields)
|
||||
{
|
||||
if (!in_array($name, $fields, true)) $fields[] = $name;
|
||||
};
|
||||
|
||||
if (stripos($message, 'Name') !== false && stripos($message, 'Datenbankname') === false) $add('connection_name');
|
||||
if (stripos($message, 'Datenbank-Server') !== false) { $add('nc_host'); $stage = 'Legacy-Datenbank'; }
|
||||
if (stripos($message, 'Datenbank-Port') !== false) { $add('nc_port'); $stage = 'Legacy-Datenbank'; }
|
||||
if (stripos($message, 'Datenbankname') !== false) { $add('nc_database'); $stage = 'Legacy-Datenbank'; }
|
||||
if (stripos($message, 'Reader-Benutzer') !== false) { $add('nc_user'); $stage = 'Legacy-Datenbank'; }
|
||||
if (stripos($message, 'Datenbankpasswort') !== false) { $add('nc_db_password'); $stage = 'Legacy-Datenbank'; }
|
||||
if (stripos($message, 'Storage-ID') !== false) { $add('nc_storage_id[]'); $stage = 'Speicherorte'; }
|
||||
if (stripos($message, 'lokaler Pfad') !== false || stripos($message, 'Speicherort') !== false) { $add('nc_local_mount[]'); $stage = 'Speicherorte'; }
|
||||
if (stripos($message, 'Galerieordner') !== false) { $add('nc_gallery_root'); $stage = 'Erweiterte Legacy-Einstellungen'; }
|
||||
if (stripos($message, 'Datenbankansichten') !== false || stripos($message, 'Source-View') !== false) { $add('nc_source_view'); $stage = 'Erweiterte Legacy-Einstellungen'; }
|
||||
if (stripos($message, 'Datenbankansichten') !== false || stripos($message, 'Activity-View') !== false) { $add('nc_activity_view'); $stage = 'Erweiterte Legacy-Einstellungen'; }
|
||||
|
||||
if (stripos($message, 'Nextcloud') !== false)
|
||||
{
|
||||
$stage = 'Nextcloud / WebDAV';
|
||||
if (stripos($message, 'Adresse') !== false) $add('nc_nextcloud_url');
|
||||
if (stripos($message, 'Benutzer') !== false) $add('nc_nextcloud_user');
|
||||
if (stripos($message, 'Passwort') !== false) $add('nc_nextcloud_password');
|
||||
}
|
||||
if (stripos($message, 'API') !== false)
|
||||
{
|
||||
$stage = 'Piwigo API';
|
||||
$add('nc_connection_api_key_id');
|
||||
$add('nc_connection_api_key_secret');
|
||||
}
|
||||
|
||||
bratonien_tools_nc_edit_fail(
|
||||
$message,
|
||||
$fields,
|
||||
$stage,
|
||||
'Interne Prüfung: '.get_class($e)
|
||||
);
|
||||
}
|
||||
104
nc-connector-source-picker-start.php
Normal file
104
nc-connector-source-picker-start.php
Normal file
@@ -0,0 +1,104 @@
|
||||
<?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');
|
||||
|
||||
function bratonien_tools_nc_source_picker_json($status, array $payload)
|
||||
{
|
||||
http_response_code((int)$status);
|
||||
echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
||||
exit;
|
||||
}
|
||||
|
||||
function bratonien_tools_nc_source_picker_fail($message, array $fields = array())
|
||||
{
|
||||
bratonien_tools_nc_source_picker_json(422, array(
|
||||
'ok'=>false,
|
||||
'message'=>(string)$message,
|
||||
'fields'=>array_values(array_unique($fields)),
|
||||
));
|
||||
}
|
||||
|
||||
if (!defined('BRATONIEN_TOOLS_PATH'))
|
||||
{
|
||||
bratonien_tools_nc_source_picker_json(404, array('ok'=>false, 'message'=>'Bratonien Tools ist nicht aktiv.', 'fields'=>array()));
|
||||
}
|
||||
if (!function_exists('is_admin') || !is_admin())
|
||||
{
|
||||
bratonien_tools_nc_source_picker_json(403, array('ok'=>false, 'message'=>'Administratorrechte erforderlich.', 'fields'=>array()));
|
||||
}
|
||||
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST')
|
||||
{
|
||||
bratonien_tools_nc_source_picker_json(405, array('ok'=>false, 'message'=>'Nur POST ist erlaubt.', 'fields'=>array()));
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
check_pwg_token();
|
||||
require_once(BRATONIEN_TOOLS_PATH.'include/tool_registry.inc.php');
|
||||
|
||||
$id = (int)($_POST['connection_id'] ?? 0);
|
||||
$connection = bratonien_tools_nc_connector_connection($id, true);
|
||||
if (!$connection)
|
||||
{
|
||||
bratonien_tools_nc_source_picker_fail('Die zu bearbeitende Verbindung wurde nicht gefunden.');
|
||||
}
|
||||
if ((string)$connection['adapter'] !== 'local')
|
||||
{
|
||||
bratonien_tools_nc_source_picker_fail('Die automatische Migrationsauswahl ist nur für die bestehende Legacy-Verbindung vorgesehen.');
|
||||
}
|
||||
|
||||
$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'] ?? ''));
|
||||
$password = (string)($credentials['nextcloud_password'] ?? '');
|
||||
|
||||
$missing = array();
|
||||
if ($base_url === '') $missing[] = 'nc_nextcloud_url';
|
||||
if ($username === '') $missing[] = 'nc_nextcloud_user';
|
||||
if ($password === '') $missing[] = 'nc_nextcloud_password';
|
||||
if ($missing)
|
||||
{
|
||||
bratonien_tools_nc_source_picker_fail(
|
||||
'Für die automatische Ordnerauswahl müssen Nextcloud-Adresse, Benutzer und Passwort gespeichert sein.',
|
||||
$missing
|
||||
);
|
||||
}
|
||||
|
||||
bratonien_tools_nc_connector_prepare_webdav_wizard_from_connection($connection, 'migrate');
|
||||
|
||||
$state = bratonien_tools_nc_wizard_state();
|
||||
if ((int)($state['step'] ?? 0) !== 2 || empty($state['scan_ok']) || empty($state['directory_selection_ready']))
|
||||
{
|
||||
$detail = trim((string)($state['technical_error'] ?? ''));
|
||||
bratonien_tools_nc_source_picker_fail(
|
||||
$detail !== '' ? 'Die Nextcloud-Ordner konnten nicht geladen werden: '.$detail : 'Die Nextcloud-Ordner konnten nicht geladen werden.',
|
||||
array('nc_nextcloud_url','nc_nextcloud_user','nc_nextcloud_password')
|
||||
);
|
||||
}
|
||||
|
||||
bratonien_tools_nc_source_picker_json(200, array(
|
||||
'ok'=>true,
|
||||
'message'=>'Nextcloud-Ordner wurden geladen. Die Auswahl wird geöffnet.',
|
||||
'fields'=>array(),
|
||||
));
|
||||
}
|
||||
catch (Throwable $e)
|
||||
{
|
||||
$message = trim($e->getMessage());
|
||||
if ($message === '') $message = 'Die Nextcloud-Ordnerauswahl konnte nicht vorbereitet werden.';
|
||||
bratonien_tools_nc_source_picker_fail(
|
||||
$message,
|
||||
array('nc_nextcloud_url','nc_nextcloud_user','nc_nextcloud_password')
|
||||
);
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
169
runtime/cleanup-webdav-piwigo.php
Normal file
169
runtime/cleanup-webdav-piwigo.php
Normal file
@@ -0,0 +1,169 @@
|
||||
#!/usr/bin/env php
|
||||
<?php
|
||||
if (PHP_SAPI !== 'cli')
|
||||
{
|
||||
fwrite(STDERR, "CLI only\n");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
$pluginRoot = dirname(__DIR__);
|
||||
$piwigoRoot = dirname($pluginRoot, 2);
|
||||
define('PHPWG_ROOT_PATH', rtrim($piwigoRoot, '/').'/');
|
||||
|
||||
$_SERVER['REMOTE_ADDR'] = '127.0.0.1';
|
||||
$_SERVER['SERVER_ADDR'] = '127.0.0.1';
|
||||
$_SERVER['SERVER_NAME'] = 'localhost';
|
||||
$_SERVER['HTTP_HOST'] = 'localhost';
|
||||
$_SERVER['SERVER_PORT'] = '80';
|
||||
$_SERVER['REQUEST_METHOD'] = 'GET';
|
||||
$_SERVER['REQUEST_URI'] = '/';
|
||||
$_SERVER['SCRIPT_NAME'] = '/plugins/bratonien_tools/runtime/cleanup-webdav-piwigo.php';
|
||||
$_SERVER['PHP_SELF'] = $_SERVER['SCRIPT_NAME'];
|
||||
$_SERVER['QUERY_STRING'] = '';
|
||||
$_SERVER['HTTPS'] = 'off';
|
||||
|
||||
require_once(PHPWG_ROOT_PATH.'include/common.inc.php');
|
||||
require_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
|
||||
|
||||
function bratonien_cleanup_tree($path, $allowed_root)
|
||||
{
|
||||
$path = rtrim((string)$path, '/');
|
||||
$allowed_root = rtrim((string)$allowed_root, '/');
|
||||
if ($path === '' || $allowed_root === '' || strpos($path, $allowed_root.'/') !== 0 || !file_exists($path)) return;
|
||||
|
||||
if (is_link($path) || is_file($path))
|
||||
{
|
||||
@unlink($path);
|
||||
return;
|
||||
}
|
||||
|
||||
$items = @scandir($path);
|
||||
if (!is_array($items)) return;
|
||||
foreach ($items as $item)
|
||||
{
|
||||
if ($item === '.' || $item === '..') continue;
|
||||
bratonien_cleanup_tree($path.'/'.$item, $allowed_root);
|
||||
}
|
||||
@rmdir($path);
|
||||
}
|
||||
|
||||
function bratonien_webdav_site_images($site_id)
|
||||
{
|
||||
$rows = array();
|
||||
$query = '
|
||||
SELECT DISTINCT i.id, i.path, i.representative_ext
|
||||
FROM '.IMAGES_TABLE.' AS i
|
||||
LEFT JOIN '.CATEGORIES_TABLE.' AS sc ON sc.id = i.storage_category_id
|
||||
LEFT JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON ic.image_id = i.id
|
||||
LEFT JOIN '.CATEGORIES_TABLE.' AS vc ON vc.id = ic.category_id
|
||||
WHERE sc.site_id = '.(int)$site_id.' OR vc.site_id = '.(int)$site_id.'
|
||||
;';
|
||||
$result = pwg_query($query);
|
||||
while ($row = pwg_db_fetch_assoc($result))
|
||||
{
|
||||
$row['id'] = (int)$row['id'];
|
||||
$rows[$row['id']] = $row;
|
||||
}
|
||||
return $rows;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
$connection_table = function_exists('bratonien_tools_nc_connector_table')
|
||||
? bratonien_tools_nc_connector_table()
|
||||
: $GLOBALS['prefixeTable'].'bratonien_tools_nc_connections';
|
||||
|
||||
$active = array();
|
||||
$exists = pwg_query("SHOW TABLES LIKE '".pwg_db_real_escape_string($connection_table)."'");
|
||||
if (pwg_db_num_rows($exists))
|
||||
{
|
||||
$result = pwg_query("SELECT id FROM `".$connection_table."`");
|
||||
while ($row = pwg_db_fetch_assoc($result))
|
||||
{
|
||||
$active[(int)$row['id']] = true;
|
||||
}
|
||||
}
|
||||
|
||||
$site_prefix = './_data/bratonien-tools/nc-webdav-gallery/connection-';
|
||||
$result = pwg_query(
|
||||
"SELECT id, galleries_url FROM ".SITES_TABLE.
|
||||
" WHERE galleries_url LIKE '".pwg_db_real_escape_string($site_prefix)."%'"
|
||||
);
|
||||
|
||||
$removed_sites = 0;
|
||||
$removed_images = 0;
|
||||
while ($site = pwg_db_fetch_assoc($result))
|
||||
{
|
||||
$site_id = (int)$site['id'];
|
||||
$site_url = (string)$site['galleries_url'];
|
||||
if (!preg_match('#^\./_data/bratonien-tools/nc-webdav-gallery/connection-([0-9]+)/$#', $site_url, $match)) continue;
|
||||
|
||||
$connection_id = (int)$match[1];
|
||||
if ($connection_id < 1 || isset($active[$connection_id])) continue;
|
||||
|
||||
$images = bratonien_webdav_site_images($site_id);
|
||||
foreach ($images as $row)
|
||||
{
|
||||
try
|
||||
{
|
||||
delete_element_derivatives($row);
|
||||
}
|
||||
catch (Throwable $e)
|
||||
{
|
||||
fwrite(STDERR, 'WebDAV-Cleanup: Derivate von Bild #'.(int)$row['id'].' konnten nicht vollständig entfernt werden: '.$e->getMessage()."\n");
|
||||
}
|
||||
}
|
||||
|
||||
delete_site($site_id);
|
||||
|
||||
if ($images)
|
||||
{
|
||||
$ids = array_keys($images);
|
||||
$remaining = query2array(
|
||||
'SELECT id FROM '.IMAGES_TABLE.' WHERE id IN ('.implode(',', array_map('intval', $ids)).')',
|
||||
null,
|
||||
'id'
|
||||
);
|
||||
if ($remaining)
|
||||
{
|
||||
delete_elements(array_map('intval', $remaining), false);
|
||||
}
|
||||
}
|
||||
|
||||
$removed_sites++;
|
||||
$removed_images += count($images);
|
||||
echo 'NC WebDAV: entferne verwaiste Piwigo-Site '.$site_id.' für gelöschte Verbindung '.$connection_id.".\n";
|
||||
|
||||
$gallery_root = PHPWG_ROOT_PATH.'_data/bratonien-tools/nc-webdav-gallery';
|
||||
$source_root = PHPWG_ROOT_PATH.'_data/bratonien-tools/nc-webdav-source';
|
||||
$preview_root = PHPWG_ROOT_PATH.'_data/bratonien-tools/nc-webdav-preview';
|
||||
bratonien_cleanup_tree($gallery_root.'/connection-'.$connection_id, $gallery_root);
|
||||
bratonien_cleanup_tree($source_root.'/connection-'.$connection_id, $source_root);
|
||||
bratonien_cleanup_tree($preview_root.'/connection-'.$connection_id, $preview_root);
|
||||
|
||||
$state_root = '/var/lib/bratonien-tools/nc-connector';
|
||||
bratonien_cleanup_tree($state_root.'/connection-'.$connection_id, $state_root);
|
||||
|
||||
foreach (glob('/etc/bratonien-tools/nc-connector/webdav-connection-'.$connection_id.'.*') ?: array() as $file)
|
||||
{
|
||||
@unlink($file);
|
||||
}
|
||||
|
||||
$status_root = PHPWG_ROOT_PATH.'_data/bratonien-tools/nc-connector-status';
|
||||
@unlink($status_root.'/connection-'.$connection_id.'.json');
|
||||
@unlink($status_root.'/deleted-'.$connection_id);
|
||||
}
|
||||
|
||||
if ($removed_sites > 0)
|
||||
{
|
||||
invalidate_user_cache(true);
|
||||
}
|
||||
|
||||
echo 'NC WebDAV Piwigo-Cleanup: sites='.$removed_sites.' bilder='.$removed_images."\n";
|
||||
exit(0);
|
||||
}
|
||||
catch (Throwable $e)
|
||||
{
|
||||
fwrite(STDERR, 'NC WebDAV Piwigo-Cleanup: '.$e->getMessage()."\n");
|
||||
exit(1);
|
||||
}
|
||||
@@ -6,6 +6,8 @@ if (PHP_SAPI !== 'cli')
|
||||
exit(1);
|
||||
}
|
||||
|
||||
const BRATONIEN_WEBDAV_DERIVATIVE_BUILDER_VERSION = '0.9.6.1';
|
||||
|
||||
$options = getopt('', array('piwigo-root:', 'connection-id:'));
|
||||
$piwigo_root = rtrim((string)($options['piwigo-root'] ?? ''), '/');
|
||||
$connection_id = (int)($options['connection-id'] ?? 0);
|
||||
@@ -31,7 +33,7 @@ $_SERVER['REQUEST_URI'] = '/';
|
||||
$_SERVER['SCRIPT_NAME'] = '/plugins/bratonien_tools/runtime/lib/build-webdav-derivatives.php';
|
||||
$_SERVER['PHP_SELF'] = $_SERVER['SCRIPT_NAME'];
|
||||
$_SERVER['QUERY_STRING'] = '';
|
||||
$_SERVER['HTTP_USER_AGENT'] = 'Bratonien-WebDAV-Derivative-Builder/0.9.5.21';
|
||||
$_SERVER['HTTP_USER_AGENT'] = 'Bratonien-WebDAV-Derivative-Builder/'.BRATONIEN_WEBDAV_DERIVATIVE_BUILDER_VERSION;
|
||||
$_SERVER['HTTPS'] = 'off';
|
||||
|
||||
require_once(PHPWG_ROOT_PATH.'include/common.inc.php');
|
||||
@@ -53,10 +55,11 @@ try
|
||||
}
|
||||
|
||||
$images = 0;
|
||||
$generated = 0;
|
||||
$generated_or_ready = 0;
|
||||
$identity = 0;
|
||||
$metadata_repaired = 0;
|
||||
$errors = 0;
|
||||
$error_lines = array();
|
||||
|
||||
$result = pwg_query('SELECT * FROM '.IMAGES_TABLE.' ORDER BY id');
|
||||
while ($row = pwg_db_fetch_assoc($result))
|
||||
@@ -70,7 +73,15 @@ try
|
||||
if (!$preview)
|
||||
{
|
||||
$errors++;
|
||||
fwrite(STDERR, 'Bild #'.$image_id.": vorbereitetes WebDAV-Preview fehlt.\n");
|
||||
$error_lines[] = 'Bild #'.$image_id.': vorbereitetes WebDAV-Preview fehlt.';
|
||||
continue;
|
||||
}
|
||||
|
||||
$preview_ext = strtolower(pathinfo($preview, PATHINFO_EXTENSION));
|
||||
if (!in_array($preview_ext, array('jpg', 'jpeg', 'png', 'gif'), true))
|
||||
{
|
||||
$errors++;
|
||||
$error_lines[] = 'Bild #'.$image_id.': Preview-Format '.$preview_ext.' ist nicht Piwigo-kompatibel; Precache muss neu erzeugt werden.';
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -78,7 +89,7 @@ try
|
||||
if (!is_array($size) || empty($size[0]) || empty($size[1]))
|
||||
{
|
||||
$errors++;
|
||||
fwrite(STDERR, 'Bild #'.$image_id.": Abmessungen des WebDAV-Previews konnten nicht gelesen werden.\n");
|
||||
$error_lines[] = 'Bild #'.$image_id.': Preview ist kein lesbares Bild: '.$preview;
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -109,20 +120,21 @@ try
|
||||
continue;
|
||||
}
|
||||
|
||||
if (bratonien_tools_webdav_generate_derivative($params, $src))
|
||||
$detail = '';
|
||||
if (bratonien_tools_webdav_generate_derivative($params, $src, $detail))
|
||||
{
|
||||
$generated++;
|
||||
$generated_or_ready++;
|
||||
}
|
||||
else
|
||||
{
|
||||
$errors++;
|
||||
fwrite(STDERR, 'Bild #'.$image_id.' '.$variant_name.": Derivat konnte nicht erzeugt werden.\n");
|
||||
$error_lines[] = 'Bild #'.$image_id.' '.$variant_name.': '.($detail !== '' ? $detail : 'Derivat konnte nicht erzeugt werden.');
|
||||
}
|
||||
}
|
||||
catch (Throwable $e)
|
||||
{
|
||||
$errors++;
|
||||
fwrite(STDERR, 'Bild #'.$image_id.' '.$variant_name.': '.$e->getMessage()."\n");
|
||||
$error_lines[] = 'Bild #'.$image_id.' '.$variant_name.': '.get_class($e).': '.$e->getMessage();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -133,16 +145,30 @@ try
|
||||
invalidate_user_cache(true);
|
||||
}
|
||||
|
||||
echo 'WebDAV-Derivate: bilder='.$images.
|
||||
if ($errors > 0)
|
||||
{
|
||||
foreach (array_slice($error_lines, 0, 30) as $line)
|
||||
{
|
||||
fwrite(STDERR, $line."\n");
|
||||
}
|
||||
if (count($error_lines) > 30)
|
||||
{
|
||||
fwrite(STDERR, 'Weitere Fehler: '.(count($error_lines) - 30)."\n");
|
||||
}
|
||||
}
|
||||
|
||||
echo 'WebDAV-Derivative-Builder: version='.BRATONIEN_WEBDAV_DERIVATIVE_BUILDER_VERSION.
|
||||
' bilder='.$images.
|
||||
' varianten='.count($variants).
|
||||
' erzeugt='.$generated.
|
||||
' bereit='.$generated_or_ready.
|
||||
' identisch='.$identity.
|
||||
' metadaten_repariert='.$metadata_repaired.
|
||||
' fehler='.$errors."\n";
|
||||
|
||||
exit($errors > 0 ? 1 : 0);
|
||||
}
|
||||
catch (Throwable $e)
|
||||
{
|
||||
fwrite(STDERR, 'WebDAV-Derivate: '.$e->getMessage()."\n");
|
||||
fwrite(STDERR, 'WebDAV-Derivate: '.get_class($e).': '.$e->getMessage()."\n");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
@@ -6,6 +6,10 @@ if (PHP_SAPI !== 'cli')
|
||||
exit(1);
|
||||
}
|
||||
|
||||
const BRATONIEN_WEBDAV_PREVIEW_VERSION = 2;
|
||||
const BRATONIEN_WEBDAV_PREVIEW_MAX_EDGE = 4096;
|
||||
const BRATONIEN_WEBDAV_PREVIEW_JPEG_QUALITY = 88;
|
||||
|
||||
function fail_preview($message)
|
||||
{
|
||||
throw new RuntimeException($message);
|
||||
@@ -28,72 +32,161 @@ function fetch_remote_blob($url, $user, $password)
|
||||
CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
|
||||
CURLOPT_USERPWD => $user.':'.$password,
|
||||
CURLOPT_FAILONERROR => false,
|
||||
CURLOPT_USERAGENT => 'Bratonien-Tools-WebDAV-Precache/0.9.5.19',
|
||||
CURLOPT_USERAGENT => 'Bratonien-Tools-WebDAV-Precache/0.9.6.1',
|
||||
));
|
||||
$body = curl_exec($ch);
|
||||
$errno = curl_errno($ch);
|
||||
$error = curl_error($ch);
|
||||
$http = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
curl_close($ch);
|
||||
|
||||
if ($body === false || $errno !== 0) fail_preview('WebDAV-Bild konnte nicht geladen werden: '.$error);
|
||||
if ($http < 200 || $http >= 300) fail_preview('WebDAV-Bild antwortete mit HTTP '.$http.'.');
|
||||
if ($body === '') fail_preview('WebDAV-Bild ist leer.');
|
||||
return (string)$body;
|
||||
}
|
||||
|
||||
function write_preview($blob, $target)
|
||||
function preview_extension_for_entry(array $entry)
|
||||
{
|
||||
$content_type = strtolower(trim((string)($entry['content_type'] ?? '')));
|
||||
$path = strtolower((string)($entry['webdav_path'] ?? ''));
|
||||
if ($content_type === 'image/png' || preg_match('/\.png$/', $path))
|
||||
{
|
||||
return 'png';
|
||||
}
|
||||
return 'jpg';
|
||||
}
|
||||
|
||||
function preview_target_for_entry($cache_dir, $key, array $entry)
|
||||
{
|
||||
return $cache_dir.'/'.$key.'.'.preview_extension_for_entry($entry);
|
||||
}
|
||||
|
||||
function remove_other_preview_format($cache_dir, $key, $keep_target)
|
||||
{
|
||||
foreach (array('jpg', 'png', 'webp') as $ext)
|
||||
{
|
||||
$candidate = $cache_dir.'/'.$key.'.'.$ext;
|
||||
if ($candidate !== $keep_target && is_file($candidate)) @unlink($candidate);
|
||||
}
|
||||
}
|
||||
|
||||
function write_preview_imagick($blob, $target, $extension)
|
||||
{
|
||||
$image = new Imagick();
|
||||
try
|
||||
{
|
||||
$image->readImageBlob($blob);
|
||||
if (method_exists($image, 'autoOrientImage')) @$image->autoOrientImage();
|
||||
$image->setIteratorIndex(0);
|
||||
$image->thumbnailImage(BRATONIEN_WEBDAV_PREVIEW_MAX_EDGE, BRATONIEN_WEBDAV_PREVIEW_MAX_EDGE, true, true);
|
||||
$image->stripImage();
|
||||
|
||||
if ($extension === 'png')
|
||||
{
|
||||
$image->setImageFormat('png');
|
||||
}
|
||||
else
|
||||
{
|
||||
$image->setImageBackgroundColor('white');
|
||||
if (method_exists($image, 'mergeImageLayers'))
|
||||
{
|
||||
$image = $image->mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN);
|
||||
}
|
||||
$image->setImageFormat('jpeg');
|
||||
$image->setImageCompression(Imagick::COMPRESSION_JPEG);
|
||||
$image->setImageCompressionQuality(BRATONIEN_WEBDAV_PREVIEW_JPEG_QUALITY);
|
||||
$image->setInterlaceScheme(Imagick::INTERLACE_PLANE);
|
||||
}
|
||||
|
||||
if (!$image->writeImage($target)) fail_preview('Imagick konnte das Preview nicht schreiben.');
|
||||
}
|
||||
finally
|
||||
{
|
||||
$image->clear();
|
||||
$image->destroy();
|
||||
}
|
||||
}
|
||||
|
||||
function write_preview_gd($blob, $target, $extension)
|
||||
{
|
||||
$source = @imagecreatefromstring($blob);
|
||||
if (!$source) fail_preview('GD konnte das Bild nicht dekodieren.');
|
||||
|
||||
try
|
||||
{
|
||||
$width = imagesx($source);
|
||||
$height = imagesy($source);
|
||||
if ($width < 1 || $height < 1) fail_preview('Bildabmessungen sind ungültig.');
|
||||
|
||||
$scale = min(1, BRATONIEN_WEBDAV_PREVIEW_MAX_EDGE / $width, BRATONIEN_WEBDAV_PREVIEW_MAX_EDGE / $height);
|
||||
$target_width = max(1, (int)round($width * $scale));
|
||||
$target_height = max(1, (int)round($height * $scale));
|
||||
$preview = imagecreatetruecolor($target_width, $target_height);
|
||||
if (!$preview) fail_preview('GD konnte die Preview-Arbeitsfläche nicht anlegen.');
|
||||
|
||||
try
|
||||
{
|
||||
if ($extension === 'png')
|
||||
{
|
||||
imagealphablending($preview, false);
|
||||
imagesavealpha($preview, true);
|
||||
$transparent = imagecolorallocatealpha($preview, 0, 0, 0, 127);
|
||||
imagefilledrectangle($preview, 0, 0, $target_width, $target_height, $transparent);
|
||||
}
|
||||
else
|
||||
{
|
||||
$white = imagecolorallocate($preview, 255, 255, 255);
|
||||
imagefilledrectangle($preview, 0, 0, $target_width, $target_height, $white);
|
||||
}
|
||||
|
||||
if (!imagecopyresampled($preview, $source, 0, 0, 0, 0, $target_width, $target_height, $width, $height))
|
||||
{
|
||||
fail_preview('GD konnte das Preview nicht skalieren.');
|
||||
}
|
||||
|
||||
$written = $extension === 'png'
|
||||
? imagepng($preview, $target, 6)
|
||||
: imagejpeg($preview, $target, BRATONIEN_WEBDAV_PREVIEW_JPEG_QUALITY);
|
||||
if (!$written) fail_preview('GD konnte das Preview nicht schreiben.');
|
||||
}
|
||||
finally
|
||||
{
|
||||
imagedestroy($preview);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
imagedestroy($source);
|
||||
}
|
||||
}
|
||||
|
||||
function write_preview($blob, $target, $extension)
|
||||
{
|
||||
$dir = dirname($target);
|
||||
if (!is_dir($dir) && !mkdir($dir, 0755, true) && !is_dir($dir)) fail_preview('Preview-Verzeichnis konnte nicht angelegt werden.');
|
||||
|
||||
if (class_exists('Imagick'))
|
||||
{
|
||||
$image = new Imagick();
|
||||
$image->readImageBlob($blob);
|
||||
if (method_exists($image, 'autoOrientImage')) @$image->autoOrientImage();
|
||||
$image->setIteratorIndex(0);
|
||||
$image->thumbnailImage(1600, 1600, true, true);
|
||||
$image->setImageFormat('webp');
|
||||
$image->setImageCompressionQuality(85);
|
||||
if (!$image->writeImage($target)) fail_preview('Imagick konnte das Preview nicht schreiben.');
|
||||
$image->clear();
|
||||
$image->destroy();
|
||||
@chmod($target, 0644);
|
||||
return;
|
||||
write_preview_imagick($blob, $target, $extension);
|
||||
}
|
||||
|
||||
if (function_exists('imagecreatefromstring') && function_exists('imagewebp'))
|
||||
elseif (function_exists('imagecreatefromstring') && function_exists('imagejpeg') && function_exists('imagepng'))
|
||||
{
|
||||
$source = @imagecreatefromstring($blob);
|
||||
if (!$source) fail_preview('GD konnte das Bild nicht dekodieren.');
|
||||
$width = imagesx($source);
|
||||
$height = imagesy($source);
|
||||
if ($width < 1 || $height < 1)
|
||||
{
|
||||
imagedestroy($source);
|
||||
fail_preview('Bildabmessungen sind ungültig.');
|
||||
}
|
||||
$scale = min(1, 1600 / $width, 1600 / $height);
|
||||
$target_width = max(1, (int)round($width * $scale));
|
||||
$target_height = max(1, (int)round($height * $scale));
|
||||
$preview = imagecreatetruecolor($target_width, $target_height);
|
||||
imagealphablending($preview, false);
|
||||
imagesavealpha($preview, true);
|
||||
$transparent = imagecolorallocatealpha($preview, 0, 0, 0, 127);
|
||||
imagefilledrectangle($preview, 0, 0, $target_width, $target_height, $transparent);
|
||||
imagecopyresampled($preview, $source, 0, 0, 0, 0, $target_width, $target_height, $width, $height);
|
||||
if (!imagewebp($preview, $target, 85))
|
||||
{
|
||||
imagedestroy($preview);
|
||||
imagedestroy($source);
|
||||
fail_preview('GD konnte das Preview nicht schreiben.');
|
||||
}
|
||||
imagedestroy($preview);
|
||||
imagedestroy($source);
|
||||
@chmod($target, 0644);
|
||||
return;
|
||||
write_preview_gd($blob, $target, $extension);
|
||||
}
|
||||
else
|
||||
{
|
||||
fail_preview('Weder Imagick noch GD ist für die Preview-Erzeugung verfügbar.');
|
||||
}
|
||||
|
||||
fail_preview('Weder Imagick noch GD/WebP ist für die Preview-Erzeugung verfügbar.');
|
||||
clearstatcache(true, $target);
|
||||
$size = @getimagesize($target);
|
||||
if (!is_array($size) || empty($size[0]) || empty($size[1]) || !is_file($target) || filesize($target) < 64)
|
||||
{
|
||||
@unlink($target);
|
||||
fail_preview('Das erzeugte Preview ist ungültig.');
|
||||
}
|
||||
@chmod($target, 0644);
|
||||
}
|
||||
|
||||
try
|
||||
@@ -117,6 +210,7 @@ try
|
||||
|
||||
if (!is_dir($cache_dir) && !mkdir($cache_dir, 0755, true) && !is_dir($cache_dir)) fail_preview('Preview-Cache konnte nicht angelegt werden.');
|
||||
@chmod($cache_dir, 0755);
|
||||
|
||||
$state_file = $cache_dir.'/state.json';
|
||||
$old_state = array();
|
||||
if (is_readable($state_file))
|
||||
@@ -135,12 +229,26 @@ try
|
||||
if (!is_array($entry) || (string)($entry['kind'] ?? '') !== 'file') continue;
|
||||
$webdav_path = trim((string)($entry['webdav_path'] ?? ''), '/');
|
||||
if ($webdav_path === '') continue;
|
||||
|
||||
$etag = (string)($entry['etag'] ?? '');
|
||||
$key = sha1($webdav_path);
|
||||
$target = $cache_dir.'/'.$key.'.webp';
|
||||
$new_state[$key] = array('path'=>$webdav_path, 'etag'=>$etag);
|
||||
$target = preview_target_for_entry($cache_dir, $key, $entry);
|
||||
$extension = pathinfo($target, PATHINFO_EXTENSION);
|
||||
$new_state[$key] = array(
|
||||
'path' => $webdav_path,
|
||||
'etag' => $etag,
|
||||
'format' => $extension,
|
||||
'version' => BRATONIEN_WEBDAV_PREVIEW_VERSION,
|
||||
);
|
||||
|
||||
if (is_file($target) && isset($old_state[$key]) && (string)($old_state[$key]['etag'] ?? '') === $etag)
|
||||
$old = $old_state[$key] ?? null;
|
||||
if (
|
||||
is_file($target)
|
||||
&& is_array($old)
|
||||
&& (string)($old['etag'] ?? '') === $etag
|
||||
&& (string)($old['format'] ?? '') === $extension
|
||||
&& (int)($old['version'] ?? 0) === BRATONIEN_WEBDAV_PREVIEW_VERSION
|
||||
)
|
||||
{
|
||||
$cached++;
|
||||
continue;
|
||||
@@ -150,7 +258,8 @@ try
|
||||
{
|
||||
$url = $base_url.'/remote.php/dav/files/'.rawurlencode($user).'/'.quote_webdav_path($webdav_path);
|
||||
$blob = fetch_remote_blob($url, $user, $password);
|
||||
write_preview($blob, $target);
|
||||
write_preview($blob, $target, $extension);
|
||||
remove_other_preview_format($cache_dir, $key, $target);
|
||||
$generated++;
|
||||
}
|
||||
catch (Throwable $e)
|
||||
@@ -160,10 +269,12 @@ try
|
||||
}
|
||||
}
|
||||
|
||||
foreach (glob($cache_dir.'/*.webp') ?: array() as $file)
|
||||
foreach (glob($cache_dir.'/*') ?: array() as $file)
|
||||
{
|
||||
$key = basename($file, '.webp');
|
||||
if (!isset($new_state[$key])) @unlink($file);
|
||||
if (!is_file($file) || basename($file) === 'state.json') continue;
|
||||
$name = basename($file);
|
||||
if (!preg_match('/^([a-f0-9]{40})\.(jpg|png|webp)$/', $name, $m)) continue;
|
||||
if (!isset($new_state[$m[1]])) @unlink($file);
|
||||
}
|
||||
|
||||
file_put_contents($state_file, json_encode($new_state, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT)."\n", LOCK_EX);
|
||||
|
||||
@@ -5,13 +5,109 @@ CONFIG_DIR="/etc/bratonien-tools/nc-connector"
|
||||
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
|
||||
shopt -s nullglob
|
||||
|
||||
read_config_value() {
|
||||
local key="$1"
|
||||
local file="$2"
|
||||
local value
|
||||
value="$(sed -n "s/^${key}=//p" "$file" | tail -n 1)"
|
||||
value="${value%\"}"
|
||||
value="${value#\"}"
|
||||
value="${value%\'}"
|
||||
value="${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"
|
||||
local detail="$3"
|
||||
local fallback_used="$4"
|
||||
local success="$5"
|
||||
|
||||
[[ -n "${ROUTE_STATUS_FILE:-}" ]] || return 0
|
||||
mkdir -p -- "$(dirname -- "$ROUTE_STATUS_FILE")"
|
||||
|
||||
php -r '
|
||||
$payload = array(
|
||||
"timestamp" => time(),
|
||||
"route" => (string)$argv[2],
|
||||
"label" => (string)$argv[3],
|
||||
"detail" => (string)$argv[4],
|
||||
"fallback_used" => $argv[5] === "1",
|
||||
"success" => $argv[6] === "1"
|
||||
);
|
||||
$json = json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
|
||||
if (!is_string($json) || file_put_contents($argv[1], $json.PHP_EOL, LOCK_EX) === false) {
|
||||
fwrite(STDERR, "Route-Status konnte nicht geschrieben werden.\n");
|
||||
exit(1);
|
||||
}
|
||||
@chmod($argv[1], 0644);
|
||||
' "$ROUTE_STATUS_FILE" "$route" "$label" "$detail" "$fallback_used" "$success"
|
||||
}
|
||||
|
||||
if ! php "$SCRIPT_DIR/reconcile.php"; then
|
||||
echo "NC Connector: gespeicherte lokale Verbindungen konnten nicht mit der Runtime abgeglichen werden." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if ! php "$SCRIPT_DIR/reconcile-webdav.php"; then
|
||||
echo "NC Connector: WebDAV-Testverbindungen konnten nicht mit der parallelen Runtime abgeglichen werden." >&2
|
||||
echo "NC Connector: WebDAV-Verbindungen konnten nicht mit der Runtime abgeglichen werden." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if ! php "$SCRIPT_DIR/cleanup-webdav-piwigo.php"; then
|
||||
echo "NC Connector: Piwigo-Inhalte geloeschter WebDAV-Verbindungen konnten nicht bereinigt werden." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
@@ -28,20 +124,68 @@ if [[ ${#configs[@]} -eq 0 && ${#webdav_configs[@]} -eq 0 ]]; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
result=0
|
||||
|
||||
# WebDAV zuerst: Der parallele Shadow Tree muss bereits vollständig stehen,
|
||||
# bevor der weiterhin produktive lokale Weg seine normale Piwigo-
|
||||
# Dateisynchronisierung ausführt. So wird der neue Baum im selben Minutenlauf
|
||||
# sichtbar, ohne dass der WebDAV-Zweig selbst eine zweite globale Piwigo-
|
||||
# Synchronisierung startet.
|
||||
for config in "${webdav_configs[@]}"; do
|
||||
name="$(basename "$config")"
|
||||
echo "NC Connector WebDAV parallel: $name"
|
||||
if ! env PIWIGO_CONFIG="$config" bash "$SCRIPT_DIR/sync-webdav.sh"; then
|
||||
result=1
|
||||
fi
|
||||
route_piwigo_root=""
|
||||
for candidate in "${webdav_configs[@]}" "${configs[@]}"; do
|
||||
[[ -f "$candidate" ]] || continue
|
||||
route_piwigo_root="$(read_config_value PIWIGO_ROOT "$candidate")"
|
||||
[[ -n "$route_piwigo_root" ]] && break
|
||||
done
|
||||
[[ -n "$route_piwigo_root" ]] || route_piwigo_root="/var/www/piwigo"
|
||||
ROUTE_STATUS_FILE="${route_piwigo_root%/}/_data/bratonien-tools/nc-connector-status/route-status.json"
|
||||
|
||||
webdav_success=0
|
||||
webdav_failed=0
|
||||
webdav_failure_detail=""
|
||||
|
||||
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 \
|
||||
"webdav" \
|
||||
"WebDAV (primaer)" \
|
||||
"WebDAV erfolgreich. Legacy-Fallback wurde in diesem Lauf nicht ausgefuehrt." \
|
||||
"0" \
|
||||
"1"
|
||||
echo "NC Connector: WebDAV erfolgreich; Legacy-Verbindung wird in diesem Lauf nicht ausgefuehrt."
|
||||
exit 0
|
||||
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-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
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "NC Connector: kein erfolgreicher WebDAV-Lauf; Legacy-Fallback wird ausgefuehrt."
|
||||
legacy_result=0
|
||||
|
||||
for config in "${configs[@]}"; do
|
||||
name="$(basename "$config")"
|
||||
@@ -50,11 +194,7 @@ for config in "${configs[@]}"; do
|
||||
connection_id="${BASH_REMATCH[1]}"
|
||||
fi
|
||||
|
||||
piwigo_root="$(sed -n 's/^PIWIGO_ROOT=//p' "$config" | tail -n 1)"
|
||||
piwigo_root="${piwigo_root%\"}"
|
||||
piwigo_root="${piwigo_root#\"}"
|
||||
piwigo_root="${piwigo_root%\'}"
|
||||
piwigo_root="${piwigo_root#\'}"
|
||||
piwigo_root="$(read_config_value PIWIGO_ROOT "$config")"
|
||||
[[ -n "$piwigo_root" ]] || piwigo_root="/var/www/piwigo"
|
||||
tombstone_dir="${piwigo_root%/}/_data/bratonien-tools/nc-connector-status"
|
||||
|
||||
@@ -69,10 +209,33 @@ for config in "${configs[@]}"; do
|
||||
continue
|
||||
fi
|
||||
|
||||
echo "NC Connector lokal: $name"
|
||||
echo "NC Connector Legacy-Fallback: $name"
|
||||
if ! env PIWIGO_CONFIG="$config" bash "$SCRIPT_DIR/sync.sh"; then
|
||||
result=1
|
||||
legacy_result=1
|
||||
fi
|
||||
done
|
||||
|
||||
exit "$result"
|
||||
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-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-Fehler: $webdav_failure_detail Legacy-Fallback ist ebenfalls fehlgeschlagen." \
|
||||
"1" \
|
||||
"0"
|
||||
|
||||
if [[ "$webdav_failed" -eq 1 ]]; then
|
||||
echo "NC Connector: WebDAV und Legacy-Fallback sind fehlgeschlagen." >&2
|
||||
fi
|
||||
exit 1
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -58,7 +58,7 @@ if (!empty($_GET['preview']))
|
||||
{
|
||||
$mtime = @filemtime($preview) ?: time();
|
||||
$etag = sha1($preview.'|'.$mtime.'|'.(@filesize($preview) ?: 0));
|
||||
header('Content-Type: image/webp');
|
||||
header('Content-Type: '.bratonien_tools_webdav_preview_content_type($preview));
|
||||
header('Content-Length: '.(string)filesize($preview));
|
||||
header('ETag: "'.$etag.'"');
|
||||
header('Cache-Control: private, max-age=86400, must-revalidate');
|
||||
@@ -69,7 +69,7 @@ if (!empty($_GET['preview']))
|
||||
http_response_code(304);
|
||||
exit;
|
||||
}
|
||||
if ($_SERVER['REQUEST_METHOD'] !== 'HEAD') readfile($preview);
|
||||
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'HEAD') readfile($preview);
|
||||
exit;
|
||||
}
|
||||
}
|
||||
@@ -120,7 +120,7 @@ $options = array(
|
||||
CURLOPT_USERPWD => $user.':'.$password,
|
||||
CURLOPT_RETURNTRANSFER => false,
|
||||
CURLOPT_FAILONERROR => false,
|
||||
CURLOPT_USERAGENT => 'Bratonien-Tools-WebDAV-Image/0.9.5.19',
|
||||
CURLOPT_USERAGENT => 'Bratonien-Tools-WebDAV-Image/0.9.6.1',
|
||||
CURLOPT_HEADERFUNCTION => function($ch, $line)
|
||||
{
|
||||
$length = strlen($line);
|
||||
@@ -152,7 +152,7 @@ if (!empty($_SERVER['HTTP_RANGE']))
|
||||
$range = trim((string)$_SERVER['HTTP_RANGE']);
|
||||
if (preg_match('/^bytes=(.+)$/i', $range, $m)) $options[CURLOPT_RANGE] = $m[1];
|
||||
}
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'HEAD')
|
||||
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'HEAD')
|
||||
{
|
||||
$options[CURLOPT_NOBODY] = true;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user