mirror of
https://github.com/Terranom674/Piwigo_Bratonien_Tools.git
synced 2026-09-19 19:54:31 +00:00
Compare commits
109 Commits
1bb2088d06
...
fix/connec
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ecde2c7edd | ||
|
|
d7ef7efe43 | ||
|
|
a8ec0859da | ||
|
|
528a23b4dd | ||
|
|
fea3332ff0 | ||
|
|
039fb5160c | ||
|
|
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 | ||
|
|
bf03fea647 | ||
|
|
b3aef2744f | ||
|
|
bcf98c63ef | ||
|
|
fa3ce09589 | ||
|
|
fde03e66f9 | ||
|
|
b780636791 | ||
|
|
8785a1ccc5 | ||
|
|
554778601f | ||
|
|
c1665e53ad | ||
|
|
047045ad23 | ||
|
|
0355f4a555 | ||
|
|
a71c07cbce | ||
|
|
69213adabf | ||
|
|
272930ead5 | ||
|
|
5a115e3b4a | ||
|
|
6791b65e50 | ||
|
|
2238845579 | ||
|
|
4c862c77b3 | ||
|
|
370572c77d | ||
|
|
74911e473c | ||
|
|
65cd8898d3 | ||
|
|
e46196c143 | ||
|
|
6a71532839 | ||
|
|
3cd647ea6b | ||
|
|
639e50afb5 | ||
|
|
17f7fa8d52 | ||
|
|
af527e496b | ||
|
|
577d1ebf81 | ||
|
|
3bd3158817 | ||
|
|
c916d742f5 | ||
|
|
6f0891f6a8 | ||
|
|
b8ea6b1fe2 | ||
|
|
aeba24c6fa | ||
|
|
0d81d83d12 | ||
|
|
dbedb83c14 | ||
|
|
04620f20a2 | ||
|
|
2127649209 | ||
|
|
fd5b55ac53 | ||
|
|
933db21d88 | ||
|
|
a854bda115 | ||
|
|
08040edf8f | ||
|
|
bb024000f2 | ||
|
|
539605b19a | ||
|
|
a550bbd01a | ||
|
|
e344455e0c | ||
|
|
88edd5aee9 | ||
|
|
aa7ddefa0b | ||
|
|
ef37e3b612 | ||
|
|
eadee3cc24 | ||
|
|
d05a6f4f46 | ||
|
|
04b32309df | ||
|
|
db28692cfb | ||
|
|
5866824398 | ||
|
|
ac419ac56f | ||
|
|
65910375d2 | ||
|
|
c547c9b089 | ||
|
|
21caddcec5 | ||
|
|
237500a8fa | ||
|
|
f5dae306db | ||
|
|
20bd5105f3 | ||
|
|
82019fb14d | ||
|
|
17e4f66126 |
18
.github/workflows/lint.yml
vendored
18
.github/workflows/lint.yml
vendored
@@ -25,6 +25,24 @@ 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
|
||||
|
||||
- name: Python Syntax pruefen
|
||||
shell: bash
|
||||
run: |
|
||||
|
||||
@@ -1,122 +1,139 @@
|
||||
# Aktueller Entwicklungsstand
|
||||
|
||||
Stand: 18.08.2026
|
||||
Stand: 19.08.2026
|
||||
|
||||
## Plugin
|
||||
|
||||
- Aktuelle Plugin-Version: **0.9.4.4**
|
||||
- Aktueller Entwicklungsblock: **NC Connector – Endnutzer-Assistent und Konsolidierung**
|
||||
- `0.9.3.43` markiert den abgeschlossenen vorherigen Meilenstein.
|
||||
- `0.9.4.x` ist der neue Entwicklungsblock.
|
||||
- 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.
|
||||
- Der bestehende lokale Connector bleibt vollständig erhalten und wird nicht automatisch migriert.
|
||||
|
||||
## Produktiver Stand
|
||||
## Nicht verhandelbare Architekturregeln
|
||||
|
||||
Der lokale NC Connector ist im aktuellen Bratonien-Einsatz End-to-End funktionsfähig:
|
||||
- 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.
|
||||
|
||||
- Nextcloud-Freigaben `folder` und `file` werden verarbeitet.
|
||||
- Ordnerfreigaben werden als physische Piwigo-Alben synchronisiert.
|
||||
- Einzeldateifreigaben werden als echte Piwigo-Orphans ohne Albumzuordnung registriert.
|
||||
- Entfernte Freigaben werden aus Piwigo entfernt, Originaldateien bleiben erhalten.
|
||||
- Neue physische Connector-Alben werden privat angelegt.
|
||||
- API-first-Synchronisierung ist produktiv für Piwigo **16.4.0** freigegeben.
|
||||
- Piwigo-Album- und Fotoinformationen werden nach dem direkten Sync aktualisiert.
|
||||
- Der gemeinsame systemd-Timer verarbeitet aktive Verbindungen regelmäßig.
|
||||
## Bestehende Quellenmodi
|
||||
|
||||
## 0.9.4.1
|
||||
Weiterhin vorhanden:
|
||||
|
||||
Die Statusaktualisierung im Admin-UI wurde von Seiten-Reload auf gezielte DOM-Aktualisierung umgestellt. Der Poller aktualisiert nur noch **Letzter Lauf** und **Nächster Lauf**. Offene Dialoge, Details und der Assistent bleiben dadurch erhalten.
|
||||
- `legacy-view`
|
||||
- `user-shares`
|
||||
- `selected-fileids`
|
||||
|
||||
## 0.9.4.2
|
||||
Neuer WebDAV-Modus:
|
||||
|
||||
### Verbindungsassistent
|
||||
- `webdav-placeholder`
|
||||
|
||||
Der Assistent wurde aus Endnutzersicht konsolidiert. Technische Werte werden nur gezielt abgefragt, wenn eine automatische Prüfung sie nicht bestätigen kann.
|
||||
Es gibt keine automatische Migration bestehender Verbindungen auf WebDAV.
|
||||
|
||||
### Storage-Mappings
|
||||
## WebDAV-Ablauf in 0.9.6.1
|
||||
|
||||
Das Storage-Format erlaubt einen leeren `source_prefix`. Damit kann ein kompletter Storage direkt auf einen lokalen Mount zeigen.
|
||||
|
||||
### Native Aktivierung
|
||||
|
||||
`nc-connector-install.php` unterstützt API-only-Verbindungen ohne dauerhaft gespeicherten Login-Fallback. Ein Fallback ist nur nötig, wenn keine nutzbare API gespeichert ist.
|
||||
|
||||
## 0.9.4.3
|
||||
|
||||
- Syntaxfehler im Wizard-Abschluss korrigiert.
|
||||
- Neue Wizard-Durchläufe werden von alten serverseitigen Zuständen getrennt.
|
||||
- Abbrechen und Schließen verwerfen den laufenden Wizard-State.
|
||||
|
||||
## 0.9.4.4
|
||||
|
||||
Der Connector-Benutzer aus Schritt 1 ist zugleich der lesende Datenbank-Benutzer. Der Assistent fragt deshalb Benutzername und Passwort nicht erneut ab.
|
||||
|
||||
Ablauf:
|
||||
|
||||
1. Nextcloud-Adresse + Connector-Benutzer + Passwort.
|
||||
2. Web-Zugang und OCS werden geprüft.
|
||||
3. Derselbe Benutzer und dasselbe Passwort werden automatisch für PostgreSQL verwendet.
|
||||
4. Der Assistent prüft den üblichen Weg mit Nextcloud-Host, Port 5432 und Datenbank `nextcloud` bzw. bekannte passende Verbindungswerte.
|
||||
5. Nur wenn die Datenbank dort nicht erreichbar ist, werden Host, Port und Datenbankname abgefragt. Benutzer und Passwort bleiben unverändert aus Schritt 1.
|
||||
6. Danach folgen gegebenenfalls Storage-Zuordnung, Showcase-Benutzer, Piwigo-API und Fallback.
|
||||
|
||||
Die PHP-Datei `include/nc_connector_wizard.inc.php` wurde vor dem Versionsbump mit dem PHP-Parser geprüft.
|
||||
|
||||
## Architektur NC Connector
|
||||
|
||||
- Nextcloud ist Quelle der Originalbilder.
|
||||
- Piwigo erhält einen Shadow Tree aus Verzeichnissen und Symlinks.
|
||||
- PostgreSQL-Reader und die Views `piwigo_showcase_sources` / `piwigo_showcase_activity` liefern Quellen und Aktivität.
|
||||
- Runtime-Konfigurationen: `/etc/bratonien-tools/nc-connector/connection-*.conf`
|
||||
- State: `/var/lib/bratonien-tools/nc-connector/connection-ID`
|
||||
- Öffentlicher Admin-Status: Piwigo `_data/bratonien-tools/nc-connector-status/`
|
||||
- Runner: `runtime/run-all.sh`
|
||||
- Einzelverbindung: `runtime/sync.sh`
|
||||
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.
|
||||
|
||||
## Piwigo-Synchronisierung
|
||||
|
||||
Priorität:
|
||||
WebDAV verwendet denselben Piwigo-Synchronisationspfad wie der bestehende Connector, aber mit einer verbindungseigenen physischen Site.
|
||||
|
||||
1. gespeicherter Piwigo-API-Key;
|
||||
2. bei nicht nutzbarer API gespeicherter Benutzername/Passwort-Fallback;
|
||||
3. ohne beide Wege Abbruch mit Fehlerstatus.
|
||||
Nach der Dateisynchronisierung laufen die vorhandenen Piwigo-Nacharbeiten, darunter Metadaten-, Integritäts-, Kategorie-, Pfad-, Rang- und Cache-Aktualisierungen sowie der Orphan-Abgleich.
|
||||
|
||||
Produktive API-Methoden:
|
||||
Die direkte produktive Synchronisierung ist derzeit ausdrücklich auf **Piwigo 16.4.0** abgestimmt.
|
||||
|
||||
- `bratonien.nc.syncProductive`
|
||||
- `bratonien.nc.syncOrphans`
|
||||
## WebDAV-Bildausgabe und Derivate
|
||||
|
||||
`bratonien.nc.syncProductive` ist auf Piwigo 16.4.0 versionsgebunden. Der direkte Sync verwendet Bratonien-eigene Logik auf Basis der Piwigo-Core-Funktionen, nicht das Rendern oder Fernsteuern einer Admin-Seite.
|
||||
Wichtige Dateien:
|
||||
|
||||
## Activity Gate und Shadow Tree
|
||||
- `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.
|
||||
|
||||
Das Activity Gate berücksichtigt:
|
||||
Der Frontend-Hook führt keine Bildgenerierung mehr aus. Damit bleibt ein Fehler in GD/Imagick/External ImageMagick auf den Hintergrundlauf begrenzt.
|
||||
|
||||
- Aktivitätsstand;
|
||||
- Share-Fingerprint;
|
||||
- Quiet-Time;
|
||||
- Max-Wartezeit;
|
||||
- periodischen Full-Sync;
|
||||
- Reparaturbedarf bei beschädigter lokaler Struktur.
|
||||
## Löschen einer WebDAV-Verbindung seit 0.9.6.1
|
||||
|
||||
Der Shadow-Tree-Wechsel besitzt einen Rollback auf den vorherigen Baum, falls das Umschalten fehlschlägt.
|
||||
Eine gelöschte WebDAV-Verbindung darf keine weiterhin sichtbaren oder über alte Piwigo-Datensätze erreichbaren Bilder hinterlassen.
|
||||
|
||||
Beim Löschen über die Oberfläche:
|
||||
|
||||
- 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.
|
||||
|
||||
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.
|
||||
|
||||
## Gemeinsamer Runner
|
||||
|
||||
`runtime/run-all.sh` verarbeitet die Schritte in kontrollierter Reihenfolge:
|
||||
|
||||
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.
|
||||
|
||||
Der vorhandene systemd-Timer ruft direkt die Runtime aus dem installierten Plugin auf.
|
||||
|
||||
## Status- und UI-Regeln
|
||||
|
||||
- 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.
|
||||
|
||||
## Sicherheit
|
||||
|
||||
- Nextcloud-Originale werden nicht gelöscht.
|
||||
- Connector-Zugangsdaten werden verschlüsselt gespeichert.
|
||||
- Wizard-Secrets bleiben serverseitig.
|
||||
- Storage-Pfade werden validiert.
|
||||
- SQL-View-Namen werden validiert.
|
||||
- Piwigo-API ist versionsgebunden.
|
||||
- Mutierende Admin-Aktionen verwenden Post/Redirect/Get, sodass Browser-Reloads sie nicht erneut ausführen.
|
||||
- Self-Updates sind an einen konkreten Commit und SHA-256 gebunden.
|
||||
- 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.
|
||||
|
||||
## Noch offen
|
||||
## Aktueller Prüfstand
|
||||
|
||||
- vollständiger Remote-Nextcloud-Adapter ohne direkten PostgreSQL-/Storage-Zugriff;
|
||||
- weitere Bereinigung alter Legacy-Migrationshelfer, sobald sie nicht mehr benötigt werden;
|
||||
- weitere Endnutzer-Optimierung des Assistenten auf Basis realer Fehler- und Installationspfade.
|
||||
Bereits umgesetzt:
|
||||
|
||||
## Repository-Fallback
|
||||
- WebDAV-Verbindungsassistent;
|
||||
- Verzeichnisauswahl;
|
||||
- rekursiver WebDAV-Scan;
|
||||
- Shadow Tree;
|
||||
- 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.
|
||||
|
||||
GitHub bleibt das führende Repository. Das private Gitea-System dient weiterhin als Mirror/Fallback.
|
||||
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.
|
||||
|
||||
214
README.md
214
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.4.4**
|
||||
Aktuelle Plugin-Version: **0.9.6.1**
|
||||
|
||||
## Grundprinzip
|
||||
|
||||
@@ -12,113 +12,131 @@ Für die Administration gilt: Der normale Nutzer sieht Aufgaben, Entscheidungen
|
||||
|
||||
## NC Connector
|
||||
|
||||
Der NC Connector synchronisiert ausdrücklich freigegebene Nextcloud-Inhalte mit Piwigo.
|
||||
Der NC Connector synchronisiert ausdrücklich ausgewählte Nextcloud-Inhalte mit Piwigo.
|
||||
|
||||
### 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 mit Symlinks.
|
||||
- Ordnerfreigaben werden als physische Piwigo-Alben synchronisiert.
|
||||
- Einzeldateifreigaben werden im Galerie-Root verlinkt und als echte Piwigo-Orphans ohne Albumzuordnung registriert.
|
||||
- Entfernte Freigaben werden aus Shadow Tree und Piwigo entfernt, das Nextcloud-Original bleibt erhalten.
|
||||
- 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 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.
|
||||
|
||||
### Verbindungsassistent
|
||||
### Bestehende lokale Quellenmodi
|
||||
|
||||
Neue Verbindungen werden bevorzugt mit einem Endnutzer-Assistenten angelegt.
|
||||
Der bestehende Connector unterstützt weiterhin:
|
||||
|
||||
Ablauf:
|
||||
- `legacy-view`
|
||||
- `user-shares`
|
||||
- `selected-fileids`
|
||||
|
||||
1. Nextcloud-Adresse, Benutzer und Passwort eingeben.
|
||||
2. Der Assistent prüft HTTP/HTTPS, Nextcloud-Status und Anmeldung.
|
||||
3. Derselbe in Schritt 1 angegebene Connector-Benutzer und dasselbe Passwort werden auch für den lesenden PostgreSQL-Zugriff verwendet; es gibt im normalen Ablauf keine zweite Benutzer-/Passwortabfrage.
|
||||
4. Vorhandene passende Connector-Werte für Host, Port, Datenbank und Storage-Zuordnungen werden wiederverwendet, aber erneut mit dem aktuellen Zugang geprüft.
|
||||
5. Nur wenn der übliche PostgreSQL-Weg nicht erreichbar ist, werden abweichende Datenbank-Adresse, Port und Datenbankname gezielt abgefragt. Benutzer und Passwort bleiben dabei die Angaben aus Schritt 1.
|
||||
6. Nicht automatisch zuordenbare Storage-Mounts werden einzeln bestätigt.
|
||||
7. Danach wird der Nextcloud-Benutzer gewählt, dessen Freigaben verwendet werden sollen. Empfohlen wird ein eigener `showcase`-Benutzer.
|
||||
8. Piwigo-API-Zugang testen oder bewusst überspringen.
|
||||
9. Optionaler bzw. bei übersprungener API verpflichtender Login-Fallback.
|
||||
10. Erst der Abschluss legt die Verbindung dauerhaft an.
|
||||
Diese Modi bleiben erhalten. Es gibt keine automatische Migration auf WebDAV.
|
||||
|
||||
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.
|
||||
### WebDAV-Modus
|
||||
|
||||
Die vollständige technische Maske bleibt weiterhin über **Ohne Assistent anlegen** sowie bei bestehenden Verbindungen unter **Technische Einstellungen** erreichbar.
|
||||
Der neue Endnutzerpfad verwendet `source_mode=webdav-placeholder` und `adapter=remote`.
|
||||
|
||||
### Lokaler Adapter
|
||||
Benötigt werden nur:
|
||||
|
||||
Der derzeit produktive Adapter verwendet:
|
||||
- Nextcloud-Adresse;
|
||||
- Nextcloud-Benutzer bzw. App-Passwort;
|
||||
- normaler WebDAV-Zugriff auf die Inhalte dieses Benutzers;
|
||||
- eine normale Piwigo-Installation mit ihrer vorhandenen PHP-/Bildverarbeitungsumgebung.
|
||||
|
||||
- PostgreSQL-Reader mit minimalen Leserechten;
|
||||
- Source-View `piwigo_showcase_sources`;
|
||||
- Activity-View `piwigo_showcase_activity`;
|
||||
- explizite Storage-Zuordnungen auf bereits vorhandene lokale Mounts;
|
||||
- Plugin-eigene Runtime und getrennten State pro Verbindung.
|
||||
Nicht vorausgesetzt werden:
|
||||
|
||||
Ein Storage-Mapping besteht aus `storage_id`, einem optionalen `source_prefix` und dem lokalen Mount. Ein leerer Prefix ist zulässig und bedeutet, dass der Mount direkt dem Storage-Root entspricht.
|
||||
- PostgreSQL-Zugriff auf Nextcloud;
|
||||
- `occ`-Adminzugriff;
|
||||
- Storage-IDs oder Backend-Pfade;
|
||||
- zusätzliche Host-Mounts;
|
||||
- FUSE;
|
||||
- davfs;
|
||||
- rclone.
|
||||
|
||||
### Activity Gate
|
||||
### WebDAV-Ablauf
|
||||
|
||||
Der regelmäßige Lauf berücksichtigt:
|
||||
|
||||
- Nextcloud-Aktivität;
|
||||
- Signatur der sichtbaren Freigaben;
|
||||
- Quiet-Time;
|
||||
- maximale Wartezeit;
|
||||
- periodischen Full-Sync;
|
||||
- notwendigen Reparaturlauf bei beschädigtem Shadow Tree oder fehlenden Piwigo-Alben.
|
||||
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 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:
|
||||
|
||||
### 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.
|
||||
|
||||
Das Löschen einer Connector-Verbindung entfernt keine Nextcloud-Originale und keine Piwigo-Bilder. Erreichbare Connector-eigene Status-/State-Daten der Verbindung werden bereinigt.
|
||||
|
||||
### Legacy-Migration
|
||||
|
||||
Für ältere Installationen mit dem früheren separaten `piwigo-sync` existieren weiterhin Migrations-/Cutover-Helfer. Neue Installationen sollen den nativen Connector-Weg verwenden.
|
||||
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
|
||||
|
||||
@@ -128,7 +146,7 @@ Für ältere Installationen mit dem früheren separaten `piwigo-sync` existieren
|
||||
- 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
|
||||
|
||||
@@ -171,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_create_api.inc.php` – API-first-Verbindungserstellung
|
||||
- `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` – Auflösung der Nextcloud-Freigaben auf Storage-Mounts
|
||||
- `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
|
||||
- `runtime/sync.sh` – Ablauf einer Verbindung
|
||||
- `nc-connector-install.php` – native Root-Aktivierung
|
||||
- `nc-connector-disable.php` – Deaktivierung
|
||||
- `nc-connector-normalize.php` – Normalisierung älterer aktiver Verbindungen
|
||||
- `nc-connector-*-cleanup/switch/cutover` – Legacy-Migrationshelfer
|
||||
- `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
|
||||
@@ -214,15 +229,18 @@ Wichtige Dateien und Verzeichnisse:
|
||||
|
||||
- administrative Schreibaktionen verwenden Piwigos CSRF-Schutz;
|
||||
- Connector-Zugangsdaten werden verschlüsselt gespeichert;
|
||||
- Wizard-Geheimnisse werden nicht in Browser-Web-Storage persistiert;
|
||||
- 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;
|
||||
- gefährliche technische Pfade sind nicht Teil des normalen Wizard-Happy-Paths;
|
||||
- produktive Piwigo-API ist versionsgebunden;
|
||||
- Originalbilder werden vom Connector nicht gelöscht;
|
||||
- Update-Pakete werden an Commit und Hash gebunden;
|
||||
- Root-Helfer prüfen CLI-/Root-Ausführung, bevor sie Systemdienste oder `/etc`-/`/var/lib`-Daten verändern.
|
||||
- WebDAV-Originalbilder werden nicht dauerhaft lokal gespeichert;
|
||||
- Update-Pakete werden an Commit und Hash gebunden.
|
||||
|
||||
## Entwicklungsstand
|
||||
|
||||
`0.9.4.x` ist der aktuelle Entwicklungsblock. Der lokale NC Connector ist End-to-End produktiv im Einsatz. Der Verbindungsassistent und die Verwaltung werden weiter aus Endnutzersicht konsolidiert. Ein vollständig entfernter Nextcloud-Adapter ohne direkten PostgreSQL-/Storage-Zugriff ist noch nicht umgesetzt.
|
||||
`0.9.6.x` ist die aktuelle Versionslinie.
|
||||
|
||||
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.
|
||||
|
||||
Der jeweils detaillierte Prüf- und Entwicklungsstand steht in [`CURRENT_STATUS.md`](CURRENT_STATUS.md).
|
||||
|
||||
@@ -43,6 +43,8 @@ function bratonien_tools_nc_wizard_finish_connection_scoped()
|
||||
$_POST['nc_nextcloud_url']=(string)$state['base_url'];
|
||||
$_POST['nc_showcase_user']=(string)$state['showcase_user'];
|
||||
$_POST['nc_access_user']=(string)$state['username'];
|
||||
$_POST['nc_nextcloud_user']=(string)$state['username'];
|
||||
$_POST['nc_nextcloud_password']=(string)$state['_password'];
|
||||
$_POST['nc_product']=(string)$state['product'];
|
||||
$_POST['nc_version']=(string)$state['version'];
|
||||
$_POST['nc_api_validated']=$state['api_status']==='ok'?'1':'0';
|
||||
@@ -121,12 +123,14 @@ function bratonien_tools_nc_connector_verify_connection_scoped()
|
||||
}
|
||||
|
||||
$payload = json_encode(array(
|
||||
'v'=>2,
|
||||
'v'=>3,
|
||||
'db_password'=>$db_password,
|
||||
'piwigo_user'=>$fallback_user,
|
||||
'piwigo_password'=>$fallback_password,
|
||||
'api_key_id'=>$api_key_id,
|
||||
'api_key_secret'=>$api_key_secret,
|
||||
'nextcloud_user'=>'',
|
||||
'nextcloud_password'=>'',
|
||||
), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
||||
if (!is_string($payload)) throw new RuntimeException('Verbindungsauthentifizierung konnte nicht migriert werden.');
|
||||
|
||||
@@ -148,33 +152,44 @@ function bratonien_tools_nc_connector_scoped_secret(array $connection)
|
||||
if (is_array($decoded) && array_key_exists('db_password', $decoded))
|
||||
{
|
||||
return array(
|
||||
'v'=>2,
|
||||
'v'=>3,
|
||||
'db_password'=>(string)($decoded['db_password'] ?? ''),
|
||||
'piwigo_user'=>(string)($decoded['piwigo_user'] ?? ''),
|
||||
'piwigo_password'=>(string)($decoded['piwigo_password'] ?? ''),
|
||||
'api_key_id'=>(string)($decoded['api_key_id'] ?? ''),
|
||||
'api_key_secret'=>(string)($decoded['api_key_secret'] ?? ''),
|
||||
'nextcloud_user'=>(string)($decoded['nextcloud_user'] ?? ''),
|
||||
'nextcloud_password'=>(string)($decoded['nextcloud_password'] ?? ''),
|
||||
);
|
||||
}
|
||||
|
||||
return array(
|
||||
'v'=>2,
|
||||
'v'=>3,
|
||||
'db_password'=>(string)$plain,
|
||||
'piwigo_user'=>'',
|
||||
'piwigo_password'=>'',
|
||||
'api_key_id'=>'',
|
||||
'api_key_secret'=>'',
|
||||
'nextcloud_user'=>'',
|
||||
'nextcloud_password'=>'',
|
||||
);
|
||||
}
|
||||
|
||||
function bratonien_tools_nc_connector_store_scoped_secret($id, array $connection, array $credentials)
|
||||
{
|
||||
if (trim((string)($credentials['db_password'] ?? '')) === '') throw new RuntimeException('Das Datenbankpasswort der Verbindung fehlt.');
|
||||
$config = is_array($connection['config'] ?? null) ? $connection['config'] : array();
|
||||
$is_webdav = (string)($config['source_mode'] ?? '') === 'webdav-placeholder';
|
||||
if (!$is_webdav && trim((string)($credentials['db_password'] ?? '')) === '') throw new RuntimeException('Das Datenbankpasswort der Verbindung fehlt.');
|
||||
if ($is_webdav && (trim((string)($credentials['nextcloud_user'] ?? '')) === '' || (string)($credentials['nextcloud_password'] ?? '') === ''))
|
||||
{
|
||||
throw new RuntimeException('Die Nextcloud-Zugangsdaten der WebDAV-Verbindung fehlen.');
|
||||
}
|
||||
|
||||
$credentials['v'] = 3;
|
||||
$payload = json_encode($credentials, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
||||
if (!is_string($payload)) throw new RuntimeException('Verbindungszugangsdaten konnten nicht serialisiert werden.');
|
||||
$blob = bratonien_tools_nc_connector_encrypt_secret($payload);
|
||||
|
||||
$config = is_array($connection['config'] ?? null) ? $connection['config'] : array();
|
||||
if (array_key_exists('api_enabled', $config))
|
||||
{
|
||||
$config['api_enabled'] = trim((string)($credentials['api_key_id'] ?? '')) !== '' && trim((string)($credentials['api_key_secret'] ?? '')) !== '';
|
||||
|
||||
@@ -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',
|
||||
@@ -28,6 +33,13 @@ function bratonien_tools_nc_connector_create_local_api_first()
|
||||
throw new RuntimeException('Fallback-Benutzer und Fallback-Passwort muessen entweder beide angegeben oder beide leer gelassen werden.');
|
||||
}
|
||||
|
||||
$nextcloud_user = trim((string)($_POST['nc_nextcloud_user'] ?? $_POST['nc_access_user'] ?? ''));
|
||||
$nextcloud_password = (string)($_POST['nc_nextcloud_password'] ?? '');
|
||||
if (($nextcloud_user === '') !== ($nextcloud_password === ''))
|
||||
{
|
||||
throw new RuntimeException('Nextcloud-Benutzer und Nextcloud-Passwort muessen entweder beide vorhanden oder beide leer sein.');
|
||||
}
|
||||
|
||||
$wizard_auth_present = array_key_exists('nc_api_validated', $_POST);
|
||||
$validated_pending_api = (string)($_POST['nc_api_validated'] ?? '') === '1';
|
||||
$api_key_id = trim((string)($_POST['nc_connection_api_key_id'] ?? ''));
|
||||
@@ -84,12 +96,14 @@ function bratonien_tools_nc_connector_create_local_api_first()
|
||||
bratonien_tools_nc_connector_view_name($config['activity_view']);
|
||||
|
||||
$secret_payload = json_encode(array(
|
||||
'v'=>2,
|
||||
'v'=>3,
|
||||
'db_password'=>(string)$_POST['nc_db_password'],
|
||||
'piwigo_user'=>$fallback_user,
|
||||
'piwigo_password'=>$fallback_password,
|
||||
'api_key_id'=>$api_key_id,
|
||||
'api_key_secret'=>$api_key_secret,
|
||||
'nextcloud_user'=>$nextcloud_user,
|
||||
'nextcloud_password'=>$nextcloud_password,
|
||||
), 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);
|
||||
|
||||
135
include/nc_connector_delete_safe.inc.php
Normal file
135
include/nc_connector_delete_safe.inc.php
Normal file
@@ -0,0 +1,135 @@
|
||||
<?php
|
||||
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.
|
||||
* 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()
|
||||
{
|
||||
$id = (int)($_POST['connection_id'] ?? 0);
|
||||
$connection = bratonien_tools_nc_connector_connection($id, false);
|
||||
if (!$connection)
|
||||
{
|
||||
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");
|
||||
|
||||
$status_dir = rtrim(PHPWG_ROOT_PATH, '/').'/_data/bratonien-tools/nc-connector-status';
|
||||
$public_status = $status_dir.'/connection-'.$id.'.json';
|
||||
if (is_file($public_status))
|
||||
{
|
||||
@unlink($public_status);
|
||||
}
|
||||
|
||||
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. Quelldateien blieben unverändert.',
|
||||
);
|
||||
}
|
||||
195
include/nc_connector_edit.inc.php
Normal file
195
include/nc_connector_edit.inc.php
Normal file
@@ -0,0 +1,195 @@
|
||||
<?php
|
||||
if (!defined('PHPWG_ROOT_PATH'))
|
||||
{
|
||||
die('Hacking attempt!');
|
||||
}
|
||||
|
||||
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 geöffnet.');
|
||||
}
|
||||
|
||||
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.');
|
||||
}
|
||||
|
||||
bratonien_tools_nc_connector_prepare_webdav_wizard_from_connection($connection, 'migrate');
|
||||
return array('message'=>'Die WebDAV-Migration für Verbindung #'.$id.' wurde geöffnet. Die bestehende Legacy-Verbindung bleibt bis zum erfolgreichen Umstieg unverändert.');
|
||||
}
|
||||
|
||||
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 für Legacy-Verbindungen vorgesehen.');
|
||||
|
||||
$name = trim((string)($_POST['connection_name'] ?? ''));
|
||||
if ($name === '') throw new RuntimeException('Bitte einen Namen für 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 ungültig.');
|
||||
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 dürfen 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 gültiger 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.');
|
||||
|
||||
$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;
|
||||
unset($config['verification']);
|
||||
|
||||
$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('Für die Legacy-Verbindung ist kein Datenbankpasswort gespeichert.');
|
||||
|
||||
$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");
|
||||
|
||||
return array('message'=>'Verbindung #'.$id.' wurde gespeichert. Die neuen Werte gelten ab dem nächsten Connector-Lauf.');
|
||||
}
|
||||
@@ -54,6 +54,8 @@ function bratonien_tools_nc_wizard_finish_generic_scope()
|
||||
$_POST['nc_piwigo_password']=$fallback_password;
|
||||
$_POST['nc_nextcloud_url']=(string)$state['base_url'];
|
||||
$_POST['nc_access_user']=(string)$state['username'];
|
||||
$_POST['nc_nextcloud_user']=(string)$state['username'];
|
||||
$_POST['nc_nextcloud_password']=(string)$state['_password'];
|
||||
$_POST['nc_product']=(string)$state['product'];
|
||||
$_POST['nc_version']=(string)$state['version'];
|
||||
$_POST['nc_api_validated']=($state['api_status'] ?? '')==='ok'?'1':'0';
|
||||
|
||||
@@ -179,6 +179,76 @@ function bratonien_tools_nc_connector_piwigo_api_request($api_key_id, $api_key_s
|
||||
return bratonien_tools_nc_connector_api_payload($decoded);
|
||||
}
|
||||
|
||||
function bratonien_tools_nc_connector_validate_fallback_credentials($username, $password)
|
||||
{
|
||||
if (!function_exists('curl_init'))
|
||||
{
|
||||
throw new RuntimeException('cURL ist in PHP nicht verfuegbar. Der Piwigo-Fallback kann nicht geprueft werden.');
|
||||
}
|
||||
|
||||
$username = trim((string)$username);
|
||||
$password = (string)$password;
|
||||
if ($username === '' || $password === '')
|
||||
{
|
||||
throw new RuntimeException('Piwigo-Benutzername und Passwort muessen angegeben werden.');
|
||||
}
|
||||
|
||||
$cookie_file = tempnam(sys_get_temp_dir(), 'br-pwg-auth-');
|
||||
if ($cookie_file === false)
|
||||
{
|
||||
throw new RuntimeException('Temporare Piwigo-Sitzung konnte nicht angelegt werden.');
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
$url = rtrim(get_absolute_root_url(true), '/').'/ws.php?format=json';
|
||||
$request = function(array $fields) use ($url, $cookie_file)
|
||||
{
|
||||
$ch = curl_init($url);
|
||||
curl_setopt_array($ch, array(
|
||||
CURLOPT_RETURNTRANSFER=>true,
|
||||
CURLOPT_POST=>true,
|
||||
CURLOPT_POSTFIELDS=>http_build_query($fields),
|
||||
CURLOPT_COOKIEJAR=>$cookie_file,
|
||||
CURLOPT_COOKIEFILE=>$cookie_file,
|
||||
CURLOPT_CONNECTTIMEOUT=>10,
|
||||
CURLOPT_TIMEOUT=>20,
|
||||
CURLOPT_FOLLOWLOCATION=>false,
|
||||
CURLOPT_USERAGENT=>'Bratonien-Tools-NC-Connector/'.(function_exists('bratonien_tools_current_version') ? bratonien_tools_current_version() : 'dev'),
|
||||
));
|
||||
$body = curl_exec($ch);
|
||||
$errno = curl_errno($ch);
|
||||
$error = curl_error($ch);
|
||||
$http = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
$type = (string)curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
|
||||
curl_close($ch);
|
||||
if ($body === false || $errno !== 0) throw new RuntimeException('Piwigo-Fallback konnte nicht geprueft werden: '.$error);
|
||||
if ($http < 200 || $http >= 300) throw new RuntimeException('Piwigo-Fallback-Pruefung antwortete mit HTTP '.$http.'.');
|
||||
$decoded = bratonien_tools_nc_connector_decode_api_response((string)$body, $type);
|
||||
if (($decoded['stat'] ?? '') !== 'ok')
|
||||
{
|
||||
$message = trim((string)($decoded['message'] ?? $decoded['err'] ?? 'Piwigo hat die Anmeldung abgelehnt.'));
|
||||
throw new RuntimeException($message !== '' ? $message : 'Piwigo hat die Anmeldung abgelehnt.');
|
||||
}
|
||||
return bratonien_tools_nc_connector_api_payload($decoded);
|
||||
};
|
||||
|
||||
$request(array('method'=>'pwg.session.login', 'username'=>$username, 'password'=>$password));
|
||||
$status = $request(array('method'=>'pwg.session.getStatus'));
|
||||
if (!is_array($status)) throw new RuntimeException('Piwigo hat keinen auswertbaren Benutzerstatus geliefert.');
|
||||
$role = strtolower(trim((string)($status['status'] ?? '')));
|
||||
if (!in_array($role, array('admin','webmaster'), true))
|
||||
{
|
||||
throw new RuntimeException('Der Piwigo-Fallback funktioniert, gehoert aber keinem Administrator/Webmaster.');
|
||||
}
|
||||
return array('username'=>(string)($status['username'] ?? $username), 'status'=>$role);
|
||||
}
|
||||
finally
|
||||
{
|
||||
@unlink($cookie_file);
|
||||
}
|
||||
}
|
||||
|
||||
function bratonien_tools_nc_connector_piwigo_api_test()
|
||||
{
|
||||
$api_key_id = trim((string)($_POST['nc_piwigo_api_key_id'] ?? ''));
|
||||
|
||||
261
include/nc_connector_webdav.inc.php
Normal file
261
include/nc_connector_webdav.inc.php
Normal file
@@ -0,0 +1,261 @@
|
||||
<?php
|
||||
if (!defined('PHPWG_ROOT_PATH'))
|
||||
{
|
||||
die('Hacking attempt!');
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*
|
||||
* 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()
|
||||
{
|
||||
$state = bratonien_tools_nc_wizard_state();
|
||||
|
||||
if (empty($state['scan_ok']) || empty($state['technical_complete']))
|
||||
{
|
||||
throw new RuntimeException('Die WebDAV-Verbindung wurde im Assistenten noch nicht vollständig vorbereitet.');
|
||||
}
|
||||
|
||||
$base_url = rtrim(trim((string)($state['base_url'] ?? '')), '/');
|
||||
$username = trim((string)($state['username'] ?? ''));
|
||||
$password = (string)($state['_password'] ?? '');
|
||||
if ($base_url === '' || $username === '' || $password === '')
|
||||
{
|
||||
throw new RuntimeException('Für den WebDAV-Zugang fehlen Nextcloud-Adresse oder Zugangsdaten.');
|
||||
}
|
||||
|
||||
$selected = isset($state['directory_selected']) && is_array($state['directory_selected'])
|
||||
? array_values(array_unique(array_map(function($path) { return trim((string)$path, '/'); }, $state['directory_selected'])))
|
||||
: array();
|
||||
$selected_ids = isset($state['directory_selected_fileids']) && is_array($state['directory_selected_fileids'])
|
||||
? $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 auswählen.');
|
||||
|
||||
$roots = array();
|
||||
foreach ($selected as $path)
|
||||
{
|
||||
$fileid = isset($selected_ids[$path]) ? (int)$selected_ids[$path] : 0;
|
||||
if ($fileid < 1) throw new RuntimeException('Für ein ausgewähltes Nextcloud-Verzeichnis fehlt die eindeutige Datei-ID.');
|
||||
$roots[] = array(
|
||||
'fileid'=>$fileid,
|
||||
'display_name'=>basename($path),
|
||||
'webdav_path'=>$path,
|
||||
);
|
||||
}
|
||||
|
||||
$name = trim((string)($state['connection_name'] ?? ''));
|
||||
if ($name === '') $name = 'Nextcloud WebDAV';
|
||||
$gallery_root = rtrim(trim((string)($state['gallery_root'] ?? '')), '/');
|
||||
if ($gallery_root === '') $gallery_root = rtrim(PHPWG_ROOT_PATH, '/').'/galleries';
|
||||
|
||||
$api_key_id = ($state['api_status'] ?? '') === 'ok' ? trim((string)($state['_api_key_id'] ?? '')) : '';
|
||||
$api_key_secret = ($state['api_status'] ?? '') === 'ok' ? trim((string)($state['_api_key_secret'] ?? '')) : '';
|
||||
$fallback_user = trim((string)($state['_fallback_user'] ?? ''));
|
||||
$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',
|
||||
'transport'=>'webdav',
|
||||
'nextcloud_url'=>$base_url,
|
||||
'access_user'=>$username,
|
||||
'nextcloud_access_user'=>$username,
|
||||
'gallery_root'=>$gallery_root,
|
||||
'roots'=>$roots,
|
||||
'state_dir'=>'',
|
||||
'status_file'=>'',
|
||||
'quiet_seconds'=>120,
|
||||
'max_wait_seconds'=>900,
|
||||
'full_sync_seconds'=>86400,
|
||||
'parallel_test'=>true,
|
||||
'piwigo_auth'=>'connection-scoped',
|
||||
'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] ?? ''));
|
||||
if ($value !== '') $config[$config_key] = $value;
|
||||
}
|
||||
|
||||
$secret_payload = json_encode(array(
|
||||
'v'=>3,
|
||||
'db_password'=>'',
|
||||
'piwigo_user'=>$fallback_user,
|
||||
'piwigo_password'=>$fallback_password,
|
||||
'api_key_id'=>$api_key_id,
|
||||
'api_key_secret'=>$api_key_secret,
|
||||
'nextcloud_user'=>$username,
|
||||
'nextcloud_password'=>$password,
|
||||
), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
||||
if (!is_string($secret_payload)) throw new RuntimeException('WebDAV-Zugangsdaten konnten nicht serialisiert werden.');
|
||||
|
||||
bratonien_tools_nc_connector_ensure_table();
|
||||
$table = bratonien_tools_nc_connector_table();
|
||||
$now = date('Y-m-d H:i:s');
|
||||
$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','"
|
||||
.pwg_db_real_escape_string($config_json)."','"
|
||||
.pwg_db_real_escape_string($secret_blob)."','"
|
||||
.pwg_db_real_escape_string($now)."','"
|
||||
.pwg_db_real_escape_string($now)."')");
|
||||
|
||||
$id = (int)pwg_db_insert_id();
|
||||
if ($id < 1) throw new RuntimeException('Die WebDAV-Verbindung konnte nicht eindeutig angelegt werden.');
|
||||
|
||||
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 $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.',
|
||||
);
|
||||
}
|
||||
|
||||
return array(
|
||||
'connection_id'=>$id,
|
||||
'message'=>'WebDAV-Verbindung wurde angelegt.',
|
||||
);
|
||||
}
|
||||
207
include/nc_connector_wizard_webdav_flow.inc.php
Normal file
207
include/nc_connector_wizard_webdav_flow.inc.php
Normal file
@@ -0,0 +1,207 @@
|
||||
<?php
|
||||
if (!defined('PHPWG_ROOT_PATH'))
|
||||
{
|
||||
die('Hacking attempt!');
|
||||
}
|
||||
|
||||
function bratonien_tools_nc_wizard_scan_webdav_first()
|
||||
{
|
||||
$state = bratonien_tools_nc_wizard_state();
|
||||
$host_input = trim((string)($_POST['nc_wizard_host'] ?? $state['host_input']));
|
||||
$username = trim((string)($_POST['nc_wizard_user'] ?? $state['username']));
|
||||
$password = array_key_exists('nc_wizard_password', $_POST) ? (string)$_POST['nc_wizard_password'] : (string)$state['_password'];
|
||||
|
||||
$state['step'] = 1;
|
||||
$state['host_input'] = $host_input;
|
||||
$state['username'] = $username;
|
||||
$state['_password'] = $password;
|
||||
bratonien_tools_nc_wizard_store($state);
|
||||
|
||||
if ($username === '' || $password === '')
|
||||
{
|
||||
throw new RuntimeException('Nextcloud-Benutzer und Passwort werden für den Scan benötigt.');
|
||||
}
|
||||
|
||||
$base_url = '';
|
||||
$status_data = null;
|
||||
foreach (bratonien_tools_nc_wizard_candidate_urls($host_input) as $candidate_url)
|
||||
{
|
||||
try
|
||||
{
|
||||
$response = bratonien_tools_nc_wizard_http($candidate_url.'/status.php');
|
||||
if ($response['status'] < 200 || $response['status'] >= 300) continue;
|
||||
$candidate_status = json_decode($response['body'], true);
|
||||
if (!is_array($candidate_status) || empty($candidate_status['installed'])) continue;
|
||||
$base_url = $candidate_url;
|
||||
$status_data = $candidate_status;
|
||||
break;
|
||||
}
|
||||
catch (Throwable $ignored) {}
|
||||
}
|
||||
|
||||
if ($base_url === '' || !is_array($status_data))
|
||||
{
|
||||
throw new RuntimeException('Unter dieser Adresse konnte keine Nextcloud erreicht werden. HTTP und HTTPS wurden automatisch geprüft.');
|
||||
}
|
||||
|
||||
$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 die Anmeldung konnte nicht geprüft werden.');
|
||||
}
|
||||
|
||||
$user_data = bratonien_tools_nc_wizard_ocs_data($user_response['body']);
|
||||
$resolved_username = trim((string)($user_data['id'] ?? $username));
|
||||
if ($resolved_username === '') $resolved_username = $username;
|
||||
$url_host = (string)parse_url($base_url, PHP_URL_HOST);
|
||||
|
||||
$state = array_merge($state, array(
|
||||
'step'=>2,
|
||||
'scan_ok'=>true,
|
||||
'base_url'=>$base_url,
|
||||
'host_input'=>$host_input,
|
||||
'username'=>$resolved_username,
|
||||
'display_name'=>(string)($user_data['display-name'] ?? $user_data['displayname'] ?? ''),
|
||||
'version'=>(string)($status_data['versionstring'] ?? $status_data['version'] ?? ''),
|
||||
'product'=>(string)($status_data['productname'] ?? 'Nextcloud'),
|
||||
'users'=>array(),
|
||||
'can_list_users'=>false,
|
||||
'showcase_user'=>$resolved_username,
|
||||
'connection_name'=>$url_host !== '' ? $url_host : 'Nextcloud WebDAV',
|
||||
'scan_message'=>'Nextcloud und WebDAV-Zugriff wurden bestätigt.',
|
||||
'_password'=>$password,
|
||||
'source_mode'=>'webdav-placeholder',
|
||||
'transport'=>'webdav',
|
||||
'gallery_root'=>rtrim(PHPWG_ROOT_PATH, '/').'/galleries',
|
||||
'storages'=>array(),
|
||||
'storage_candidates'=>array(),
|
||||
'roots'=>array(),
|
||||
'technical_stage'=>'mounts',
|
||||
'technical_source'=>'WebDAV',
|
||||
'technical_error'=>'',
|
||||
'technical_complete'=>false,
|
||||
'directory_selection_ready'=>true,
|
||||
'directory_path'=>'',
|
||||
'directory_parent'=>'',
|
||||
'directory_children'=>array(),
|
||||
'directory_current_fileid'=>0,
|
||||
'directory_fileids'=>array(),
|
||||
'directory_selected'=>array(),
|
||||
'directory_selected_fileids'=>array(),
|
||||
'database_prompted'=>false,
|
||||
'mount_prompted'=>false,
|
||||
'api_status'=>'pending',
|
||||
'api_username'=>'',
|
||||
'api_error'=>'',
|
||||
));
|
||||
|
||||
bratonien_tools_nc_wizard_refresh_directory_state($state, '');
|
||||
bratonien_tools_nc_wizard_store($state);
|
||||
|
||||
return array('message'=>'Nextcloud und WebDAV wurden bestätigt. Jetzt können die Verzeichnisse des angemeldeten Benutzers ausgewählt werden.');
|
||||
}
|
||||
|
||||
function bratonien_tools_nc_wizard_save_sources_dispatch()
|
||||
{
|
||||
$state = bratonien_tools_nc_wizard_state();
|
||||
if ((string)($state['source_mode'] ?? '') !== 'webdav-placeholder')
|
||||
{
|
||||
return bratonien_tools_nc_wizard_save_mounts_server_side();
|
||||
}
|
||||
|
||||
if ((int)($state['step'] ?? 0) !== 2 || empty($state['directory_selection_ready']))
|
||||
{
|
||||
throw new RuntimeException('Die Verzeichnisauswahl ist in diesem Fenster nicht verfügbar.');
|
||||
}
|
||||
|
||||
$selected = isset($state['directory_selected']) && is_array($state['directory_selected'])
|
||||
? array_values(array_unique(array_map(function($path) { return trim((string)$path, '/'); }, $state['directory_selected'])))
|
||||
: array();
|
||||
$selected = array_values(array_filter($selected, function($path) { return $path !== ''; }));
|
||||
if (!$selected)
|
||||
{
|
||||
throw new RuntimeException('Bitte mindestens ein Nextcloud-Verzeichnis auswählen.');
|
||||
}
|
||||
|
||||
$selected_ids = isset($state['directory_selected_fileids']) && is_array($state['directory_selected_fileids'])
|
||||
? $state['directory_selected_fileids']
|
||||
: array();
|
||||
$roots = array();
|
||||
foreach ($selected as $path)
|
||||
{
|
||||
$fileid = (int)($selected_ids[$path] ?? 0);
|
||||
if ($fileid < 1)
|
||||
{
|
||||
throw new RuntimeException('Für eine Auswahl fehlt die eindeutige Nextcloud-Datei-ID. Bitte das Verzeichnis erneut auswählen.');
|
||||
}
|
||||
$roots[] = array(
|
||||
'fileid'=>$fileid,
|
||||
'display_name'=>basename($path),
|
||||
'webdav_path'=>$path,
|
||||
);
|
||||
}
|
||||
|
||||
$state['roots'] = $roots;
|
||||
$state['technical_complete'] = true;
|
||||
$state['technical_stage'] = 'ready';
|
||||
$state['technical_source'] = 'WebDAV-Verzeichnisse ausgewählt';
|
||||
$state['technical_error'] = '';
|
||||
$state['directory_selection_ready'] = false;
|
||||
bratonien_tools_nc_wizard_store($state);
|
||||
|
||||
return array('message'=>'WebDAV-Verzeichnisse wurden übernommen. Die Verbindung ist für den parallelen Testweg vorbereitet.');
|
||||
}
|
||||
|
||||
function bratonien_tools_nc_wizard_finish_dispatch()
|
||||
{
|
||||
$state = bratonien_tools_nc_wizard_state();
|
||||
if ((string)($state['source_mode'] ?? '') !== 'webdav-placeholder')
|
||||
{
|
||||
return bratonien_tools_nc_wizard_finish_generic_scope();
|
||||
}
|
||||
|
||||
if ((int)($state['step'] ?? 0) !== 4 || empty($state['technical_complete']))
|
||||
{
|
||||
throw new RuntimeException('Der Assistent ist noch nicht vollständig.');
|
||||
}
|
||||
|
||||
if (array_key_exists('nc_wizard_fallback_user', $_POST)) $state['_fallback_user'] = trim((string)$_POST['nc_wizard_fallback_user']);
|
||||
if (array_key_exists('nc_wizard_fallback_password', $_POST)) $state['_fallback_password'] = (string)$_POST['nc_wizard_fallback_password'];
|
||||
bratonien_tools_nc_wizard_store($state);
|
||||
|
||||
$fallback_user = trim((string)($state['_fallback_user'] ?? ''));
|
||||
$fallback_password = (string)($state['_fallback_password'] ?? '');
|
||||
if (($fallback_user === '') !== ($fallback_password === ''))
|
||||
{
|
||||
throw new RuntimeException('Fallback-Benutzer und Fallback-Passwort müssen entweder beide angegeben oder beide leer gelassen werden.');
|
||||
}
|
||||
if (($state['api_status'] ?? '') !== 'ok' && $fallback_user === '')
|
||||
{
|
||||
throw new RuntimeException('Da die Piwigo-API übersprungen wurde, ist für diese Verbindung ein Fallback-Zugang erforderlich.');
|
||||
}
|
||||
|
||||
if ($fallback_user !== '')
|
||||
{
|
||||
try
|
||||
{
|
||||
bratonien_tools_nc_connector_validate_fallback_credentials($fallback_user, $fallback_password);
|
||||
}
|
||||
catch (Throwable $e)
|
||||
{
|
||||
throw new RuntimeException('Der Piwigo-Fallback wurde nicht gespeichert: '.$e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
$result = bratonien_tools_nc_connector_create_webdav_placeholder_from_wizard();
|
||||
unset($_SESSION['bratonien_nc_wizard']);
|
||||
return $result;
|
||||
}
|
||||
@@ -27,6 +27,10 @@ require_once(BRATONIEN_TOOLS_PATH . 'include/nc_connector_wizard_user_scope.inc.
|
||||
require_once(BRATONIEN_TOOLS_PATH . 'include/nc_connector_wizard_flow.inc.php');
|
||||
require_once(BRATONIEN_TOOLS_PATH . 'include/nc_connector_connection_scope.inc.php');
|
||||
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()
|
||||
{
|
||||
@@ -52,19 +56,23 @@ function bratonien_tools_get_tools()
|
||||
'album_share_regenerate_link' => array('handler' => 'bratonien_tools_regenerate_album_share_link'),
|
||||
'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_delete' => array('handler' => 'bratonien_tools_nc_connector_delete_any'),
|
||||
'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'),
|
||||
'nc_connector_wizard_scan' => array('handler' => 'bratonien_tools_nc_wizard_scan_user_scoped'),
|
||||
'nc_connector_wizard_scan' => array('handler' => 'bratonien_tools_nc_wizard_scan_webdav_first'),
|
||||
'nc_connector_wizard_save_technical' => array('handler' => 'bratonien_tools_nc_wizard_save_technical_flow'),
|
||||
'nc_connector_wizard_directory_browse' => array('handler' => 'bratonien_tools_nc_wizard_directory_browse'),
|
||||
'nc_connector_wizard_directory_add' => array('handler' => 'bratonien_tools_nc_wizard_directory_add'),
|
||||
'nc_connector_wizard_directory_remove' => array('handler' => 'bratonien_tools_nc_wizard_directory_remove'),
|
||||
'nc_connector_wizard_save_mounts' => array('handler' => 'bratonien_tools_nc_wizard_save_mounts_server_side'),
|
||||
'nc_connector_wizard_save_mounts' => array('handler' => 'bratonien_tools_nc_wizard_save_sources_dispatch'),
|
||||
'nc_connector_wizard_select_user' => array('handler' => 'bratonien_tools_nc_wizard_select_current_user'),
|
||||
'nc_connector_wizard_api_test' => array('handler' => 'bratonien_tools_nc_wizard_api_test'),
|
||||
'nc_connector_wizard_api_skip' => array('handler' => 'bratonien_tools_nc_wizard_api_skip'),
|
||||
'nc_connector_wizard_finish' => array('handler' => 'bratonien_tools_nc_wizard_finish_generic_scope'),
|
||||
'nc_connector_wizard_finish' => array('handler' => 'bratonien_tools_nc_wizard_finish_dispatch'),
|
||||
'nc_connector_wizard_back' => array('handler' => 'bratonien_tools_nc_wizard_back'),
|
||||
'nc_connector_wizard_reset' => array('handler' => 'bratonien_tools_nc_wizard_reset'),
|
||||
'nc_connector_import_legacy' => array('handler' => 'bratonien_tools_nc_connector_import_legacy'),
|
||||
|
||||
434
include/webdav_image_runtime.inc.php
Normal file
434
include/webdav_image_runtime.inc.php
Normal file
@@ -0,0 +1,434 @@
|
||||
<?php
|
||||
if (!defined('PHPWG_ROOT_PATH'))
|
||||
{
|
||||
die('Hacking attempt!');
|
||||
}
|
||||
|
||||
function bratonien_tools_webdav_image_source_info($image_id)
|
||||
{
|
||||
static $cache = array();
|
||||
$image_id = (int)$image_id;
|
||||
if ($image_id < 1) return null;
|
||||
if (array_key_exists($image_id, $cache)) return $cache[$image_id];
|
||||
|
||||
$result = pwg_query('SELECT path, coi FROM '.IMAGES_TABLE.' WHERE id='.$image_id.' LIMIT 1');
|
||||
if (!pwg_db_num_rows($result)) return $cache[$image_id] = null;
|
||||
$row = pwg_db_fetch_assoc($result);
|
||||
$path = (string)($row['path'] ?? '');
|
||||
if ($path === '') return $cache[$image_id] = null;
|
||||
|
||||
$absolute = $path;
|
||||
if (strpos($absolute, '/') !== 0)
|
||||
{
|
||||
$absolute = PHPWG_ROOT_PATH.ltrim(preg_replace('#^\./#', '', $absolute), '/');
|
||||
}
|
||||
$resolved = realpath($absolute);
|
||||
if ($resolved === false) return $cache[$image_id] = null;
|
||||
|
||||
$normalized = str_replace('\\', '/', $resolved);
|
||||
if (!preg_match('#/nc-webdav-source/connection-([0-9]+)/root-([0-9]+)/(.*)$#', $normalized, $match))
|
||||
{
|
||||
return $cache[$image_id] = null;
|
||||
}
|
||||
|
||||
$connection_id = (int)$match[1];
|
||||
$root_fileid = (int)$match[2];
|
||||
$relative_path = trim((string)$match[3], '/');
|
||||
if ($relative_path === '') return $cache[$image_id] = null;
|
||||
|
||||
$table = defined('BRATONIEN_TOOLS_NC_CONNECTIONS_TABLE')
|
||||
? BRATONIEN_TOOLS_NC_CONNECTIONS_TABLE
|
||||
: $GLOBALS['prefixeTable'].'bratonien_tools_nc_connections';
|
||||
$connection_result = pwg_query('SELECT config_json FROM `'.$table.'` WHERE id='.$connection_id.' LIMIT 1');
|
||||
if (!pwg_db_num_rows($connection_result)) return $cache[$image_id] = null;
|
||||
$connection_row = pwg_db_fetch_assoc($connection_result);
|
||||
$config = json_decode((string)$connection_row['config_json'], true);
|
||||
if (!is_array($config) || (string)($config['source_mode'] ?? '') !== 'webdav-placeholder')
|
||||
{
|
||||
return $cache[$image_id] = null;
|
||||
}
|
||||
|
||||
$root_path = '';
|
||||
$roots = isset($config['roots']) && is_array($config['roots']) ? $config['roots'] : array();
|
||||
foreach ($roots as $root)
|
||||
{
|
||||
if ((int)($root['fileid'] ?? 0) === $root_fileid)
|
||||
{
|
||||
$root_path = trim((string)($root['webdav_path'] ?? ''), '/');
|
||||
break;
|
||||
}
|
||||
}
|
||||
if ($root_path === '') return $cache[$image_id] = null;
|
||||
|
||||
$webdav_path = $root_path.'/'.$relative_path;
|
||||
$content_type = '';
|
||||
$size = 0;
|
||||
$etag = '';
|
||||
|
||||
$state_dir = rtrim((string)($config['state_dir'] ?? ''), '/');
|
||||
if ($state_dir !== '')
|
||||
{
|
||||
$mapping_file = $state_dir.'/webdav-map.json';
|
||||
if (is_readable($mapping_file))
|
||||
{
|
||||
$mapping = json_decode((string)file_get_contents($mapping_file), true);
|
||||
if (is_array($mapping) && isset($mapping['files']) && is_array($mapping['files']))
|
||||
{
|
||||
$entry = $mapping['files'][$resolved] ?? $mapping['files'][$normalized] ?? null;
|
||||
if (is_array($entry) && (string)($entry['kind'] ?? '') === 'file')
|
||||
{
|
||||
$webdav_path = trim((string)($entry['webdav_path'] ?? $webdav_path), '/');
|
||||
$content_type = (string)($entry['content_type'] ?? '');
|
||||
$size = (int)($entry['size'] ?? 0);
|
||||
$etag = (string)($entry['etag'] ?? '');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $cache[$image_id] = array(
|
||||
'image_id'=>$image_id,
|
||||
'connection_id'=>$connection_id,
|
||||
'webdav_path'=>$webdav_path,
|
||||
'content_type'=>$content_type,
|
||||
'size'=>$size,
|
||||
'etag'=>$etag,
|
||||
'coi'=>$row['coi'] ?? null,
|
||||
);
|
||||
}
|
||||
|
||||
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));
|
||||
return $url;
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
$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)
|
||||
{
|
||||
if (!class_exists('DerivativeParams') || !class_exists('SizingParams')) return null;
|
||||
$tokens = explode('_', (string)$key);
|
||||
if (!$tokens) return null;
|
||||
|
||||
$token = array_shift($tokens);
|
||||
$crop = 0;
|
||||
$min_size = null;
|
||||
$parse_size = function($value)
|
||||
{
|
||||
$parts = explode('x', (string)$value, 2);
|
||||
if (count($parts) === 1)
|
||||
{
|
||||
$size = max(1, (int)$parts[0]);
|
||||
return array($size, $size);
|
||||
}
|
||||
return array(max(1, (int)$parts[0]), max(1, (int)$parts[1]));
|
||||
};
|
||||
|
||||
if (isset($token[0]) && $token[0] === 's')
|
||||
{
|
||||
$size = $parse_size(substr($token, 1));
|
||||
}
|
||||
elseif (isset($token[0]) && $token[0] === 'e')
|
||||
{
|
||||
$crop = 1;
|
||||
$size = $min_size = $parse_size(substr($token, 1));
|
||||
}
|
||||
else
|
||||
{
|
||||
if (count($tokens) < 2) return null;
|
||||
$size = $parse_size($token);
|
||||
$crop_token = array_shift($tokens);
|
||||
$min_size = $parse_size(array_shift($tokens));
|
||||
$crop = function_exists('char_to_fraction') ? char_to_fraction($crop_token) : 0;
|
||||
}
|
||||
|
||||
$params = new DerivativeParams(new SizingParams($size, $crop, $min_size));
|
||||
if (class_exists('ImageStdParams')) ImageStdParams::apply_global($params);
|
||||
return $params;
|
||||
}
|
||||
|
||||
function bratonien_tools_webdav_derivative_variants()
|
||||
{
|
||||
$variants = array();
|
||||
if (!class_exists('ImageStdParams')) return $variants;
|
||||
|
||||
foreach (ImageStdParams::get_defined_type_map() as $type => $params)
|
||||
{
|
||||
$variants['standard:'.$type] = $params;
|
||||
}
|
||||
foreach (ImageStdParams::$custom as $custom_key => $last_used)
|
||||
{
|
||||
$params = bratonien_tools_webdav_custom_derivative_params($custom_key);
|
||||
if ($params) $variants['custom:'.$custom_key] = $params;
|
||||
}
|
||||
return $variants;
|
||||
}
|
||||
|
||||
function bratonien_tools_webdav_generate_derivative($params, $src_image, &$detail=null)
|
||||
{
|
||||
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)
|
||||
{
|
||||
$detail = 'WebDAV-Quellzuordnung fehlt.';
|
||||
return false;
|
||||
}
|
||||
|
||||
$preview = bratonien_tools_webdav_preview_path($info);
|
||||
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');
|
||||
|
||||
$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();
|
||||
$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) >= max($preview_mtime, (int)($params->last_mod_time ?? 0)))
|
||||
{
|
||||
$detail = 'Bereits vorhanden.';
|
||||
return true;
|
||||
}
|
||||
|
||||
$directory = dirname($target);
|
||||
$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 = null;
|
||||
try
|
||||
{
|
||||
$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)
|
||||
{
|
||||
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)
|
||||
{
|
||||
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) && !$image->sharpen($params->sharpen))
|
||||
{
|
||||
$detail = 'Sharpen fehlgeschlagen.';
|
||||
return false;
|
||||
}
|
||||
|
||||
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
|
||||
{
|
||||
if (is_object($image)) $image->destroy();
|
||||
}
|
||||
|
||||
@chmod($target, 0644);
|
||||
clearstatcache(true, $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)
|
||||
{
|
||||
if (!is_object($src_image) || empty($src_image->id)) return $url;
|
||||
$webdav_url = bratonien_tools_webdav_image_url((int)$src_image->id, false);
|
||||
return $webdav_url ?: $url;
|
||||
}
|
||||
|
||||
function bratonien_tools_filter_webdav_derivative_url($url, $params, $src_image, $rel_url)
|
||||
{
|
||||
if (!is_object($src_image) || empty($src_image->id)) return $url;
|
||||
$info = bratonien_tools_webdav_image_source_info((int)$src_image->id);
|
||||
if (!$info) return $url;
|
||||
|
||||
try
|
||||
{
|
||||
$derivative = new DerivativeImage($params, $src_image);
|
||||
if (!$derivative->same_as_source())
|
||||
{
|
||||
$path = $derivative->get_path();
|
||||
if ($path !== '' && is_file($path) && is_readable($path)) return $url;
|
||||
}
|
||||
}
|
||||
catch (Throwable $e)
|
||||
{
|
||||
error_log('Bratonien WebDAV derivative lookup #'.(int)$src_image->id.': '.$e->getMessage());
|
||||
}
|
||||
|
||||
$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();
|
||||
}
|
||||
})();
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<?php
|
||||
/*
|
||||
Plugin Name: Bratonien Tools
|
||||
Version: 0.9.5.3
|
||||
Version: 0.9.6.9
|
||||
Description: Erweiterbare Administrationswerkzeuge fuer die Bratonien-Piwigo-Installation.
|
||||
Plugin URI: https://github.com/Terranom674/Piwigo_Bratonien_Tools
|
||||
Author: Bratonien
|
||||
@@ -16,6 +16,7 @@ define('BRATONIEN_TOOLS_ID', basename(dirname(__FILE__)));
|
||||
define('BRATONIEN_TOOLS_PATH', PHPWG_PLUGINS_PATH . BRATONIEN_TOOLS_ID . '/');
|
||||
|
||||
require_once(BRATONIEN_TOOLS_PATH . 'include/watermark_runtime.inc.php');
|
||||
require_once(BRATONIEN_TOOLS_PATH . 'include/webdav_image_runtime.inc.php');
|
||||
require_once(BRATONIEN_TOOLS_PATH . 'include/public_selection.inc.php');
|
||||
require_once(BRATONIEN_TOOLS_PATH . 'include/picture_navigation.inc.php');
|
||||
require_once(BRATONIEN_TOOLS_PATH . 'include/batch_titles.inc.php');
|
||||
@@ -26,6 +27,8 @@ require_once(BRATONIEN_TOOLS_PATH . 'include/nc_productive_ws.inc.php');
|
||||
|
||||
add_event_handler('get_admin_plugin_menu_links', 'bratonien_tools_admin_menu');
|
||||
add_event_handler('get_derivative_url', 'bratonien_tools_filter_derivative_url', EVENT_HANDLER_PRIORITY_NEUTRAL, 4);
|
||||
add_event_handler('get_src_image_url', 'bratonien_tools_filter_webdav_src_url', EVENT_HANDLER_PRIORITY_NEUTRAL + 50, 2);
|
||||
add_event_handler('get_derivative_url', 'bratonien_tools_filter_webdav_derivative_url', EVENT_HANDLER_PRIORITY_NEUTRAL + 50, 4);
|
||||
add_event_handler('loc_end_element_set_global', 'bratonien_tools_batch_titles_register_action');
|
||||
add_event_handler('element_set_global_action', 'bratonien_tools_batch_titles_apply', EVENT_HANDLER_PRIORITY_NEUTRAL, 2);
|
||||
add_event_handler('init', 'bratonien_tools_prepare_connector_private_import', EVENT_HANDLER_PRIORITY_NEUTRAL - 30);
|
||||
|
||||
84
nc-connector-edit-data.php
Normal file
84
nc-connector-edit-data.php
Normal file
@@ -0,0 +1,84 @@
|
||||
<?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');
|
||||
|
||||
$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();
|
||||
try
|
||||
{
|
||||
$credentials = bratonien_tools_nc_connector_scoped_secret($connection);
|
||||
}
|
||||
catch (Throwable $e)
|
||||
{
|
||||
$credentials = array();
|
||||
}
|
||||
|
||||
$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,
|
||||
),
|
||||
);
|
||||
|
||||
echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
||||
@@ -36,6 +36,11 @@ $latest = array(
|
||||
'api'=>array('state'=>'not_run','message'=>''),
|
||||
'fallback'=>array('state'=>'not_run','message'=>''),
|
||||
'error_detail'=>'',
|
||||
'route'=>'',
|
||||
'route_label'=>'Noch kein Datenweg erfasst',
|
||||
'route_timestamp'=>0,
|
||||
'route_time_label'=>'Nicht verfügbar',
|
||||
'route_detail'=>'',
|
||||
);
|
||||
|
||||
if (is_dir($dir))
|
||||
@@ -57,6 +62,54 @@ if (is_dir($dir))
|
||||
$latest['connection_file'] = basename($file);
|
||||
}
|
||||
}
|
||||
|
||||
$route_file = $dir.'/route-status.json';
|
||||
if (is_readable($route_file))
|
||||
{
|
||||
$route = json_decode((string)@file_get_contents($route_file), true);
|
||||
if (is_array($route))
|
||||
{
|
||||
$route_name = (string)($route['route'] ?? '');
|
||||
$route_timestamp = (int)($route['timestamp'] ?? 0);
|
||||
$route_label = (string)($route['label'] ?? '');
|
||||
|
||||
if ($route_name === 'webdav')
|
||||
{
|
||||
$route_label = 'WEBDAV PRIMÄR';
|
||||
}
|
||||
elseif ($route_name === 'legacy_fallback')
|
||||
{
|
||||
$route_label = 'LEGACY-FALLBACK AKTIV';
|
||||
}
|
||||
elseif ($route_name === 'failed')
|
||||
{
|
||||
$route_label = 'FEHLER - KEIN ERFOLGREICHER DATENWEG';
|
||||
}
|
||||
elseif ($route_label === '')
|
||||
{
|
||||
$route_label = 'UNBEKANNTER DATENWEG';
|
||||
}
|
||||
|
||||
$route_detail = trim((string)($route['detail'] ?? ''));
|
||||
$latest['route'] = $route_name;
|
||||
$latest['route_label'] = $route_label;
|
||||
$latest['route_timestamp'] = $route_timestamp;
|
||||
$latest['route_time_label'] = $route_timestamp > 0 ? date('d.m.Y H:i:s', $route_timestamp) : 'Nicht verfügbar';
|
||||
$latest['route_detail'] = $route_detail;
|
||||
|
||||
$base_message = trim((string)($latest['message'] ?? ''));
|
||||
$message_parts = array($route_label);
|
||||
if ($route_name !== 'webdav' && $route_detail !== '')
|
||||
{
|
||||
$message_parts[] = $route_detail;
|
||||
}
|
||||
if ($base_message !== '')
|
||||
{
|
||||
$message_parts[] = $base_message;
|
||||
}
|
||||
$latest['message'] = implode(' · ', $message_parts);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ((int)$latest['timestamp'] > 0)
|
||||
|
||||
86
runtime/cleanup-stale.php
Normal file
86
runtime/cleanup-stale.php
Normal file
@@ -0,0 +1,86 @@
|
||||
#!/usr/bin/env php
|
||||
<?php
|
||||
if (PHP_SAPI !== 'cli')
|
||||
{
|
||||
fwrite(STDERR, "CLI only\n");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
$pluginRoot = dirname(__DIR__);
|
||||
$piwigoRoot = dirname($pluginRoot, 2);
|
||||
$dbConfig = $piwigoRoot.'/local/config/database.inc.php';
|
||||
$configDir = '/etc/bratonien-tools/nc-connector';
|
||||
$stateRoot = '/var/lib/bratonien-tools/nc-connector';
|
||||
|
||||
function cleanup_fail($message)
|
||||
{
|
||||
fwrite(STDERR, $message."\n");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
function cleanup_tree($path)
|
||||
{
|
||||
$path = rtrim((string)$path, '/');
|
||||
if ($path === '' || $path === '/' || !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;
|
||||
cleanup_tree($path.'/'.$item);
|
||||
}
|
||||
@rmdir($path);
|
||||
}
|
||||
|
||||
if (!is_readable($dbConfig)) cleanup_fail('Piwigo-Datenbankkonfiguration ist nicht lesbar.');
|
||||
$conf = array();
|
||||
$prefixeTable = 'piwigo_';
|
||||
require $dbConfig;
|
||||
foreach (array('db_host','db_user','db_password','db_base') as $key)
|
||||
{
|
||||
if (!isset($conf[$key])) cleanup_fail('Piwigo-Datenbankkonfiguration ist unvollstaendig: '.$key);
|
||||
}
|
||||
|
||||
$db = new mysqli($conf['db_host'], $conf['db_user'], $conf['db_password'], $conf['db_base']);
|
||||
if ($db->connect_errno) cleanup_fail('Piwigo-Datenbank ist nicht erreichbar: '.$db->connect_error);
|
||||
$db->set_charset('utf8mb4');
|
||||
|
||||
$table = $prefixeTable.'bratonien_tools_nc_connections';
|
||||
$escapedTable = $db->real_escape_string($table);
|
||||
$exists = $db->query("SHOW TABLES LIKE '{$escapedTable}'");
|
||||
if (!$exists) cleanup_fail('Connector-Tabelle konnte nicht geprüft werden: '.$db->error);
|
||||
if ($exists->num_rows === 0) exit(0);
|
||||
|
||||
$activeIds = array();
|
||||
$result = $db->query("SELECT id FROM `{$table}`");
|
||||
if (!$result) cleanup_fail('Connector-Verbindungen konnten nicht gelesen werden: '.$db->error);
|
||||
while ($row = $result->fetch_assoc())
|
||||
{
|
||||
$activeIds[(int)$row['id']] = true;
|
||||
}
|
||||
|
||||
if (!is_dir($configDir)) exit(0);
|
||||
foreach (glob($configDir.'/connection-*.conf') ?: array() as $configPath)
|
||||
{
|
||||
if (!preg_match('/connection-([0-9]+)\.conf$/', $configPath, $matches)) continue;
|
||||
$id = (int)$matches[1];
|
||||
if (isset($activeIds[$id])) continue;
|
||||
|
||||
echo "NC Connector: entferne verwaiste Laufzeitdateien fuer Verbindung {$id}.\n";
|
||||
foreach (array('.conf','.db-password','.piwigo-password','.storages.tsv','.roots.tsv') as $suffix)
|
||||
{
|
||||
@unlink($configDir.'/connection-'.$id.$suffix);
|
||||
}
|
||||
cleanup_tree($stateRoot.'/connection-'.$id);
|
||||
|
||||
$statusDir = rtrim($piwigoRoot, '/').'/_data/bratonien-tools/nc-connector-status';
|
||||
@unlink($statusDir.'/connection-'.$id.'.json');
|
||||
@unlink($statusDir.'/deleted-'.$id);
|
||||
}
|
||||
|
||||
exit(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);
|
||||
}
|
||||
174
runtime/lib/build-webdav-derivatives.php
Normal file
174
runtime/lib/build-webdav-derivatives.php
Normal file
@@ -0,0 +1,174 @@
|
||||
#!/usr/bin/env php
|
||||
<?php
|
||||
if (PHP_SAPI !== 'cli')
|
||||
{
|
||||
fwrite(STDERR, "CLI only\n");
|
||||
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);
|
||||
if ($piwigo_root === '' || $connection_id < 1)
|
||||
{
|
||||
fwrite(STDERR, "Parameter --piwigo-root und --connection-id werden benoetigt.\n");
|
||||
exit(1);
|
||||
}
|
||||
if (!is_dir($piwigo_root))
|
||||
{
|
||||
fwrite(STDERR, "Piwigo-Root wurde nicht gefunden.\n");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
define('PHPWG_ROOT_PATH', $piwigo_root.'/');
|
||||
$_SERVER['REMOTE_ADDR'] = '127.0.0.1';
|
||||
$_SERVER['SERVER_ADDR'] = '127.0.0.1';
|
||||
$_SERVER['SERVER_NAME'] = 'localhost';
|
||||
$_SERVER['HTTP_HOST'] = 'localhost';
|
||||
$_SERVER['SERVER_PORT'] = '80';
|
||||
$_SERVER['REQUEST_METHOD'] = 'GET';
|
||||
$_SERVER['REQUEST_URI'] = '/';
|
||||
$_SERVER['SCRIPT_NAME'] = '/plugins/bratonien_tools/runtime/lib/build-webdav-derivatives.php';
|
||||
$_SERVER['PHP_SELF'] = $_SERVER['SCRIPT_NAME'];
|
||||
$_SERVER['QUERY_STRING'] = '';
|
||||
$_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');
|
||||
require_once(PHPWG_ROOT_PATH.'include/derivative.inc.php');
|
||||
require_once(PHPWG_ROOT_PATH.'admin/include/image.class.php');
|
||||
|
||||
if (!function_exists('bratonien_tools_webdav_image_source_info') || !function_exists('bratonien_tools_webdav_generate_derivative'))
|
||||
{
|
||||
fwrite(STDERR, "Bratonien WebDAV-Bildruntime ist nicht aktiv.\n");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
$variants = bratonien_tools_webdav_derivative_variants();
|
||||
if (!$variants)
|
||||
{
|
||||
throw new RuntimeException('Keine Piwigo-Derivate konfiguriert.');
|
||||
}
|
||||
|
||||
$images = 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))
|
||||
{
|
||||
$image_id = (int)$row['id'];
|
||||
$info = bratonien_tools_webdav_image_source_info($image_id);
|
||||
if (!$info || (int)$info['connection_id'] !== $connection_id) continue;
|
||||
|
||||
$images++;
|
||||
$preview = bratonien_tools_webdav_preview_path($info);
|
||||
if (!$preview)
|
||||
{
|
||||
$errors++;
|
||||
$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;
|
||||
}
|
||||
|
||||
$size = @getimagesize($preview);
|
||||
if (!is_array($size) || empty($size[0]) || empty($size[1]))
|
||||
{
|
||||
$errors++;
|
||||
$error_lines[] = 'Bild #'.$image_id.': Preview ist kein lesbares Bild: '.$preview;
|
||||
continue;
|
||||
}
|
||||
|
||||
$preview_width = (int)$size[0];
|
||||
$preview_height = (int)$size[1];
|
||||
if ((int)($row['width'] ?? 0) !== $preview_width || (int)($row['height'] ?? 0) !== $preview_height || (int)($row['rotation'] ?? 0) !== 0)
|
||||
{
|
||||
pwg_query(
|
||||
'UPDATE '.IMAGES_TABLE.
|
||||
' SET width='.$preview_width.', height='.$preview_height.', rotation=0'.
|
||||
' WHERE id='.$image_id
|
||||
);
|
||||
$row['width'] = $preview_width;
|
||||
$row['height'] = $preview_height;
|
||||
$row['rotation'] = 0;
|
||||
$metadata_repaired++;
|
||||
}
|
||||
|
||||
$src = new SrcImage($row);
|
||||
foreach ($variants as $variant_name => $params)
|
||||
{
|
||||
try
|
||||
{
|
||||
$probe = new DerivativeImage($params, $src);
|
||||
if ($probe->same_as_source())
|
||||
{
|
||||
$identity++;
|
||||
continue;
|
||||
}
|
||||
|
||||
$detail = '';
|
||||
if (bratonien_tools_webdav_generate_derivative($params, $src, $detail))
|
||||
{
|
||||
$generated_or_ready++;
|
||||
}
|
||||
else
|
||||
{
|
||||
$errors++;
|
||||
$error_lines[] = 'Bild #'.$image_id.' '.$variant_name.': '.($detail !== '' ? $detail : 'Derivat konnte nicht erzeugt werden.');
|
||||
}
|
||||
}
|
||||
catch (Throwable $e)
|
||||
{
|
||||
$errors++;
|
||||
$error_lines[] = 'Bild #'.$image_id.' '.$variant_name.': '.get_class($e).': '.$e->getMessage();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($metadata_repaired > 0)
|
||||
{
|
||||
update_category('all');
|
||||
invalidate_user_cache(true);
|
||||
}
|
||||
|
||||
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).
|
||||
' 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: '.get_class($e).': '.$e->getMessage()."\n");
|
||||
exit(1);
|
||||
}
|
||||
319
runtime/lib/build_webdav_placeholder_source.py
Normal file
319
runtime/lib/build_webdav_placeholder_source.py
Normal file
@@ -0,0 +1,319 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build a placeholder-backed local source tree from Nextcloud WebDAV.
|
||||
|
||||
This is intentionally additive: it does not replace the existing local-storage
|
||||
connector path. It creates only tiny placeholder files plus a metadata mapping;
|
||||
no Nextcloud original media is downloaded.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import getpass
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import ssl
|
||||
import sys
|
||||
import tempfile
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import xml.etree.ElementTree as ET
|
||||
from pathlib import Path, PurePosixPath
|
||||
|
||||
DAV = "DAV:"
|
||||
OC = "http://owncloud.org/ns"
|
||||
SUPPORTED_IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".gif", ".webp"}
|
||||
# 1x1 transparent GIF, 34 bytes. The filename keeps the remote extension;
|
||||
# the placeholder exists only so Piwigo can discover the logical image entry.
|
||||
PLACEHOLDER = base64.b64decode("R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==")
|
||||
|
||||
|
||||
def fail(message: str) -> None:
|
||||
raise RuntimeError(message)
|
||||
|
||||
|
||||
def validate_relative(value: str) -> str:
|
||||
value = str(value).strip("/")
|
||||
parts = PurePosixPath(value).parts
|
||||
if ".." in parts:
|
||||
raise ValueError(f"unsafe WebDAV path: {value!r}")
|
||||
return value
|
||||
|
||||
|
||||
def quote_path(value: str) -> str:
|
||||
value = validate_relative(value)
|
||||
return "/".join(urllib.parse.quote(part, safe="") for part in PurePosixPath(value).parts)
|
||||
|
||||
|
||||
def safe_local_name(name: str) -> str:
|
||||
if not name or name in {".", ".."} or "/" in name or "\x00" in name:
|
||||
raise ValueError(f"unsafe remote name: {name!r}")
|
||||
return name
|
||||
|
||||
|
||||
class WebDavClient:
|
||||
def __init__(self, base_url: str, user: str, password: str, timeout: int = 30) -> None:
|
||||
self.base_url = base_url.rstrip("/")
|
||||
self.user = user
|
||||
self.password = password
|
||||
self.timeout = timeout
|
||||
token = base64.b64encode(f"{user}:{password}".encode("utf-8")).decode("ascii")
|
||||
self.auth_header = f"Basic {token}"
|
||||
self.context = ssl.create_default_context()
|
||||
|
||||
def collection_url(self, relative: str) -> str:
|
||||
user = urllib.parse.quote(self.user, safe="")
|
||||
suffix = quote_path(relative)
|
||||
url = f"{self.base_url}/remote.php/dav/files/{user}/"
|
||||
if suffix:
|
||||
url += suffix + "/"
|
||||
return url
|
||||
|
||||
def list_collection(self, relative: str) -> tuple[dict[str, object], list[dict[str, object]]]:
|
||||
relative = validate_relative(relative)
|
||||
url = self.collection_url(relative)
|
||||
body = (
|
||||
'<?xml version="1.0"?>'
|
||||
'<d:propfind xmlns:d="DAV:" xmlns:oc="http://owncloud.org/ns">'
|
||||
'<d:prop><d:displayname/><d:resourcetype/><d:getcontenttype/>'
|
||||
'<d:getcontentlength/><d:getetag/><oc:fileid/></d:prop></d:propfind>'
|
||||
).encode("utf-8")
|
||||
request = urllib.request.Request(url, data=body, method="PROPFIND")
|
||||
request.add_header("Authorization", self.auth_header)
|
||||
request.add_header("Depth", "1")
|
||||
request.add_header("Content-Type", "application/xml; charset=utf-8")
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=self.timeout, context=self.context) as response:
|
||||
status = response.status
|
||||
payload = response.read()
|
||||
except urllib.error.HTTPError as error:
|
||||
if error.code in {401, 403}:
|
||||
fail("Nextcloud rejected the WebDAV credentials or directory access")
|
||||
fail(f"Nextcloud PROPFIND failed with HTTP {error.code}")
|
||||
except urllib.error.URLError as error:
|
||||
fail(f"Nextcloud WebDAV is unreachable: {error.reason}")
|
||||
if status != 207:
|
||||
fail(f"Nextcloud PROPFIND returned HTTP {status}")
|
||||
|
||||
try:
|
||||
root = ET.fromstring(payload)
|
||||
except ET.ParseError as error:
|
||||
raise RuntimeError("Nextcloud returned invalid WebDAV XML") from error
|
||||
|
||||
base_path = urllib.parse.unquote(urllib.parse.urlparse(url).path).rstrip("/")
|
||||
current: dict[str, object] | None = None
|
||||
children: list[dict[str, object]] = []
|
||||
for response in root.findall(f"{{{DAV}}}response"):
|
||||
href = response.findtext(f"{{{DAV}}}href", default="")
|
||||
href_path = urllib.parse.unquote(urllib.parse.urlparse(href).path).rstrip("/")
|
||||
prop = None
|
||||
for propstat in response.findall(f"{{{DAV}}}propstat"):
|
||||
status_text = propstat.findtext(f"{{{DAV}}}status", default="")
|
||||
if " 200 " in status_text:
|
||||
prop = propstat.find(f"{{{DAV}}}prop")
|
||||
if prop is not None:
|
||||
break
|
||||
if prop is None:
|
||||
continue
|
||||
display = prop.findtext(f"{{{DAV}}}displayname", default="")
|
||||
fileid_text = prop.findtext(f"{{{OC}}}fileid", default="").strip()
|
||||
resource_type = prop.find(f"{{{DAV}}}resourcetype")
|
||||
is_dir = resource_type is not None and resource_type.find(f"{{{DAV}}}collection") is not None
|
||||
item = {
|
||||
"display_name": display,
|
||||
"fileid": int(fileid_text) if fileid_text.isdigit() else 0,
|
||||
"is_dir": is_dir,
|
||||
"content_type": prop.findtext(f"{{{DAV}}}getcontenttype", default=""),
|
||||
"size": int(prop.findtext(f"{{{DAV}}}getcontentlength", default="0") or 0),
|
||||
"etag": prop.findtext(f"{{{DAV}}}getetag", default="").strip('"'),
|
||||
}
|
||||
if href_path == base_path:
|
||||
current = item
|
||||
continue
|
||||
if display:
|
||||
children.append(item)
|
||||
if current is None or int(current.get("fileid", 0)) < 1:
|
||||
fail(f"Nextcloud returned no stable fileid for {relative or '/'}")
|
||||
return current, children
|
||||
|
||||
|
||||
def link_placeholder(seed: Path, target: Path) -> None:
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
try:
|
||||
os.link(seed, target)
|
||||
except OSError:
|
||||
target.write_bytes(PLACEHOLDER)
|
||||
|
||||
|
||||
def build_root(
|
||||
client: WebDavClient,
|
||||
remote_root: str,
|
||||
local_root: Path,
|
||||
seed: Path,
|
||||
mapping: dict[str, dict[str, object]],
|
||||
) -> tuple[int, int, int]:
|
||||
files = 0
|
||||
folders = 0
|
||||
skipped = 0
|
||||
stack: list[tuple[str, Path]] = [(validate_relative(remote_root), local_root)]
|
||||
visited: set[str] = set()
|
||||
|
||||
while stack:
|
||||
remote_dir, local_dir = stack.pop()
|
||||
if remote_dir in visited:
|
||||
continue
|
||||
visited.add(remote_dir)
|
||||
current, children = client.list_collection(remote_dir)
|
||||
local_dir.mkdir(parents=True, exist_ok=True)
|
||||
folders += 1
|
||||
mapping[str(local_dir)] = {
|
||||
"kind": "folder",
|
||||
"fileid": int(current["fileid"]),
|
||||
"webdav_path": remote_dir,
|
||||
"display_name": str(current.get("display_name", "")),
|
||||
}
|
||||
|
||||
for child in children:
|
||||
name = safe_local_name(str(child["display_name"]))
|
||||
child_remote = name if remote_dir == "" else f"{remote_dir}/{name}"
|
||||
child_local = local_dir / name
|
||||
if bool(child["is_dir"]):
|
||||
stack.append((child_remote, child_local))
|
||||
continue
|
||||
extension = Path(name).suffix.lower()
|
||||
if extension not in SUPPORTED_IMAGE_EXTENSIONS:
|
||||
skipped += 1
|
||||
continue
|
||||
link_placeholder(seed, child_local)
|
||||
files += 1
|
||||
mapping[str(child_local)] = {
|
||||
"kind": "file",
|
||||
"fileid": int(child.get("fileid", 0)),
|
||||
"webdav_path": child_remote,
|
||||
"display_name": name,
|
||||
"content_type": str(child.get("content_type", "")),
|
||||
"size": int(child.get("size", 0)),
|
||||
"etag": str(child.get("etag", "")),
|
||||
}
|
||||
return files, folders, skipped
|
||||
|
||||
|
||||
def atomic_json(path: Path, payload: object) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with tempfile.NamedTemporaryFile("w", encoding="utf-8", dir=path.parent, delete=False) as handle:
|
||||
json.dump(payload, handle, ensure_ascii=False, indent=2, sort_keys=True)
|
||||
handle.write("\n")
|
||||
temporary = Path(handle.name)
|
||||
temporary.replace(path)
|
||||
|
||||
|
||||
def atomic_text(path: Path, text: str) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with tempfile.NamedTemporaryFile("w", encoding="utf-8", dir=path.parent, delete=False) as handle:
|
||||
handle.write(text)
|
||||
temporary = Path(handle.name)
|
||||
temporary.replace(path)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--base-url", required=True)
|
||||
parser.add_argument("--user", required=True)
|
||||
parser.add_argument("--password-file", type=Path)
|
||||
parser.add_argument("--root", action="append", required=True, help="WebDAV path relative to the authenticated user's files root")
|
||||
parser.add_argument("--source-dir", required=True, type=Path)
|
||||
parser.add_argument("--manifest", required=True, type=Path)
|
||||
parser.add_argument("--mapping", required=True, type=Path)
|
||||
parser.add_argument("--timeout", type=int, default=30)
|
||||
args = parser.parse_args()
|
||||
|
||||
try:
|
||||
if args.password_file:
|
||||
password = args.password_file.read_text(encoding="utf-8").rstrip("\r\n")
|
||||
else:
|
||||
password = getpass.getpass("Nextcloud password: ")
|
||||
if not password:
|
||||
fail("Nextcloud password is empty")
|
||||
|
||||
source_dir = args.source_dir.resolve()
|
||||
staging = source_dir.with_name(f".{source_dir.name}.next")
|
||||
previous = source_dir.with_name(f".{source_dir.name}.previous")
|
||||
seed = source_dir.parent / ".bratonien-webdav-placeholder.gif"
|
||||
source_dir.parent.mkdir(parents=True, exist_ok=True)
|
||||
seed.write_bytes(PLACEHOLDER)
|
||||
os.chmod(seed, 0o644)
|
||||
if staging.exists():
|
||||
shutil.rmtree(staging)
|
||||
staging.mkdir(parents=True)
|
||||
|
||||
client = WebDavClient(args.base_url, args.user, password, max(1, args.timeout))
|
||||
mapping: dict[str, dict[str, object]] = {}
|
||||
manifest: list[str] = []
|
||||
total_files = total_folders = total_skipped = 0
|
||||
used_names: set[str] = set()
|
||||
|
||||
for remote_root_raw in args.root:
|
||||
remote_root = validate_relative(remote_root_raw)
|
||||
current, _ = client.list_collection(remote_root)
|
||||
fileid = int(current["fileid"])
|
||||
display = str(current.get("display_name", "")).strip() or (PurePosixPath(remote_root).name if remote_root else args.user)
|
||||
local_name = f"root-{fileid}"
|
||||
if local_name in used_names:
|
||||
fail(f"duplicate selected Nextcloud root fileid: {fileid}")
|
||||
used_names.add(local_name)
|
||||
local_root = staging / local_name
|
||||
files, folders, skipped = build_root(client, remote_root, local_root, seed, mapping)
|
||||
total_files += files
|
||||
total_folders += folders
|
||||
total_skipped += skipped
|
||||
manifest.append(f"webdav:{fileid}\tfolder\t{display}\t{source_dir / local_name}")
|
||||
|
||||
if previous.exists():
|
||||
shutil.rmtree(previous)
|
||||
if source_dir.exists():
|
||||
source_dir.rename(previous)
|
||||
try:
|
||||
staging.rename(source_dir)
|
||||
except Exception:
|
||||
if source_dir.exists():
|
||||
shutil.rmtree(source_dir)
|
||||
if previous.exists():
|
||||
previous.rename(source_dir)
|
||||
raise
|
||||
if previous.exists():
|
||||
shutil.rmtree(previous)
|
||||
|
||||
final_mapping: dict[str, dict[str, object]] = {}
|
||||
staging_text = str(staging)
|
||||
source_text = str(source_dir)
|
||||
for path, data in mapping.items():
|
||||
final_path = source_text + path[len(staging_text):] if path.startswith(staging_text) else path
|
||||
final_mapping[final_path] = data
|
||||
|
||||
atomic_text(args.manifest, "\n".join(manifest) + "\n")
|
||||
atomic_json(args.mapping, {
|
||||
"version": 1,
|
||||
"base_url": args.base_url.rstrip("/"),
|
||||
"user": args.user,
|
||||
"files": final_mapping,
|
||||
})
|
||||
print(json.dumps({
|
||||
"roots": len(args.root),
|
||||
"files": total_files,
|
||||
"folders": total_folders,
|
||||
"skipped": total_skipped,
|
||||
"source_dir": str(source_dir),
|
||||
"manifest": str(args.manifest),
|
||||
"mapping": str(args.mapping),
|
||||
}, ensure_ascii=False))
|
||||
return 0
|
||||
except Exception as error:
|
||||
print(f"webdav-placeholder: {error}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -139,6 +139,39 @@ function decrypt_blob($blob, $hex_key)
|
||||
return (string)$plain;
|
||||
}
|
||||
|
||||
function ensure_webdav_site(mysqli $db, $prefixeTable, $piwigo_root, array $connection_config, $connection_id)
|
||||
{
|
||||
if ((string)($connection_config['source_mode'] ?? '') !== 'webdav-placeholder') return 1;
|
||||
|
||||
$gallery_root = rtrim((string)($connection_config['parallel_gallery_root'] ?? ''), '/');
|
||||
if ($gallery_root === '') fail_sync('WebDAV-Galeriewurzel fehlt in der Verbindungskonfiguration.');
|
||||
$piwigo_root = rtrim((string)$piwigo_root, '/');
|
||||
if (strpos($gallery_root, $piwigo_root.'/') !== 0)
|
||||
{
|
||||
fail_sync('WebDAV-Galeriewurzel liegt ausserhalb der Piwigo-Installation.');
|
||||
}
|
||||
if (!is_dir($gallery_root)) fail_sync('WebDAV-Galeriewurzel existiert nicht: '.$gallery_root);
|
||||
|
||||
$relative = ltrim(substr($gallery_root, strlen($piwigo_root)), '/');
|
||||
if ($relative === '') fail_sync('WebDAV-Galeriewurzel darf nicht dem Piwigo-Hauptverzeichnis entsprechen.');
|
||||
$site_url = './'.rtrim($relative, '/').'/';
|
||||
$escaped = $db->real_escape_string($site_url);
|
||||
$result = $db->query("SELECT id FROM `{$prefixeTable}sites` WHERE galleries_url='{$escaped}' LIMIT 1");
|
||||
if (!$result) fail_sync('Piwigo-Site konnte nicht gelesen werden: '.$db->error);
|
||||
if ($result->num_rows)
|
||||
{
|
||||
return (int)$result->fetch_assoc()['id'];
|
||||
}
|
||||
|
||||
if (!$db->query("INSERT INTO `{$prefixeTable}sites` (galleries_url) VALUES ('{$escaped}')"))
|
||||
{
|
||||
fail_sync('Piwigo-Site fuer WebDAV-Verbindung #'.$connection_id.' konnte nicht angelegt werden: '.$db->error);
|
||||
}
|
||||
$site_id = (int)$db->insert_id;
|
||||
if ($site_id < 1) fail_sync('Piwigo-Site fuer WebDAV-Verbindung #'.$connection_id.' erhielt keine gueltige ID.');
|
||||
return $site_id;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
$options = getopt('', array('piwigo-root:', 'connection-id:', 'base-url:'));
|
||||
@@ -173,6 +206,8 @@ try
|
||||
$connection_credentials = json_decode($connection_plain, true);
|
||||
if (!is_array($connection_credentials)) $connection_credentials = array();
|
||||
|
||||
$site_id = ensure_webdav_site($db, $prefixeTable, $piwigo_root, $connection_config, $connection_id);
|
||||
|
||||
$api = array('key_id'=>'', 'key_secret'=>'');
|
||||
$connection_scoped = (string)($connection_config['piwigo_auth'] ?? '') === 'connection-scoped' || array_key_exists('api_enabled', $connection_config);
|
||||
if ($connection_scoped)
|
||||
@@ -185,7 +220,6 @@ try
|
||||
}
|
||||
else
|
||||
{
|
||||
// Nur fuer bereits aktive Altverbindungen: bisheriger globaler API-Zugang.
|
||||
$api_result = $db->query("SELECT value FROM `{$prefixeTable}config` WHERE param='bratonien_nc_piwigo_api' LIMIT 1");
|
||||
if ($api_result && $api_result->num_rows)
|
||||
{
|
||||
@@ -216,11 +250,17 @@ try
|
||||
'Accept: application/json, text/xml;q=0.9',
|
||||
'Content-Type: application/x-www-form-urlencoded',
|
||||
);
|
||||
decode_ws(http_request($base_url.'/ws.php?format=json', array('method'=>'bratonien.nc.syncProductive', 'site_id'=>1), $headers));
|
||||
$orphan = decode_ws(http_request($base_url.'/ws.php?format=json', array('method'=>'bratonien.nc.syncOrphans', 'site_id'=>1, 'simulate'=>0), $headers));
|
||||
decode_ws(http_request($base_url.'/ws.php?format=json', array('method'=>'bratonien.nc.syncProductive', 'site_id'=>$site_id), $headers));
|
||||
$orphan = decode_ws(http_request($base_url.'/ws.php?format=json', array('method'=>'bratonien.nc.syncOrphans', 'site_id'=>$site_id, 'simulate'=>0), $headers));
|
||||
// Entfernt alte technische bratonien-webdav-N Wrapper aus Site 1,
|
||||
// nachdem deren generierte Verzeichnisse beim Reconcile entfernt wurden.
|
||||
if ($site_id !== 1)
|
||||
{
|
||||
decode_ws(http_request($base_url.'/ws.php?format=json', array('method'=>'bratonien.nc.syncOrphans', 'site_id'=>1, 'simulate'=>0), $headers));
|
||||
}
|
||||
$added = (int)($orphan['added_orphans'] ?? 0);
|
||||
$deleted = (int)($orphan['deleted_orphans'] ?? 0);
|
||||
echo "Piwigo-Synchronisierung per API erfolgreich\n";
|
||||
echo "Piwigo-Synchronisierung per API erfolgreich (Site $site_id)\n";
|
||||
echo "Piwigo-Orphans synchronisiert: +$added / -$deleted\n";
|
||||
exit(0);
|
||||
}
|
||||
@@ -245,15 +285,19 @@ try
|
||||
{
|
||||
decode_ws(http_request($base_url.'/ws.php?format=json', array('method'=>'pwg.session.login', 'username'=>$fallback_user, 'password'=>$fallback_password), array(), $cookie_file));
|
||||
http_request(
|
||||
$base_url.'/admin.php?page=site_update&site=1',
|
||||
$base_url.'/admin.php?page=site_update&site='.$site_id,
|
||||
array('sync'=>'files','display_info'=>1,'privacy_level'=>0,'sync_meta'=>1,'simulate'=>0,'subcats-included'=>1,'bratonien_connector'=>1,'submit'=>1),
|
||||
array(),
|
||||
$cookie_file
|
||||
);
|
||||
$orphan = decode_ws(http_request($base_url.'/ws.php?format=json', array('method'=>'bratonien.nc.syncOrphans', 'site_id'=>1, 'simulate'=>0), array(), $cookie_file));
|
||||
$orphan = decode_ws(http_request($base_url.'/ws.php?format=json', array('method'=>'bratonien.nc.syncOrphans', 'site_id'=>$site_id, 'simulate'=>0), array(), $cookie_file));
|
||||
if ($site_id !== 1)
|
||||
{
|
||||
decode_ws(http_request($base_url.'/ws.php?format=json', array('method'=>'bratonien.nc.syncOrphans', 'site_id'=>1, 'simulate'=>0), array(), $cookie_file));
|
||||
}
|
||||
$added = (int)($orphan['added_orphans'] ?? 0);
|
||||
$deleted = (int)($orphan['deleted_orphans'] ?? 0);
|
||||
echo "Piwigo-Datenbanksynchronisierung per Benutzername/Passwort-Fallback erfolgreich\n";
|
||||
echo "Piwigo-Datenbanksynchronisierung per Benutzername/Passwort-Fallback erfolgreich (Site $site_id)\n";
|
||||
echo "Piwigo-Orphans synchronisiert: +$added / -$deleted\n";
|
||||
}
|
||||
finally
|
||||
|
||||
290
runtime/lib/precache-webdav-previews.php
Normal file
290
runtime/lib/precache-webdav-previews.php
Normal file
@@ -0,0 +1,290 @@
|
||||
#!/usr/bin/env php
|
||||
<?php
|
||||
if (PHP_SAPI !== 'cli')
|
||||
{
|
||||
fwrite(STDERR, "CLI only\n");
|
||||
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);
|
||||
}
|
||||
|
||||
function quote_webdav_path($path)
|
||||
{
|
||||
$parts = array_values(array_filter(explode('/', trim((string)$path, '/')), 'strlen'));
|
||||
return implode('/', array_map('rawurlencode', $parts));
|
||||
}
|
||||
|
||||
function fetch_remote_blob($url, $user, $password)
|
||||
{
|
||||
$ch = curl_init($url);
|
||||
curl_setopt_array($ch, array(
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_FOLLOWLOCATION => false,
|
||||
CURLOPT_CONNECTTIMEOUT => 10,
|
||||
CURLOPT_TIMEOUT => 120,
|
||||
CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
|
||||
CURLOPT_USERPWD => $user.':'.$password,
|
||||
CURLOPT_FAILONERROR => false,
|
||||
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 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'))
|
||||
{
|
||||
write_preview_imagick($blob, $target, $extension);
|
||||
}
|
||||
elseif (function_exists('imagecreatefromstring') && function_exists('imagejpeg') && function_exists('imagepng'))
|
||||
{
|
||||
write_preview_gd($blob, $target, $extension);
|
||||
}
|
||||
else
|
||||
{
|
||||
fail_preview('Weder Imagick noch GD 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
|
||||
{
|
||||
$options = getopt('', array('mapping:', 'base-url:', 'user:', 'password-file:', 'cache-dir:'));
|
||||
$mapping_file = (string)($options['mapping'] ?? '');
|
||||
$base_url = rtrim((string)($options['base-url'] ?? ''), '/');
|
||||
$user = trim((string)($options['user'] ?? ''));
|
||||
$password_file = (string)($options['password-file'] ?? '');
|
||||
$cache_dir = rtrim((string)($options['cache-dir'] ?? ''), '/');
|
||||
|
||||
if ($mapping_file === '' || !is_readable($mapping_file)) fail_preview('WebDAV-Mapping ist nicht lesbar.');
|
||||
if ($base_url === '' || $user === '' || $password_file === '' || !is_readable($password_file) || $cache_dir === '') fail_preview('Preview-Parameter sind unvollständig.');
|
||||
if (!function_exists('curl_init')) fail_preview('PHP-cURL ist nicht verfügbar.');
|
||||
|
||||
$password = rtrim((string)file_get_contents($password_file), "\r\n");
|
||||
if ($password === '') fail_preview('Nextcloud-Passwort fehlt.');
|
||||
|
||||
$mapping = json_decode((string)file_get_contents($mapping_file), true);
|
||||
if (!is_array($mapping) || !isset($mapping['files']) || !is_array($mapping['files'])) fail_preview('WebDAV-Mapping ist ungültig.');
|
||||
|
||||
if (!is_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))
|
||||
{
|
||||
$decoded = json_decode((string)file_get_contents($state_file), true);
|
||||
if (is_array($decoded)) $old_state = $decoded;
|
||||
}
|
||||
|
||||
$new_state = array();
|
||||
$generated = 0;
|
||||
$cached = 0;
|
||||
$errors = 0;
|
||||
|
||||
foreach ($mapping['files'] as $entry)
|
||||
{
|
||||
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 = 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,
|
||||
);
|
||||
|
||||
$old = $old_state[$key] ?? null;
|
||||
if (
|
||||
is_file($target)
|
||||
&& is_array($old)
|
||||
&& (string)($old['etag'] ?? '') === $etag
|
||||
&& (string)($old['format'] ?? '') === $extension
|
||||
&& (int)($old['version'] ?? 0) === BRATONIEN_WEBDAV_PREVIEW_VERSION
|
||||
)
|
||||
{
|
||||
$cached++;
|
||||
continue;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
$url = $base_url.'/remote.php/dav/files/'.rawurlencode($user).'/'.quote_webdav_path($webdav_path);
|
||||
$blob = fetch_remote_blob($url, $user, $password);
|
||||
write_preview($blob, $target, $extension);
|
||||
remove_other_preview_format($cache_dir, $key, $target);
|
||||
$generated++;
|
||||
}
|
||||
catch (Throwable $e)
|
||||
{
|
||||
$errors++;
|
||||
fwrite(STDERR, $webdav_path.': '.$e->getMessage()."\n");
|
||||
}
|
||||
}
|
||||
|
||||
foreach (glob($cache_dir.'/*') ?: array() as $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);
|
||||
@chmod($state_file, 0644);
|
||||
|
||||
echo 'WebDAV-Previews: erzeugt='.$generated.' vorhanden='.$cached.' fehler='.$errors."\n";
|
||||
exit($errors > 0 ? 1 : 0);
|
||||
}
|
||||
catch (Throwable $e)
|
||||
{
|
||||
fwrite(STDERR, 'WebDAV-Preview-Cache: '.$e->getMessage()."\n");
|
||||
exit(1);
|
||||
}
|
||||
255
runtime/reconcile-webdav.php
Normal file
255
runtime/reconcile-webdav.php
Normal file
@@ -0,0 +1,255 @@
|
||||
#!/usr/bin/env php
|
||||
<?php
|
||||
if (PHP_SAPI !== 'cli')
|
||||
{
|
||||
fwrite(STDERR, "CLI only\n");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
function fail_webdav_reconcile($message)
|
||||
{
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
|
||||
function decrypt_webdav_credentials($blob, $hexKey)
|
||||
{
|
||||
if (!preg_match('/^[a-f0-9]{64}$/', (string)$hexKey)) fail_webdav_reconcile('Connector-Schluessel ist ungueltig.');
|
||||
$outer = base64_decode(trim((string)$blob), true);
|
||||
$payload = is_string($outer) ? json_decode($outer, true) : null;
|
||||
if (!is_array($payload) || (int)($payload['v'] ?? 0) !== 1) fail_webdav_reconcile('Connector-Zugangsdaten haben ein unbekanntes Format.');
|
||||
$iv = base64_decode((string)($payload['iv'] ?? ''), true);
|
||||
$tag = base64_decode((string)($payload['tag'] ?? ''), true);
|
||||
$cipher = base64_decode((string)($payload['data'] ?? ''), true);
|
||||
$plain = openssl_decrypt($cipher, 'aes-256-gcm', hex2bin($hexKey), OPENSSL_RAW_DATA, $iv, $tag);
|
||||
if ($plain === false || $plain === '') fail_webdav_reconcile('Connector-Zugangsdaten konnten nicht entschluesselt werden.');
|
||||
$decoded = json_decode($plain, true);
|
||||
if (!is_array($decoded)) fail_webdav_reconcile('WebDAV-Verbindung besitzt kein kompatibles Secret-Format.');
|
||||
return array(
|
||||
'nextcloud_user'=>(string)($decoded['nextcloud_user'] ?? ''),
|
||||
'nextcloud_password'=>(string)($decoded['nextcloud_password'] ?? ''),
|
||||
);
|
||||
}
|
||||
|
||||
function webdav_shell_value($value)
|
||||
{
|
||||
return escapeshellarg((string)$value);
|
||||
}
|
||||
|
||||
function webdav_remove_generated_tree($path, $allowedRoot)
|
||||
{
|
||||
$path = rtrim((string)$path, '/');
|
||||
$allowedRoot = rtrim((string)$allowedRoot, '/');
|
||||
if ($path === '' || $allowedRoot === '' || strpos($path, $allowedRoot.'/') !== 0 || !file_exists($path)) return;
|
||||
if (is_link($path) || is_file($path))
|
||||
{
|
||||
@unlink($path);
|
||||
return;
|
||||
}
|
||||
$items = scandir($path);
|
||||
if (is_array($items))
|
||||
{
|
||||
foreach ($items as $item)
|
||||
{
|
||||
if ($item === '.' || $item === '..') continue;
|
||||
webdav_remove_generated_tree($path.'/'.$item, $allowedRoot);
|
||||
}
|
||||
}
|
||||
@rmdir($path);
|
||||
}
|
||||
|
||||
function webdav_source_fingerprint($baseUrl, $user, array $roots)
|
||||
{
|
||||
$normalized = array();
|
||||
foreach ($roots as $root)
|
||||
{
|
||||
$normalized[] = array(
|
||||
'fileid'=>(int)($root['fileid'] ?? 0),
|
||||
'path'=>trim((string)($root['webdav_path'] ?? ''), '/'),
|
||||
);
|
||||
}
|
||||
usort($normalized, function($a, $b)
|
||||
{
|
||||
$cmp = $a['fileid'] <=> $b['fileid'];
|
||||
return $cmp !== 0 ? $cmp : strcmp($a['path'], $b['path']);
|
||||
});
|
||||
return hash('sha256', strtolower(rtrim((string)$baseUrl, '/'))."\n".strtolower(trim((string)$user))."\n".json_encode($normalized));
|
||||
}
|
||||
|
||||
$pluginRoot = dirname(__DIR__);
|
||||
$piwigoRoot = dirname($pluginRoot, 2);
|
||||
$dbConfig = $piwigoRoot.'/local/config/database.inc.php';
|
||||
$configDir = '/etc/bratonien-tools/nc-connector';
|
||||
$stateRoot = '/var/lib/bratonien-tools/nc-connector';
|
||||
$publicSourceRoot = rtrim($piwigoRoot, '/').'/_data/bratonien-tools/nc-webdav-source';
|
||||
$publicGalleryRoot = rtrim($piwigoRoot, '/').'/_data/bratonien-tools/nc-webdav-gallery';
|
||||
$legacyGalleryRoot = rtrim($piwigoRoot, '/').'/galleries';
|
||||
|
||||
try
|
||||
{
|
||||
if (!is_readable($dbConfig)) fail_webdav_reconcile('Piwigo-Datenbankkonfiguration ist nicht lesbar: '.$dbConfig);
|
||||
$conf = array();
|
||||
$prefixeTable = 'piwigo_';
|
||||
require $dbConfig;
|
||||
foreach (array('db_host','db_user','db_password','db_base') as $key)
|
||||
{
|
||||
if (!isset($conf[$key])) fail_webdav_reconcile('Piwigo-Datenbankkonfiguration ist unvollstaendig: '.$key);
|
||||
}
|
||||
|
||||
$db = new mysqli($conf['db_host'], $conf['db_user'], $conf['db_password'], $conf['db_base']);
|
||||
if ($db->connect_errno) fail_webdav_reconcile('Piwigo-Datenbank ist nicht erreichbar: '.$db->connect_error);
|
||||
$db->set_charset('utf8mb4');
|
||||
|
||||
$keyResult = $db->query("SELECT value FROM `{$prefixeTable}config` WHERE param='bratonien_nc_connector_secret' LIMIT 1");
|
||||
if (!$keyResult || !$keyResult->num_rows) fail_webdav_reconcile('Connector-Schluessel wurde nicht gefunden.');
|
||||
$hexKey = trim((string)$keyResult->fetch_assoc()['value']);
|
||||
|
||||
$table = $prefixeTable.'bratonien_tools_nc_connections';
|
||||
$rows = $db->query("SELECT id,name,adapter,config_json,secret_blob FROM `{$table}` ORDER BY id DESC");
|
||||
if (!$rows) fail_webdav_reconcile('Connector-Verbindungen konnten nicht gelesen werden: '.$db->error);
|
||||
|
||||
foreach (array($configDir=>$configDir, $publicSourceRoot=>$publicSourceRoot, $publicGalleryRoot=>$publicGalleryRoot) as $dir=>$unused)
|
||||
{
|
||||
if (!is_dir($dir) && !mkdir($dir, $dir === $configDir ? 0700 : 0755, true)) fail_webdav_reconcile('Runtime-Verzeichnis konnte nicht angelegt werden: '.$dir);
|
||||
}
|
||||
@chmod($configDir, 0700);
|
||||
@chmod($publicSourceRoot, 0755);
|
||||
@chmod($publicGalleryRoot, 0755);
|
||||
|
||||
$known = array();
|
||||
$seenFingerprints = array();
|
||||
|
||||
while ($row = $rows->fetch_assoc())
|
||||
{
|
||||
$id = (int)$row['id'];
|
||||
$config = json_decode((string)$row['config_json'], true);
|
||||
if (!is_array($config)) $config = array();
|
||||
if ((string)$row['adapter'] !== 'remote') continue;
|
||||
if ((string)($config['source_mode'] ?? '') !== 'webdav-placeholder') continue;
|
||||
if (empty($config['parallel_test'])) continue;
|
||||
|
||||
try
|
||||
{
|
||||
$baseUrl = rtrim(trim((string)($config['nextcloud_url'] ?? '')), '/');
|
||||
$roots = isset($config['roots']) && is_array($config['roots']) ? $config['roots'] : array();
|
||||
if ($baseUrl === '') fail_webdav_reconcile('Nextcloud-Adresse fehlt.');
|
||||
if (!$roots) fail_webdav_reconcile('Keine WebDAV-Wurzeln gespeichert.');
|
||||
|
||||
$credentials = decrypt_webdav_credentials((string)$row['secret_blob'], $hexKey);
|
||||
$user = trim($credentials['nextcloud_user']);
|
||||
$password = $credentials['nextcloud_password'];
|
||||
if ($user === '' || $password === '') fail_webdav_reconcile('Nextcloud-Zugangsdaten fehlen.');
|
||||
|
||||
$fingerprint = webdav_source_fingerprint($baseUrl, $user, $roots);
|
||||
if (isset($seenFingerprints[$fingerprint]))
|
||||
{
|
||||
fwrite(STDERR, "NC WebDAV #{$id}: identische Quelle bereits durch Verbindung #".$seenFingerprints[$fingerprint]." abgedeckt; doppelte Runtime wird unterdrueckt.\n");
|
||||
foreach (glob($configDir.'/webdav-connection-'.$id.'.*') ?: array() as $stale) @unlink($stale);
|
||||
webdav_remove_generated_tree($legacyGalleryRoot.'/bratonien-webdav-'.$id, $legacyGalleryRoot);
|
||||
webdav_remove_generated_tree($publicGalleryRoot.'/connection-'.$id, $publicGalleryRoot);
|
||||
continue;
|
||||
}
|
||||
$seenFingerprints[$fingerprint] = $id;
|
||||
$known[$id] = true;
|
||||
|
||||
$stateDir = rtrim((string)($config['state_dir'] ?? ''), '/');
|
||||
if ($stateDir === '') $stateDir = $stateRoot.'/connection-'.$id;
|
||||
if (!is_dir($stateDir) && !mkdir($stateDir, 0750, true)) fail_webdav_reconcile('State-Verzeichnis konnte nicht angelegt werden.');
|
||||
@chmod($stateDir, 0750);
|
||||
|
||||
$legacyDefault = $legacyGalleryRoot.'/bratonien-webdav-'.$id;
|
||||
$galleryRoot = rtrim((string)($config['parallel_gallery_root'] ?? ''), '/');
|
||||
if ($galleryRoot === '' || $galleryRoot === $legacyDefault || strpos($galleryRoot, $legacyGalleryRoot.'/bratonien-webdav-') === 0)
|
||||
{
|
||||
$galleryRoot = $publicGalleryRoot.'/connection-'.$id;
|
||||
}
|
||||
if (!is_dir($galleryRoot) && !mkdir($galleryRoot, 0755, true)) fail_webdav_reconcile('WebDAV-Galeriebereich konnte nicht angelegt werden.');
|
||||
@chmod($galleryRoot, 0755);
|
||||
|
||||
// Alte technische Wrapper unter ./galleries duerfen nicht als Piwigo-Alben auftauchen.
|
||||
webdav_remove_generated_tree($legacyDefault, $legacyGalleryRoot);
|
||||
|
||||
$sourceDir = $publicSourceRoot.'/connection-'.$id;
|
||||
if (!is_dir($sourceDir) && !mkdir($sourceDir, 0755, true)) fail_webdav_reconcile('WebDAV-Platzhalterquelle konnte nicht angelegt werden.');
|
||||
@chmod($sourceDir, 0755);
|
||||
|
||||
$base = $configDir.'/webdav-connection-'.$id;
|
||||
$passwordPath = $base.'.nextcloud-password';
|
||||
$rootsPath = $base.'.roots.tsv';
|
||||
$configPath = $base.'.conf';
|
||||
$statusFile = $stateDir.'/connector-status.json';
|
||||
$mappingFile = $stateDir.'/webdav-map.json';
|
||||
$manifestFile = $stateDir.'/webdav-manifest.tsv';
|
||||
$shadowMapFile = $stateDir.'/webdav-shadow-map.json';
|
||||
|
||||
file_put_contents($passwordPath, $password."\n", LOCK_EX);
|
||||
@chmod($passwordPath, 0600);
|
||||
|
||||
$rootLines = array('# webdav_path<TAB>display_name');
|
||||
foreach ($roots as $root)
|
||||
{
|
||||
$path = trim((string)($root['webdav_path'] ?? ''), '/');
|
||||
$display = trim((string)($root['display_name'] ?? ''));
|
||||
if ($path === '' || $display === '' || preg_match('/[\t\r\n]/', $path.$display)) fail_webdav_reconcile('Eine gespeicherte WebDAV-Wurzel ist ungueltig.');
|
||||
$rootLines[] = $path."\t".$display;
|
||||
}
|
||||
file_put_contents($rootsPath, implode("\n", $rootLines)."\n", LOCK_EX);
|
||||
@chmod($rootsPath, 0600);
|
||||
|
||||
$lines = array(
|
||||
'PIWIGO_ROOT='.webdav_shell_value($piwigoRoot),
|
||||
'CONNECTION_ID='.$id,
|
||||
'SOURCE_MODE=webdav-placeholder',
|
||||
'WEBDAV_BASE_URL='.webdav_shell_value($baseUrl),
|
||||
'WEBDAV_USER='.webdav_shell_value($user),
|
||||
'WEBDAV_PASSWORD_FILE='.webdav_shell_value($passwordPath),
|
||||
'WEBDAV_ROOTS_FILE='.webdav_shell_value($rootsPath),
|
||||
'WEBDAV_SOURCE_DIR='.webdav_shell_value($sourceDir),
|
||||
'WEBDAV_MAPPING_FILE='.webdav_shell_value($mappingFile),
|
||||
'MANIFEST='.webdav_shell_value($manifestFile),
|
||||
'SHADOW_MAP_FILE='.webdav_shell_value($shadowMapFile),
|
||||
'GALLERY_ROOT='.webdav_shell_value($galleryRoot),
|
||||
'STATE_DIR='.webdav_shell_value($stateDir),
|
||||
'STATUS_FILE='.webdav_shell_value($statusFile),
|
||||
'PIWIGO_SYNC_ENABLED=1',
|
||||
);
|
||||
file_put_contents($configPath, implode("\n", $lines)."\n", LOCK_EX);
|
||||
@chmod($configPath, 0600);
|
||||
|
||||
$config['state_dir'] = $stateDir;
|
||||
$config['status_file'] = $statusFile;
|
||||
$config['parallel_gallery_root'] = $galleryRoot;
|
||||
$config['source_fingerprint'] = $fingerprint;
|
||||
$config['runtime'] = array(
|
||||
'mode'=>'parallel-webdav',
|
||||
'config'=>$configPath,
|
||||
'piwigo_sync_enabled'=>true,
|
||||
'reconciled_at'=>date('Y-m-d H:i:s'),
|
||||
);
|
||||
$json = json_encode($config, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
||||
if (is_string($json))
|
||||
{
|
||||
$escaped = $db->real_escape_string($json);
|
||||
$db->query("UPDATE `{$table}` SET config_json='{$escaped}' WHERE id={$id} LIMIT 1");
|
||||
}
|
||||
}
|
||||
catch (Throwable $e)
|
||||
{
|
||||
fwrite(STDERR, "NC WebDAV #{$id}: ".$e->getMessage()."\n");
|
||||
}
|
||||
}
|
||||
|
||||
foreach (glob($configDir.'/webdav-connection-*.conf') ?: array() as $path)
|
||||
{
|
||||
if (!preg_match('/webdav-connection-([0-9]+)\.conf$/', $path, $match)) continue;
|
||||
$id = (int)$match[1];
|
||||
if (isset($known[$id])) continue;
|
||||
foreach (glob($configDir.'/webdav-connection-'.$id.'.*') ?: array() as $stale) @unlink($stale);
|
||||
}
|
||||
|
||||
exit(0);
|
||||
}
|
||||
catch (Throwable $e)
|
||||
{
|
||||
fwrite(STDERR, "NC WebDAV Reconcile: ".$e->getMessage()."\n");
|
||||
exit(1);
|
||||
}
|
||||
@@ -5,19 +5,188 @@ 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 Verbindungen konnten nicht mit der Runtime abgeglichen werden." >&2
|
||||
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-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
|
||||
|
||||
if ! php "$SCRIPT_DIR/cleanup-stale.php"; then
|
||||
echo "NC Connector: verwaiste Laufzeitdateien konnten nicht bereinigt werden." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
configs=("$CONFIG_DIR"/connection-*.conf)
|
||||
webdav_configs=("$CONFIG_DIR"/webdav-connection-*.conf)
|
||||
|
||||
if [[ ${#configs[@]} -eq 0 ]]; then
|
||||
echo "Keine aktiven NC-Connector-Verbindungen konfiguriert."
|
||||
if [[ ${#configs[@]} -eq 0 && ${#webdav_configs[@]} -eq 0 ]]; then
|
||||
echo "Keine NC-Connector-Verbindungen konfiguriert."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
result=0
|
||||
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")"
|
||||
connection_id=""
|
||||
@@ -25,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"
|
||||
|
||||
@@ -44,10 +209,33 @@ for config in "${configs[@]}"; do
|
||||
continue
|
||||
fi
|
||||
|
||||
echo "NC Connector: $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
|
||||
|
||||
205
runtime/sync-webdav.sh
Normal file
205
runtime/sync-webdav.sh
Normal file
@@ -0,0 +1,205 @@
|
||||
#!/usr/bin/env bash
|
||||
set -Eeuo pipefail
|
||||
|
||||
CONFIG_FILE="${PIWIGO_CONFIG:-}"
|
||||
[[ -n "$CONFIG_FILE" && -r "$CONFIG_FILE" ]] || { echo "WebDAV-Konfiguration fehlt: ${CONFIG_FILE:-<leer>}" >&2; exit 1; }
|
||||
|
||||
# shellcheck source=/dev/null
|
||||
source "$CONFIG_FILE"
|
||||
|
||||
: "${PIWIGO_ROOT:?PIWIGO_ROOT fehlt}"
|
||||
: "${CONNECTION_ID:?CONNECTION_ID fehlt}"
|
||||
: "${WEBDAV_BASE_URL:?WEBDAV_BASE_URL fehlt}"
|
||||
: "${WEBDAV_USER:?WEBDAV_USER fehlt}"
|
||||
: "${WEBDAV_PASSWORD_FILE:?WEBDAV_PASSWORD_FILE fehlt}"
|
||||
: "${WEBDAV_ROOTS_FILE:?WEBDAV_ROOTS_FILE fehlt}"
|
||||
: "${WEBDAV_SOURCE_DIR:?WEBDAV_SOURCE_DIR fehlt}"
|
||||
: "${WEBDAV_MAPPING_FILE:?WEBDAV_MAPPING_FILE fehlt}"
|
||||
: "${MANIFEST:?MANIFEST fehlt}"
|
||||
: "${SHADOW_MAP_FILE:?SHADOW_MAP_FILE fehlt}"
|
||||
: "${GALLERY_ROOT:?GALLERY_ROOT fehlt}"
|
||||
: "${STATE_DIR:?STATE_DIR fehlt}"
|
||||
: "${STATUS_FILE:?STATUS_FILE fehlt}"
|
||||
|
||||
[[ "${SOURCE_MODE:-}" == "webdav-placeholder" ]] || { echo "Falscher SOURCE_MODE: ${SOURCE_MODE:-<leer>}" >&2; exit 1; }
|
||||
[[ -r "$WEBDAV_PASSWORD_FILE" ]] || { echo "Nextcloud-Passwortdatei fehlt." >&2; exit 1; }
|
||||
[[ -r "$WEBDAV_ROOTS_FILE" ]] || { echo "WebDAV-Wurzeln fehlen." >&2; exit 1; }
|
||||
|
||||
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
|
||||
LOCK_FILE="$STATE_DIR/webdav-sync.lock"
|
||||
mkdir -p -- "$STATE_DIR"
|
||||
exec 9>"$LOCK_FILE"
|
||||
flock -n 9 || exit 0
|
||||
|
||||
write_status() {
|
||||
local state="$1" message="$2" detail="${3:-}" auth_mode="${4:-webdav}" api_state="${5:-not_run}" api_message="${6:-}" fallback_state="${7:-not_run}" fallback_message="${8:-}"
|
||||
python3 - "$STATUS_FILE" "$PIWIGO_ROOT" "$CONNECTION_ID" "$state" "$message" "$detail" "$auth_mode" "$api_state" "$api_message" "$fallback_state" "$fallback_message" <<'PY'
|
||||
import json, os, sys, tempfile, time
|
||||
(status_file, piwigo_root, connection_id, state, message, detail, auth_mode,
|
||||
api_state, api_message, fallback_state, fallback_message) = sys.argv[1:]
|
||||
payload = {
|
||||
"state": state,
|
||||
"message": message,
|
||||
"timestamp": int(time.time()),
|
||||
"auth_mode": auth_mode,
|
||||
"api": {"state": api_state, "message": api_message},
|
||||
"fallback": {"state": fallback_state, "message": fallback_message},
|
||||
"error_detail": detail if state == "error" else "",
|
||||
}
|
||||
public_file = os.path.join(piwigo_root.rstrip('/'), '_data', 'bratonien-tools', 'nc-connector-status', f'connection-{connection_id}.json')
|
||||
for target in (status_file, public_file):
|
||||
directory = os.path.dirname(target)
|
||||
os.makedirs(directory, exist_ok=True)
|
||||
fd, temporary = tempfile.mkstemp(dir=directory)
|
||||
with os.fdopen(fd, 'w', encoding='utf-8') as handle:
|
||||
json.dump(payload, handle, ensure_ascii=False)
|
||||
handle.write('\n')
|
||||
os.chmod(temporary, 0o644)
|
||||
os.replace(temporary, target)
|
||||
PY
|
||||
}
|
||||
|
||||
compact_output() {
|
||||
tail -n 12 | tr '\n' ' ' | sed 's/[[:space:]]\+/ /g; s/^[[:space:]]//; s/[[:space:]]$//'
|
||||
}
|
||||
|
||||
failure() {
|
||||
local code="$1" command="$2" line="$3"
|
||||
trap - ERR
|
||||
write_status error "WebDAV-Shadow-Tree fehlgeschlagen" "Exit-Code: $code; Zeile: $line; Befehl: $command"
|
||||
exit "$code"
|
||||
}
|
||||
trap 'failure $? "$BASH_COMMAND" "$LINENO"' ERR
|
||||
|
||||
ROOT_ARGS=()
|
||||
while IFS=$'\t' read -r path display_name; do
|
||||
[[ -z "$path" || "$path" == \#* ]] && continue
|
||||
ROOT_ARGS+=(--root "$path")
|
||||
done < "$WEBDAV_ROOTS_FILE"
|
||||
|
||||
[[ ${#ROOT_ARGS[@]} -gt 0 ]] || { write_status error "Keine WebDAV-Wurzeln konfiguriert"; exit 1; }
|
||||
|
||||
python3 "$SCRIPT_DIR/lib/build_webdav_placeholder_source.py" \
|
||||
--base-url "$WEBDAV_BASE_URL" \
|
||||
--user "$WEBDAV_USER" \
|
||||
--password-file "$WEBDAV_PASSWORD_FILE" \
|
||||
"${ROOT_ARGS[@]}" \
|
||||
--source-dir "$WEBDAV_SOURCE_DIR" \
|
||||
--manifest "$MANIFEST" \
|
||||
--mapping "$WEBDAV_MAPPING_FILE"
|
||||
|
||||
python3 "$SCRIPT_DIR/lib/shadow_tree.py" \
|
||||
--manifest "$MANIFEST" \
|
||||
--destination "$GALLERY_ROOT" \
|
||||
--state "$SHADOW_MAP_FILE"
|
||||
|
||||
trap - ERR
|
||||
PREVIEW_CACHE="$PIWIGO_ROOT/_data/bratonien-tools/nc-webdav-preview/connection-$CONNECTION_ID"
|
||||
PREVIEW_OUTPUT=""
|
||||
PREVIEW_EXIT=0
|
||||
if PREVIEW_OUTPUT="$(php "$SCRIPT_DIR/lib/precache-webdav-previews.php" \
|
||||
--mapping="$WEBDAV_MAPPING_FILE" \
|
||||
--base-url="$WEBDAV_BASE_URL" \
|
||||
--user="$WEBDAV_USER" \
|
||||
--password-file="$WEBDAV_PASSWORD_FILE" \
|
||||
--cache-dir="$PREVIEW_CACHE" 2>&1)"; then
|
||||
PREVIEW_EXIT=0
|
||||
else
|
||||
PREVIEW_EXIT=$?
|
||||
fi
|
||||
[[ -z "$PREVIEW_OUTPUT" ]] || printf '%s\n' "$PREVIEW_OUTPUT"
|
||||
if [[ "$PREVIEW_EXIT" -ne 0 ]]; then
|
||||
DETAIL="Exit-Code: $PREVIEW_EXIT"
|
||||
if [[ -n "$PREVIEW_OUTPUT" ]]; then
|
||||
DETAIL+="; Ausgabe: $(printf '%s\n' "$PREVIEW_OUTPUT" | compact_output)"
|
||||
fi
|
||||
write_status error "WebDAV-Vorschaubilder konnten beim Einlesen nicht erzeugt werden" "$DETAIL"
|
||||
exit "$PREVIEW_EXIT"
|
||||
fi
|
||||
|
||||
if [[ "${PIWIGO_SYNC_ENABLED:-0}" == "1" ]]; then
|
||||
PIWIGO_OUTPUT=""
|
||||
PIWIGO_EXIT=0
|
||||
if PIWIGO_OUTPUT="$(php "$SCRIPT_DIR/lib/piwigo-sync.php" \
|
||||
--piwigo-root="$PIWIGO_ROOT" \
|
||||
--connection-id="$CONNECTION_ID" \
|
||||
--base-url="http://127.0.0.1" 2>&1)"; then
|
||||
PIWIGO_EXIT=0
|
||||
else
|
||||
PIWIGO_EXIT=$?
|
||||
fi
|
||||
[[ -z "$PIWIGO_OUTPUT" ]] || printf '%s\n' "$PIWIGO_OUTPUT"
|
||||
|
||||
if [[ "$PIWIGO_EXIT" -ne 0 ]]; then
|
||||
DETAIL="Exit-Code: $PIWIGO_EXIT"
|
||||
if [[ -n "$PIWIGO_OUTPUT" ]]; then
|
||||
DETAIL+="; Ausgabe: $(printf '%s\n' "$PIWIGO_OUTPUT" | compact_output)"
|
||||
fi
|
||||
|
||||
if grep -qi 'Invalid username/password' <<<"$PIWIGO_OUTPUT"; then
|
||||
write_status error \
|
||||
"Piwigo-Fallback fehlgeschlagen: Benutzername oder Passwort ist ungültig" \
|
||||
"$DETAIL" \
|
||||
"fallback" \
|
||||
"not_configured" \
|
||||
"Für diese Verbindung ist keine nutzbare API konfiguriert" \
|
||||
"error" \
|
||||
"Piwigo hat Benutzername oder Passwort des Fallback-Zugangs abgelehnt"
|
||||
elif grep -qi 'Kein gespeicherter Benutzername/Passwort-Fallback\|Kein verbindungseigener Piwigo-Zugang' <<<"$PIWIGO_OUTPUT"; then
|
||||
write_status error \
|
||||
"Piwigo-Zugang fehlt: API und Fallback sind nicht nutzbar" \
|
||||
"$DETAIL" \
|
||||
"failed" \
|
||||
"not_configured" \
|
||||
"Für diese Verbindung ist keine nutzbare API konfiguriert" \
|
||||
"not_configured" \
|
||||
"Kein vollständiger Fallback-Zugang gespeichert"
|
||||
else
|
||||
write_status error "Piwigo-Synchronisierung des WebDAV-Shadow-Trees fehlgeschlagen" "$DETAIL"
|
||||
fi
|
||||
exit "$PIWIGO_EXIT"
|
||||
fi
|
||||
|
||||
DERIVATIVE_OUTPUT=""
|
||||
DERIVATIVE_EXIT=0
|
||||
if DERIVATIVE_OUTPUT="$(php "$SCRIPT_DIR/lib/build-webdav-derivatives.php" \
|
||||
--piwigo-root="$PIWIGO_ROOT" \
|
||||
--connection-id="$CONNECTION_ID" 2>&1)"; then
|
||||
DERIVATIVE_EXIT=0
|
||||
else
|
||||
DERIVATIVE_EXIT=$?
|
||||
fi
|
||||
[[ -z "$DERIVATIVE_OUTPUT" ]] || printf '%s\n' "$DERIVATIVE_OUTPUT"
|
||||
if [[ "$DERIVATIVE_EXIT" -ne 0 ]]; then
|
||||
DETAIL="Exit-Code: $DERIVATIVE_EXIT"
|
||||
if [[ -n "$DERIVATIVE_OUTPUT" ]]; then
|
||||
DETAIL+="; Ausgabe: $(printf '%s\n' "$DERIVATIVE_OUTPUT" | compact_output)"
|
||||
fi
|
||||
write_status error "Piwigo-Derivate für WebDAV-Bilder konnten nicht erzeugt werden" "$DETAIL"
|
||||
exit "$DERIVATIVE_EXIT"
|
||||
fi
|
||||
|
||||
if grep -q 'Piwigo-Synchronisierung per API erfolgreich' <<<"$PIWIGO_OUTPUT"; then
|
||||
write_status ok \
|
||||
"WebDAV eingelesen, Piwigo synchronisiert und Derivate erzeugt" \
|
||||
"" \
|
||||
"api" \
|
||||
"ok" \
|
||||
"Piwigo-API erfolgreich" \
|
||||
"not_needed" \
|
||||
"Fallback wurde nicht benötigt"
|
||||
elif grep -q 'Piwigo-Datenbanksynchronisierung per Benutzername/Passwort-Fallback erfolgreich' <<<"$PIWIGO_OUTPUT"; then
|
||||
write_status ok \
|
||||
"WebDAV eingelesen, Piwigo über Fallback synchronisiert und Derivate erzeugt" \
|
||||
"" \
|
||||
"fallback" \
|
||||
"not_used" \
|
||||
"API war nicht nutzbar" \
|
||||
"ok" \
|
||||
"Benutzername/Passwort-Fallback erfolgreich"
|
||||
else
|
||||
write_status ok "WebDAV eingelesen, Piwigo synchronisiert und Derivate erzeugt"
|
||||
fi
|
||||
else
|
||||
write_status ok "WebDAV eingelesen und Vorschaubilder erzeugt; Registrierung erfolgt über den bestehenden produktiven Piwigo-Sync"
|
||||
fi
|
||||
@@ -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,10 +54,35 @@
|
||||
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);applyMode();
|
||||
if(!dialog)return;
|
||||
if(typeof dialog.showModal==='function'&&!dialog.open)dialog.showModal();
|
||||
else dialog.setAttribute('open','open');
|
||||
}
|
||||
function resetServer(){
|
||||
var pwgToken=token();
|
||||
if(!pwgToken)return Promise.reject(new Error('CSRF token missing'));
|
||||
@@ -59,14 +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){
|
||||
if(resetBusy)return;event.preventDefault();event.stopImmediatePropagation();resetBusy=true;setOpen(true);
|
||||
resetServer().then(function(){window.location.reload();}).catch(function(){setOpen(false);resetBusy=false;});
|
||||
event.preventDefault();event.stopImmediatePropagation();clearMode();showWizard();
|
||||
},true);
|
||||
}
|
||||
if(closeButton){
|
||||
@@ -75,12 +105,115 @@
|
||||
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);
|
||||
[].slice.call(dialog.querySelectorAll('form[data-bratonien-wizard-form]')).forEach(function(form){
|
||||
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';
|
||||
var pollTimer=null;
|
||||
|
||||
function valueNodeForLabel(labelText){
|
||||
var labels=[].slice.call(section.querySelectorAll('.bratonien-label'));
|
||||
@@ -108,21 +241,28 @@
|
||||
var nextRunNode=valueNodeForLabel('Nächster Lauf');
|
||||
var lastResultNode=lastResultValueNode();
|
||||
|
||||
function render(data){
|
||||
if(lastRunNode&&typeof data.last_run_label==='string'&&data.last_run_label!=='')lastRunNode.textContent=data.last_run_label;
|
||||
if(nextRunNode&&typeof data.next_run_label==='string'&&data.next_run_label!=='')nextRunNode.textContent=data.next_run_label;
|
||||
if(lastResultNode&&typeof data.message==='string'&&data.message!=='')lastResultNode.textContent=data.message;
|
||||
}
|
||||
|
||||
function poll(){
|
||||
fetch(endpoint+'?_='+Date.now(),{credentials:'same-origin',cache:'no-store'})
|
||||
fetch(endpoint+'?_='+Date.now(),{credentials:'same-origin',cache:'no-store',headers:{'Accept':'application/json'}})
|
||||
.then(function(response){if(!response.ok)throw new Error('HTTP '+response.status);return response.json();})
|
||||
.then(function(data){
|
||||
if(lastRunNode&&data.last_run_label)lastRunNode.textContent=data.last_run_label;
|
||||
if(nextRunNode&&data.next_run_label)nextRunNode.textContent=data.next_run_label;
|
||||
if(lastResultNode&&typeof data.message==='string'&&data.message!=='')lastResultNode.textContent=data.message;
|
||||
})
|
||||
.then(render)
|
||||
.catch(function(){});
|
||||
}
|
||||
|
||||
poll();window.setInterval(poll,5000);
|
||||
function schedule(){
|
||||
if(pollTimer)window.clearInterval(pollTimer);
|
||||
pollTimer=window.setInterval(poll,5000);
|
||||
}
|
||||
|
||||
poll();schedule();
|
||||
}
|
||||
|
||||
function initAll(){initBratonienTabs();initNCWizardLifecycle();initNCConnectorPolling();}
|
||||
function initAll(){initBratonienTabs();initNCWizardLifecycle();initNCConnectionEditing();initNCConnectorPolling();}
|
||||
if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',initAll);else initAll();
|
||||
})();
|
||||
</script>
|
||||
|
||||
173
webdav-image.php
Normal file
173
webdav-image.php
Normal file
@@ -0,0 +1,173 @@
|
||||
<?php
|
||||
define('PHPWG_ROOT_PATH', '../../');
|
||||
include_once(PHPWG_ROOT_PATH.'include/common.inc.php');
|
||||
|
||||
if (!defined('BRATONIEN_TOOLS_PATH'))
|
||||
{
|
||||
define('BRATONIEN_TOOLS_ID', basename(__DIR__));
|
||||
define('BRATONIEN_TOOLS_PATH', PHPWG_ROOT_PATH.'plugins/'.BRATONIEN_TOOLS_ID.'/');
|
||||
}
|
||||
require_once(BRATONIEN_TOOLS_PATH.'include/webdav_image_runtime.inc.php');
|
||||
|
||||
function bratonien_tools_webdav_image_abort($status, $message)
|
||||
{
|
||||
http_response_code((int)$status);
|
||||
header('Content-Type: text/plain; charset=utf-8');
|
||||
header('Cache-Control: no-store');
|
||||
echo $message;
|
||||
exit;
|
||||
}
|
||||
|
||||
function bratonien_tools_webdav_image_decrypt_secret($blob, $hex_key)
|
||||
{
|
||||
$hex_key = trim((string)$hex_key);
|
||||
if (!preg_match('/^[a-f0-9]{64}$/', $hex_key)) return null;
|
||||
$outer = base64_decode(trim((string)$blob), true);
|
||||
$payload = is_string($outer) ? json_decode($outer, true) : null;
|
||||
if (!is_array($payload) || (int)($payload['v'] ?? 0) !== 1) return null;
|
||||
$iv = base64_decode((string)($payload['iv'] ?? ''), true);
|
||||
$tag = base64_decode((string)($payload['tag'] ?? ''), true);
|
||||
$cipher = base64_decode((string)($payload['data'] ?? ''), true);
|
||||
if (!is_string($iv) || !is_string($tag) || !is_string($cipher)) return null;
|
||||
$plain = openssl_decrypt($cipher, 'aes-256-gcm', hex2bin($hex_key), OPENSSL_RAW_DATA, $iv, $tag);
|
||||
if ($plain === false) return null;
|
||||
$decoded = json_decode((string)$plain, true);
|
||||
return is_array($decoded) ? $decoded : null;
|
||||
}
|
||||
|
||||
function bratonien_tools_webdav_image_quote_path($path)
|
||||
{
|
||||
$parts = array_values(array_filter(explode('/', trim((string)$path, '/')), 'strlen'));
|
||||
return implode('/', array_map('rawurlencode', $parts));
|
||||
}
|
||||
|
||||
$image_id = (int)($_GET['id'] ?? 0);
|
||||
if ($image_id < 1) bratonien_tools_webdav_image_abort(400, 'Bild-ID fehlt.');
|
||||
|
||||
$permission_condition = get_sql_condition_FandF(array('forbidden_categories'=>'category_id'), null, true);
|
||||
$access_result = pwg_query('SELECT 1 FROM '.IMAGE_CATEGORY_TABLE.' WHERE image_id='.$image_id.' AND '.$permission_condition.' LIMIT 1');
|
||||
if (!pwg_db_num_rows($access_result)) bratonien_tools_webdav_image_abort(403, 'Kein Zugriff auf dieses Bild.');
|
||||
|
||||
$source = bratonien_tools_webdav_image_source_info($image_id);
|
||||
if (!$source) bratonien_tools_webdav_image_abort(404, 'Keine WebDAV-Quelle für dieses Bild gefunden.');
|
||||
|
||||
if (!empty($_GET['preview']))
|
||||
{
|
||||
$preview = bratonien_tools_webdav_preview_path($source);
|
||||
if ($preview)
|
||||
{
|
||||
$mtime = @filemtime($preview) ?: time();
|
||||
$etag = sha1($preview.'|'.$mtime.'|'.(@filesize($preview) ?: 0));
|
||||
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');
|
||||
header('X-Content-Type-Options: nosniff');
|
||||
$client_etag = trim((string)($_SERVER['HTTP_IF_NONE_MATCH'] ?? ''), " \t\r\n\"");
|
||||
if ($client_etag !== '' && hash_equals($etag, $client_etag))
|
||||
{
|
||||
http_response_code(304);
|
||||
exit;
|
||||
}
|
||||
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'HEAD') readfile($preview);
|
||||
exit;
|
||||
}
|
||||
}
|
||||
|
||||
$table = $GLOBALS['prefixeTable'].'bratonien_tools_nc_connections';
|
||||
$result = pwg_query('SELECT config_json, secret_blob FROM `'.$table.'` WHERE id='.(int)$source['connection_id'].' LIMIT 1');
|
||||
if (!pwg_db_num_rows($result)) bratonien_tools_webdav_image_abort(404, 'WebDAV-Verbindung nicht gefunden.');
|
||||
$row = pwg_db_fetch_assoc($result);
|
||||
$config = json_decode((string)$row['config_json'], true);
|
||||
if (!is_array($config)) bratonien_tools_webdav_image_abort(500, 'WebDAV-Konfiguration ist ungültig.');
|
||||
|
||||
$key_result = pwg_query("SELECT value FROM ".$GLOBALS['prefixeTable']."config WHERE param='bratonien_nc_connector_secret' LIMIT 1");
|
||||
if (!pwg_db_num_rows($key_result)) bratonien_tools_webdav_image_abort(500, 'Connector-Schlüssel fehlt.');
|
||||
$key_row = pwg_db_fetch_assoc($key_result);
|
||||
$credentials = bratonien_tools_webdav_image_decrypt_secret((string)$row['secret_blob'], (string)$key_row['value']);
|
||||
if (!is_array($credentials)) bratonien_tools_webdav_image_abort(500, 'WebDAV-Zugangsdaten konnten nicht gelesen werden.');
|
||||
|
||||
$base_url = rtrim((string)($config['nextcloud_url'] ?? ''), '/');
|
||||
$user = trim((string)($credentials['nextcloud_user'] ?? ''));
|
||||
$password = (string)($credentials['nextcloud_password'] ?? '');
|
||||
$webdav_path = trim((string)$source['webdav_path'], '/');
|
||||
if ($base_url === '' || $user === '' || $password === '' || $webdav_path === '')
|
||||
{
|
||||
bratonien_tools_webdav_image_abort(500, 'WebDAV-Bildquelle ist unvollständig.');
|
||||
}
|
||||
|
||||
$etag = trim((string)($source['etag'] ?? ''));
|
||||
if ($etag !== '')
|
||||
{
|
||||
header('ETag: "'.str_replace('"', '', $etag).'"');
|
||||
$client_etag = trim((string)($_SERVER['HTTP_IF_NONE_MATCH'] ?? ''), " \t\r\n\"");
|
||||
if ($client_etag !== '' && hash_equals($etag, $client_etag))
|
||||
{
|
||||
http_response_code(304);
|
||||
exit;
|
||||
}
|
||||
}
|
||||
header('Cache-Control: private, max-age=300, must-revalidate');
|
||||
header('X-Content-Type-Options: nosniff');
|
||||
|
||||
$url = $base_url.'/remote.php/dav/files/'.rawurlencode($user).'/'.bratonien_tools_webdav_image_quote_path($webdav_path);
|
||||
$ch = curl_init($url);
|
||||
$options = array(
|
||||
CURLOPT_FOLLOWLOCATION => false,
|
||||
CURLOPT_CONNECTTIMEOUT => 10,
|
||||
CURLOPT_TIMEOUT => 120,
|
||||
CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
|
||||
CURLOPT_USERPWD => $user.':'.$password,
|
||||
CURLOPT_RETURNTRANSFER => false,
|
||||
CURLOPT_FAILONERROR => false,
|
||||
CURLOPT_USERAGENT => 'Bratonien-Tools-WebDAV-Image/0.9.6.1',
|
||||
CURLOPT_HEADERFUNCTION => function($ch, $line)
|
||||
{
|
||||
$length = strlen($line);
|
||||
$trimmed = trim($line);
|
||||
if ($trimmed === '') return $length;
|
||||
if (preg_match('#^HTTP/\S+\s+([0-9]{3})#i', $trimmed, $m))
|
||||
{
|
||||
http_response_code((int)$m[1]);
|
||||
return $length;
|
||||
}
|
||||
$colon = strpos($line, ':');
|
||||
if ($colon === false) return $length;
|
||||
$name = strtolower(trim(substr($line, 0, $colon)));
|
||||
$value = trim(substr($line, $colon + 1));
|
||||
if (in_array($name, array('content-type','content-length','content-range','accept-ranges','last-modified'), true))
|
||||
{
|
||||
header($name.': '.$value, true);
|
||||
}
|
||||
return $length;
|
||||
},
|
||||
CURLOPT_WRITEFUNCTION => function($ch, $data)
|
||||
{
|
||||
echo $data;
|
||||
return strlen($data);
|
||||
},
|
||||
);
|
||||
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'] ?? 'GET') === 'HEAD')
|
||||
{
|
||||
$options[CURLOPT_NOBODY] = true;
|
||||
}
|
||||
curl_setopt_array($ch, $options);
|
||||
$ok = curl_exec($ch);
|
||||
$errno = curl_errno($ch);
|
||||
$http = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
curl_close($ch);
|
||||
|
||||
if ($ok === false || $errno !== 0)
|
||||
{
|
||||
if (!headers_sent()) bratonien_tools_webdav_image_abort(502, 'Nextcloud-Bild konnte nicht geladen werden.');
|
||||
exit;
|
||||
}
|
||||
if ($http < 200 || $http >= 400)
|
||||
{
|
||||
exit;
|
||||
}
|
||||
Reference in New Issue
Block a user