Compare commits

..

553 Commits

Author SHA1 Message Date
Terranom674
157c6724ea Remove GitHub Actions workflow 2026-09-08 10:12:37 +02:00
Terranom674
bfc1a679db Bump version for public watermark default 2026-09-06 23:04:57 +02:00
Terranom674
a6a2f65f72 Let default public profile inherit base watermark file 2026-09-06 23:04:38 +02:00
Terranom674
940a5e3124 Make public albums watermarked by default 2026-09-06 23:04:15 +02:00
Terranom674
1a119aeb70 Bump Bratonien Tools to 0.9.7.1.50 2026-09-06 22:48:15 +02:00
Terranom674
a99aee3bcd Recover from false connector lock state before cache warmup 2026-09-06 22:48:00 +02:00
Terranom674
de193ca491 Only defer cache for an actually active connector service 2026-09-06 22:47:14 +02:00
Terranom674
51e864060b Bump Bratonien Tools to 0.9.7.1.49 2026-09-06 22:32:24 +02:00
Terranom674
c10c188587 Discard stale legacy connector wait states 2026-09-06 22:32:02 +02:00
Terranom674
ac0be6dcf7 Make every connector deferral resumable 2026-09-06 22:31:24 +02:00
Terranom674
c4813161cd Bump Bratonien Tools to 0.9.7.1.48 2026-09-06 22:30:36 +02:00
Terranom674
d97c828066 Resume cache warmup after connector sync instead of stalling 2026-09-06 22:30:19 +02:00
Terranom674
1cff325e3c Resume deferred cache worker after connector sync 2026-09-06 22:29:55 +02:00
Terranom674
776c5842ca Bump Bratonien Tools to 0.9.7.1.47 2026-09-06 21:57:24 +02:00
Terranom674
a5de1209d9 Treat missing WebDAV dimensions as non-fatal metadata 2026-09-06 21:57:09 +02:00
Terranom674
6cb6cd29e2 Bump Bratonien Tools to 0.9.7.1.46 2026-09-06 21:55:16 +02:00
Terranom674
d50cdaaccd Preserve WebDAV scan error details in connector status 2026-09-06 21:54:56 +02:00
Terranom674
65cfc0ae97 Revert unrelated sudo bridge change 2026-09-06 21:54:12 +02:00
Terranom674
6a985219e9 Restore complete plugin bootstrap for 0.9.7.1.45 2026-09-06 21:49:27 +02:00
Terranom674
8149793149 Bump Bratonien Tools to 0.9.7.1.45 2026-09-06 21:49:09 +02:00
Terranom674
36bb76f97e Provision narrow sudo bridge for manual NC sync 2026-09-06 21:48:55 +02:00
Terranom674
675815e7c0 Bump Bratonien Tools to 0.9.7.1.44 2026-09-06 21:45:47 +02:00
Terranom674
e5fb8ad90a Run manual NC sync through privileged system service 2026-09-06 21:45:18 +02:00
Terranom674
38bff89484 Keep empty WebDAV mappings valid for worker pruning 2026-09-06 21:12:38 +02:00
Terranom674
3102a3a3f5 Bump plugin version to 0.9.7.1.43 2026-09-06 21:11:20 +02:00
Terranom674
6e1cf27ef1 Allow empty WebDAV metadata after root removal 2026-09-06 21:10:45 +02:00
Terranom674
3af01bc812 Clean removed WebDAV images after Piwigo sync 2026-09-06 21:10:26 +02:00
Terranom674
e58ebc5538 Make WebDAV orphan cleanup continuous 2026-09-06 21:09:58 +02:00
Terranom674
eb002b007f Handle removed WebDAV roots without blocking sync 2026-09-06 21:09:39 +02:00
Terranom674
6983a98875 Keep WebDAV cancel signals until worker guards are secured 2026-09-05 23:43:17 +02:00
Terranom674
9f8a2569b2 Bump version for serialized cache clearing 2026-09-05 23:42:39 +02:00
Terranom674
5a9980de24 Serialize cache clear against all cache workers 2026-09-05 23:42:07 +02:00
Terranom674
50f4343029 Include derivative pipeline version in worker stage signature 2026-09-05 23:32:50 +02:00
Terranom674
bd51c27f5b Refresh presentation cache when watermark engine changes 2026-09-05 23:32:17 +02:00
Terranom674
7dc8348fd0 Version WebDAV derivative generation state for geometry repair 2026-09-05 23:31:32 +02:00
Terranom674
0fa552285e Refresh previews after active watermark profile edits 2026-09-05 23:30:47 +02:00
Terranom674
5d995dcca1 Refresh previews after global watermark rule changes 2026-09-05 23:30:23 +02:00
Terranom674
c06b9fc476 Refresh affected previews after album watermark rule changes 2026-09-05 23:30:06 +02:00
Terranom674
c96046b0ca Wire presentation refresh and bump plugin version 2026-09-05 23:29:46 +02:00
Terranom674
d039416dc5 Correct source orientation before Piwigo derivative generation 2026-09-05 23:29:21 +02:00
Terranom674
f9aa1f1a68 Resolve watermark endpoint from active plugin directory 2026-09-05 23:28:49 +02:00
Terranom674
15059f5b68 Add asynchronous Piwigo preview presentation refresh worker 2026-09-05 23:28:34 +02:00
Terranom674
136972b0eb Add local CLI caller for Bratonien watermark cache 2026-09-05 23:28:05 +02:00
Terranom674
30967247c0 Add queued Piwigo presentation refresh orchestration 2026-09-05 23:27:53 +02:00
Terranom674
6826963712 Bump version for frontend QR inventory 2026-09-05 23:05:48 +02:00
Terranom674
dc01294bdb Show QR inventory on public upload page 2026-09-05 23:05:24 +02:00
Terranom674
30b5207c2b Bump Bratonien Tools version for QR batch management 2026-09-05 23:03:10 +02:00
Terranom674
48ed46b1f0 Add QR completeness grid and batch ZIP actions 2026-09-05 23:02:45 +02:00
Terranom674
4dfc1c871c Add QR availability matrix and batch download data 2026-09-05 23:02:08 +02:00
Terranom674
6ccc61eb40 Add administrator QR code batch ZIP downloads 2026-09-05 23:01:38 +02:00
Terranom674
2f976aa9ed Bump plugin version for friendship code upload 2026-09-05 17:30:10 +02:00
Terranom674
a0fa4dfd1a Extend public upload with personal friendship codes 2026-09-05 17:29:44 +02:00
Terranom674
839683a260 Add friendship code management to QR upload admin 2026-09-05 17:28:55 +02:00
Terranom674
92724aa9a2 Expose friendship codes in QR upload administration 2026-09-05 17:28:30 +02:00
Terranom674
e7b0ecd85d Register friendship code administration actions 2026-09-05 17:27:59 +02:00
Terranom674
11d2b85948 Add protected friendship code preview and download endpoint 2026-09-05 17:27:38 +02:00
Terranom674
05a5013b8a Add personal friendship code upload storage and administration 2026-09-05 17:27:27 +02:00
Terranom674
acbf316f58 Bump Bratonien Tools version for QR downloads 2026-09-05 16:22:16 +02:00
Terranom674
930399c847 Add QR upload download action in admin 2026-09-05 16:21:54 +02:00
Terranom674
a441ad2991 Add admin download mode for QR uploads 2026-09-05 16:21:34 +02:00
Terranom674
d0f13a6d1f Bump version for QR upload management 2026-09-05 16:18:26 +02:00
Terranom674
efff4360f7 Rename QR admin tab 2026-09-05 16:18:01 +02:00
Terranom674
6cfcfd624e Add QR upload management to admin 2026-09-05 16:17:37 +02:00
Terranom674
7fb3969647 Register QR upload delete action 2026-09-05 16:17:12 +02:00
Terranom674
d006217660 Add QR upload administration and deletion 2026-09-05 16:16:52 +02:00
Terranom674
3662bdefc2 Add admin-only QR upload preview endpoint 2026-09-05 16:16:15 +02:00
Terranom674
3d66bd1137 Move customer QR upload out of Discover into root frontend navigation 2026-09-05 16:02:09 +02:00
Terranom674
21cbe59b55 Expose customer QR upload as top-level frontend menu item 2026-09-05 16:01:33 +02:00
Terranom674
420ec47a51 Expose customer QR upload in public Piwigo menu 2026-09-05 15:56:32 +02:00
Terranom674
0c8065a01c Bump Bratonien Tools to 0.9.7.1.33 2026-09-05 15:51:20 +02:00
Terranom674
7015d822cd Show fixed customer QR year capacities in admin 2026-09-05 15:50:53 +02:00
Terranom674
1c1d29af07 Restrict customer QR upload to configured yearly ranges 2026-09-05 15:50:41 +02:00
Terranom674
074a74af1f Limit customer QR years and yearly code ranges 2026-09-05 15:50:11 +02:00
Terranom674
fa86adc1d2 Keep QR batch result numbers isolated per file 2026-09-05 15:45:51 +02:00
Terranom674
289eea396e Harden customer QR batch form validation 2026-09-05 15:45:12 +02:00
Terranom674
a386c71c3c Bump Bratonien Tools to 0.9.7.1.32 2026-09-05 15:43:48 +02:00
Terranom674
9a4d39af1a Add customer QR admin tab 2026-09-05 15:43:26 +02:00
Terranom674
958c9242ff Expose customer QR upload administration 2026-09-05 15:43:04 +02:00
Terranom674
8d5e99389c Register customer QR upload settings 2026-09-05 15:42:32 +02:00
Terranom674
5a35244029 Add customer QR upload database table 2026-09-05 15:42:14 +02:00
Terranom674
d87c395be4 Add customer QR upload administration 2026-09-05 15:41:56 +02:00
Terranom674
e8cf6cc6c8 Add public customer QR upload form 2026-09-05 15:41:45 +02:00
Terranom674
3d654d30cf Add customer QR upload module 2026-09-05 15:41:11 +02:00
Terranom674
b9140103ec Add legal links to Piwigo footer 2026-09-04 22:04:38 +02:00
Terranom674
86a2a0fbec Bump Bratonien Tools version to 0.9.7.1.30 2026-09-03 23:20:45 +02:00
Terranom674
c058e48fb0 Keep partial WebDAV cache runs resumable instead of global error 2026-09-03 23:20:25 +02:00
Terranom674
d20be6a39a Make WebDAV warmup batch cancellation and connector deferral deterministic 2026-09-03 23:19:42 +02:00
Terranom674
3d7114d782 Bump Bratonien Tools to 0.9.7.1.29 2026-09-03 23:15:16 +02:00
Terranom674
c20795d108 Treat connector deferrals as waiting instead of cache errors 2026-09-03 23:14:41 +02:00
Terranom674
2863a51acf Do not collapse WebDAV warmup on connector lock deferrals 2026-09-03 23:14:08 +02:00
Terranom674
ec8036d226 Bump Bratonien Tools to 0.9.7.1.28 2026-09-03 23:04:28 +02:00
Terranom674
0094942f68 Expose WebDAV cancelling and cancelled states 2026-09-03 23:04:05 +02:00
Terranom674
12834041be Route cache cancel to combined local and WebDAV handler 2026-09-03 23:03:33 +02:00
Terranom674
1f2651b8f0 Wire combined cache cancel to WebDAV worker 2026-09-03 23:03:14 +02:00
Terranom674
791d67929b Make WebDAV cache cancel stop after current batch 2026-09-03 23:02:37 +02:00
Terranom674
ceea3b5483 Bump version for incremental WebDAV cache build 2026-09-03 22:55:10 +02:00
Terranom674
11c136439d Make cache build incremental from worker index 2026-09-03 22:54:51 +02:00
Terranom674
953bc92f1b Bump Bratonien Tools patch version to 0.9.7.1.26 2026-09-03 22:45:50 +02:00
Terranom674
7106765be6 Resume interrupted WebDAV cache builds without resetting completed stages 2026-09-03 22:45:27 +02:00
Terranom674
e0efb72a98 Bump version to 0.9.7.1.25 2026-09-03 22:39:50 +02:00
Terranom674
1ae9f2acc4 Dispatch priority warmup only for changed WebDAV content 2026-09-03 22:39:28 +02:00
Terranom674
c819861c91 Only prioritize WebDAV warmup when mapping changed 2026-09-03 22:39:14 +02:00
Terranom674
7fdb022126 Bump Bratonien Tools to 0.9.7.1.24 2026-09-03 22:29:16 +02:00
Terranom674
73de6a7a82 Fix WebDAV cache progress aggregation 2026-09-03 22:28:36 +02:00
Terranom674
00ae99e2a0 Bump version to 0.9.7.1.23 2026-09-03 22:08:36 +02:00
Terranom674
85fa5aeeb5 Preserve worker failure status and surface real failing sources 2026-09-03 22:08:18 +02:00
Terranom674
78f34fceb9 Bump patch version to 0.9.7.1.22 2026-09-03 20:41:24 +02:00
Terranom674
e790bff498 Prepare WebDAV lock files for Piwigo worker 2026-09-03 20:40:55 +02:00
Terranom674
a2b1d31f8c Store WebDAV worker index in Piwigo local state 2026-09-03 20:39:31 +02:00
Terranom674
59792988da Bump patch for WebDAV lock diagnostic 2026-09-03 20:35:10 +02:00
Terranom674
5222d12a5f Show WebDAV worker lock state in scan diagnostic 2026-09-03 20:34:45 +02:00
Terranom674
65316043d8 Extend WebDAV scan diagnostic with worker lock check 2026-09-03 20:34:33 +02:00
Terranom674
345ece63f3 Bump patch version for WebDAV scan diagnostic 2026-09-03 19:00:18 +02:00
Terranom674
b2d87d4033 Add WebDAV scan diagnostic button 2026-09-03 18:59:54 +02:00
Terranom674
424dff783f Register WebDAV scan diagnostic 2026-09-03 18:59:41 +02:00
Terranom674
621b4d8bfc Add admin handler for WebDAV scan diagnostic 2026-09-03 18:59:22 +02:00
Terranom674
5b89b453e4 Add read-only WebDAV shadow scan diagnostic 2026-09-03 18:59:11 +02:00
Terranom674
2a774dfb75 Bump patch version to 0.9.7.1.19 2026-09-03 18:53:33 +02:00
Terranom674
2f4345a9b6 Run manual WebDAV cache workers in dispatcher process 2026-09-03 18:52:57 +02:00
Terranom674
b4fef28869 Bump patch version to 0.9.7.1.18 2026-09-03 18:49:02 +02:00
Terranom674
006c62d154 Require current WebDAV worker completion before cache is marked done 2026-09-03 18:48:19 +02:00
Terranom674
db5f330e8e Invalidate WebDAV worker completion when cache is cleared 2026-09-03 18:47:50 +02:00
Terranom674
6d0df4acaa Fix WebDAV rebuild lifecycle and stale completion state 2026-09-03 18:47:30 +02:00
Terranom674
1dec85bbd0 Bump patch version to 0.9.7.1.17 2026-09-03 18:40:25 +02:00
Terranom674
e9cb1ce1f3 Show shadow-tree driven WebDAV worker status 2026-09-03 18:40:02 +02:00
Terranom674
2535040557 Dispatch WebDAV worker without legacy Piwigo state checks 2026-09-03 18:39:33 +02:00
Terranom674
4f4fd88a6a Make WebDAV worker index runtime-only and auto-built 2026-09-03 18:38:57 +02:00
Terranom674
dbcceb05c6 Drive WebDAV cache worker only from shadow tree and own index 2026-09-03 18:38:18 +02:00
Terranom674
ae5bc5c45b Add Piwigo-owned derivative request bridge for shadow paths 2026-09-03 18:37:11 +02:00
Terranom674
acfebe07fc Decouple WebDAV source index from Piwigo image index 2026-09-03 18:36:43 +02:00
Terranom674
bab54eccb9 Document cache worker handoff after architecture dead end 2026-09-03 18:29:41 +02:00
Terranom674
81e0a9e185 Bump patch version for WebDAV-only cache build routing 2026-09-03 18:26:58 +02:00
Terranom674
116b710d5d Skip legacy cache worker when only WebDAV sources exist 2026-09-03 18:26:42 +02:00
Terranom674
e2f687237e Bump patch version for automatic source-index initialization 2026-09-03 17:58:28 +02:00
Terranom674
479cdbc473 Allow warmup enable before source index exists 2026-09-03 17:58:06 +02:00
Terranom674
a20f9588f0 Bump patch version for combined cache status display 2026-09-03 17:56:45 +02:00
Terranom674
e831301650 Fix PHP branch syntax in combined cache status 2026-09-03 17:56:17 +02:00
Terranom674
030d0c1be7 Show combined cache rebuild phases in status 2026-09-03 17:55:50 +02:00
Terranom674
8c8d131fbb Explain independent WebDAV source index in admin 2026-09-03 17:46:43 +02:00
Terranom674
9f80c4aa97 Treat source index as current only after both stages 2026-09-03 17:46:25 +02:00
Terranom674
813c3d36a8 Bump patch version for independent WebDAV source index 2026-09-03 17:45:48 +02:00
Terranom674
3ff8c4f547 Use source index as WebDAV warmup baseline 2026-09-03 17:45:25 +02:00
Terranom674
6783974c7d Separate WebDAV source index from Piwigo cache state 2026-09-03 17:45:01 +02:00
Terranom674
ac6353b050 Add independent WebDAV source index 2026-09-03 17:43:46 +02:00
Terranom674
43178483e5 Exclude WebDAV images from legacy cache worker totals 2026-09-03 15:57:22 +02:00
Terranom674
5b0f7f93af Bump patch version to 0.9.7.1.12 2026-09-03 15:51:28 +02:00
Terranom674
5076a76d29 Route manual cache build through combined WebDAV rebuild 2026-09-03 15:51:08 +02:00
Terranom674
7094288534 Coordinate manual cache build with WebDAV rebuild 2026-09-03 15:48:53 +02:00
Terranom674
f7d0959eba Support full WebDAV cache rebuilds through Piwigo 2026-09-03 15:48:28 +02:00
Terranom674
2a96d0165c Add explicit WebDAV cache rebuild launcher 2026-09-03 15:47:17 +02:00
Terranom674
b6621d36db Add explicit WebDAV rebuild dispatch mode 2026-09-03 15:46:53 +02:00
Terranom674
41ffa29af7 Handle symlinks safely while removing detached cache trees 2026-09-03 15:45:54 +02:00
Terranom674
abd0cc5d21 Bump patch version for atomic cache clear 2026-09-03 14:46:11 +02:00
Terranom674
fced2eac49 Route cache clear button through atomic cutover 2026-09-03 14:45:43 +02:00
Terranom674
14aac0d7a4 Make cache clear use atomic directory cutover 2026-09-03 14:45:24 +02:00
Terranom674
3f2c1f8ff7 Load strict WebDAV derivative cache validator 2026-09-03 14:42:13 +02:00
Terranom674
7310d70b93 Add strict WebDAV derivative cache validation 2026-09-03 14:41:44 +02:00
Terranom674
ae73840d40 Bump patch version to 0.9.7.1.10 2026-09-03 14:39:56 +02:00
Terranom674
a0195b499c Keep legacy cache builder away from WebDAV placeholders 2026-09-03 14:39:26 +02:00
Terranom674
0372a74ae9 Bump patch version to 0.9.7.1.9 2026-09-03 14:33:05 +02:00
Terranom674
dbcc55351c Fix Piwigo root resolution in warmup dispatcher 2026-09-03 14:32:24 +02:00
Terranom674
f02d2f0239 Fix Piwigo root resolution in derivative caller 2026-09-03 14:31:54 +02:00
Terranom674
2617175158 Fix Piwigo root resolution in WebDAV warmup audit 2026-09-03 14:31:44 +02:00
Terranom674
362d24b89a Require warmup baseline before enabling automation 2026-09-03 14:19:48 +02:00
Terranom674
459f233b57 Refresh WebDAV mapping inside cache warmup workers 2026-09-03 14:19:03 +02:00
Terranom674
1368c8e5b7 Queue sync warmup until active worker yields 2026-09-03 14:18:04 +02:00
Terranom674
662d22c533 Queue priority warmup behind an active worker 2026-09-03 14:17:40 +02:00
Terranom674
f9188ac5db Remove obsolete full-run warmup guard 2026-09-03 14:17:14 +02:00
Terranom674
5aab3e52ed Route on-demand derivatives through sync guard 2026-09-03 14:17:03 +02:00
Terranom674
6bd14d2b9b Guard on-demand derivatives against connector tree swaps 2026-09-03 14:16:36 +02:00
Terranom674
a63d5fe3c3 Allow connector sync between warmup batches 2026-09-03 14:15:59 +02:00
Terranom674
84456de512 Preempt stage two warmup safely between batches 2026-09-03 14:15:23 +02:00
Terranom674
54a9c97525 Preserve warmup worker exit codes in guard 2026-09-03 12:58:54 +02:00
Terranom674
dfd180c11e Replay queued sync priority after active warmup 2026-09-03 12:56:56 +02:00
Terranom674
714c487ef2 Signal priority sync work to an active warmup 2026-09-03 12:54:52 +02:00
Terranom674
ccefc72c25 Document WebDAV cache warmup patch safety model 2026-09-03 12:53:42 +02:00
Terranom674
7e05e4e8a1 Remove superseded WebDAV warmup prototype 2026-09-03 12:53:08 +02:00
Terranom674
fae2daff4b Bump patch version to 0.9.7.1.8 2026-09-03 12:52:09 +02:00
Terranom674
ef4741872a Expose WebDAV warmup in cache administration 2026-09-03 12:51:53 +02:00
Terranom674
da74347c9b Trigger album warmup immediately per successful connector sync 2026-09-03 12:51:40 +02:00
Terranom674
c2408819f0 Gate periodic warmup before scanning Piwigo 2026-09-03 12:51:30 +02:00
Terranom674
4beb8f8420 Add WebDAV warmup cache administration 2026-09-03 12:51:27 +02:00
Terranom674
0ac34e3ad1 Allow connection-scoped WebDAV warmup dispatch 2026-09-03 12:50:51 +02:00
Terranom674
b81fd3afa7 Trigger safe WebDAV cache warmup after successful connector sync 2026-09-03 12:50:36 +02:00
Terranom674
87647f8f16 Hold connector sync guard for full warmup run 2026-09-03 12:50:23 +02:00
Terranom674
362229efaa Guard WebDAV warmup against connector tree swaps 2026-09-03 12:50:06 +02:00
Terranom674
8571e3ff1f Register WebDAV cache warmup controls 2026-09-03 12:49:44 +02:00
Terranom674
7e5d34e245 Expose WebDAV warmup settings in cache administration 2026-09-03 12:48:30 +02:00
Terranom674
4c73c43c60 Add manual warmup controls and read-only path audit 2026-09-03 12:48:10 +02:00
Terranom674
cc7fa01c10 Add WebDAV warmup dispatcher 2026-09-03 12:47:46 +02:00
Terranom674
3d768882d2 Add staged Piwigo-owned WebDAV cache warmup 2026-09-03 12:47:28 +02:00
Terranom674
3c822911f8 Add read-only WebDAV warmup path audit 2026-09-03 12:44:10 +02:00
Terranom674
5839d53f90 Add isolated Piwigo derivative caller 2026-09-03 12:43:43 +02:00
Terranom674
d8690fca95 Default WebDAV warmup to disabled during patch phase 2026-09-03 12:43:33 +02:00
Terranom674
fd1a9f1938 Add safe WebDAV batch warmup orchestrator 2026-09-03 12:41:22 +02:00
Terranom674
665768fb1f Add WebDAV warmup settings foundation 2026-09-03 12:40:29 +02:00
Terranom674
add913aab1 Update current status for 0.9.7.1.7 2026-08-20 20:52:44 +02:00
Terranom674
6a0851a30c Update README for 0.9.7.1.7 runtime state 2026-08-20 20:52:12 +02:00
Terranom674
c057f7922e Version 0.9.7.1.7 2026-08-20 20:48:09 +02:00
Terranom674
e3d55a1950 Version 9.7.1.7 2026-08-20 20:47:15 +02:00
Terranom674
84dce41b1c Version 0.9.7.1.6 2026-08-20 20:43:16 +02:00
Terranom674
71577f989f Keep Piwigo placeholder visible for pending picture thumbnails 2026-08-20 20:36:47 +02:00
Terranom674
9c8e44da09 Hide pending WebDAV picture thumbnails 2026-08-20 20:36:08 +02:00
Terranom674
09b6465aad Version 9.7.1.6 2026-08-20 20:26:50 +02:00
Terranom674
17a00eebdb Support Piwigo AJAX thumbnail loader responses 2026-08-20 20:26:32 +02:00
Terranom674
199d954409 Bump version to 9.7.1.5 2026-08-20 20:09:52 +02:00
Terranom674
db21cf2c5e Make WebDAV placeholder source writable by runtime group 2026-08-20 20:09:34 +02:00
Terranom674
f0f7556aaf Bump version to 9.7.1.4 2026-08-20 20:04:57 +02:00
Terranom674
68e4cd876d Fix Piwigo-relative source path resolution for WebDAV preview derivatives 2026-08-20 20:04:37 +02:00
Terranom674
43dc600b98 Bump version to 9.7.1.3 2026-08-20 19:57:40 +02:00
Terranom674
fdae62520e Fix Nextcloud preview endpoint path 2026-08-20 19:57:20 +02:00
Terranom674
8023f7b5d7 Bump version to 9.7.1.2 2026-08-20 19:47:45 +02:00
Terranom674
8a5435ea6b Keep WebDAV mapping readable by Piwigo runtime 2026-08-20 19:47:23 +02:00
Terranom674
880ff2a2b1 Fix WebDAV state permissions for runtime preview access 2026-08-20 19:46:56 +02:00
Terranom674
062d38ab08 Bump version to 9.7.1.1 2026-08-20 19:40:51 +02:00
Terranom674
10065ece46 Make WebDAV mapping lookup robust by webdav_path 2026-08-20 19:40:29 +02:00
Terranom674
bccc5cafda Set current status rebuild baseline to 9.7.1.0 2026-08-20 19:33:28 +02:00
Terranom674
2c52228265 Set README rebuild baseline to 9.7.1.0 2026-08-20 19:33:07 +02:00
Terranom674
7277a8b287 Start connector rebuild at version 9.7.1.0 2026-08-20 19:32:38 +02:00
Terranom674
9155a52290 Refresh README for preview-backed WebDAV derivatives 2026-08-20 19:30:34 +02:00
Terranom674
afa6d02c46 Update current status for preview-backed derivatives 2026-08-20 19:30:02 +02:00
Terranom674
9c94953267 Bump version to 0.9.6.8.25 2026-08-20 19:29:24 +02:00
Terranom674
66d62321d0 Use Nextcloud previews for small WebDAV derivatives 2026-08-20 19:28:55 +02:00
Terranom674
cb9a4b7d2a Expose WebDAV file metadata to materialize runtime 2026-08-20 19:27:48 +02:00
Terranom674
388351c356 Bump version to 0.9.6.8.24 2026-08-20 19:20:32 +02:00
Terranom674
ea71b54c94 Avoid HTTP self-request for WebDAV derivative generation 2026-08-20 19:20:06 +02:00
Terranom674
99edfc84d8 Bump version to 0.9.6.8.23 2026-08-20 19:06:30 +02:00
Terranom674
b224cd40f6 Fix Nextcloud image dimension XML parsing 2026-08-20 19:05:54 +02:00
Terranom674
a437f5d205 Bump version to 0.9.6.8.22 2026-08-20 18:23:34 +02:00
Terranom674
f2b2845387 Remove obsolete WebDAV precache and derivative prebuild 2026-08-20 18:23:11 +02:00
Terranom674
b54cb039fb release: bump to 0.9.6.8.21 2026-08-20 18:11:58 +02:00
Terranom674
419fe56cde webdav: stop downloading originals for dimension metadata 2026-08-20 18:11:34 +02:00
Terranom674
8cb4abf81d webdav: read image dimensions from Nextcloud metadata 2026-08-20 18:11:07 +02:00
Terranom674
ae70e64c70 release: bump plugin version to 0.9.6.8.20 2026-08-20 18:00:08 +02:00
Terranom674
e5557eba24 webdav: sync original dimensions after piwigo import 2026-08-20 17:59:45 +02:00
Terranom674
5b3eabcb55 webdav: sync original dimensions into piwigo 2026-08-20 17:58:57 +02:00
Terranom674
d56aff39a2 webdav: persist original image dimensions 2026-08-20 17:58:43 +02:00
Terranom674
01243ea022 docs: refresh current development status 2026-08-20 17:42:06 +02:00
Terranom674
88f2949903 docs: update repository information for 0.9.6.8.19 2026-08-20 17:41:35 +02:00
Terranom674
136a6c235e Fix admin dashboard album tile for single album 2026-08-20 17:37:50 +02:00
Terranom674
fb211693ff Preserve connector top-level album access without name collision 2026-08-20 17:32:13 +02:00
Terranom674
b0885a0554 Fix duplicate private album access handler 2026-08-20 17:31:52 +02:00
Terranom674
bc798c5d65 Fix access for flattened WebDAV top-level albums 2026-08-20 17:23:26 +02:00
Terranom674
f958eca176 Bump version to 0.9.6.8.15 2026-08-20 16:54:35 +02:00
Terranom674
93af719143 Flatten empty WebDAV root into gallery root 2026-08-20 16:54:06 +02:00
Terranom674
11183f2a41 Bump version to 0.9.6.8.14 2026-08-20 16:41:27 +02:00
Terranom674
26bb454ba4 Preserve empty WebDAV root path in sync 2026-08-20 16:41:10 +02:00
Terranom674
a195421fed Allow empty WebDAV root path in reconcile 2026-08-20 16:40:47 +02:00
Terranom674
ec55220124 Bump plugin version to 0.9.6.8.13 2026-08-20 16:15:08 +02:00
Terranom674
f5d3b97339 Use absolute runtime path for manual WebDAV sync 2026-08-20 16:14:41 +02:00
Terranom674
a5b4a2329e Bump version to 0.9.6.8.12 2026-08-20 16:13:13 +02:00
Terranom674
97340a517b Run manual WebDAV sync directly from plugin 2026-08-20 16:12:52 +02:00
Terranom674
238c06be33 Bump Bratonien Tools to 0.9.6.8.11 2026-08-20 16:09:54 +02:00
Terranom674
792e8eb7d2 Add manual WebDAV sync button to connector status 2026-08-20 16:09:15 +02:00
Terranom674
d489bd7979 Bump version to 0.9.6.8.10 2026-08-20 16:05:58 +02:00
Terranom674
e8a5f5f0f7 Add NC connector run-now button to admin status 2026-08-20 16:05:36 +02:00
Terranom674
ecc7665ed3 Register manual NC connector run 2026-08-20 16:05:04 +02:00
Terranom674
0d3764f043 Add manual NC connector run and clean status text 2026-08-20 16:04:45 +02:00
Terranom674
81b3b31689 Bump plugin version to 0.9.6.8.9 2026-08-20 15:59:14 +02:00
Terranom674
dcd1b9fb66 Make WebDAV shadow directories writable for runtime materialization 2026-08-20 15:58:57 +02:00
Terranom674
72a89a4636 Bump version to 0.9.6.8.8 2026-08-20 15:48:58 +02:00
Terranom674
2e03cc50d8 Add WebDAV derivative gate diagnostics 2026-08-20 15:48:29 +02:00
Terranom674
d2f171718e Bump version to 0.9.6.8.7 2026-08-20 15:34:33 +02:00
Terranom674
403b1df43f Simplify WebDAV gate to materialize real Piwigo source 2026-08-20 15:34:11 +02:00
Terranom674
38e6ebdb19 Switch WebDAV images to on-demand Piwigo materialization 2026-08-20 15:17:05 +02:00
Terranom674
474acf1de3 Use materialization resolver for WebDAV originals 2026-08-20 15:16:51 +02:00
Terranom674
fe3c7fede2 Add production WebDAV derivative materialization gate 2026-08-20 15:16:30 +02:00
Terranom674
ec801b88d2 Add production WebDAV materialization runtime 2026-08-20 15:15:40 +02:00
Terranom674
9eb38d7dcf Bump version to 0.9.6.8.5 2026-08-20 14:48:15 +02:00
Terranom674
1a7e9a13ee Add parallel WebDAV download stress test 2026-08-20 14:47:51 +02:00
Terranom674
e1d2598e22 Bump version to 0.9.6.8.4 2026-08-20 14:40:46 +02:00
Terranom674
29063b296a Add resource metrics to WebDAV derivative test 2026-08-20 14:40:13 +02:00
Terranom674
210c180e49 Bump test version to 0.9.6.8.3 2026-08-20 14:31:54 +02:00
Terranom674
7ef6c24db4 Move WebDAV derivative test source to Piwigo upload area 2026-08-20 14:31:28 +02:00
Terranom674
1e57e6d300 Bump test patch version to 0.9.6.8.2 2026-08-20 14:25:29 +02:00
Terranom674
57eec81801 Use Piwigo derivative dir for parallel test workspace 2026-08-20 14:24:53 +02:00
Terranom674
0ea01d9a26 Bump plugin version to 0.9.6.8.1 2026-08-20 14:22:36 +02:00
Terranom674
b901b4e887 Bump plugin version for parallel derivative test 2026-08-20 14:20:17 +02:00
Terranom674
bc5a94dc10 Make WebDAV derivative test fully parallel 2026-08-20 14:19:43 +02:00
Terranom674
34a473fa07 Bump plugin version for WebDAV derivative root test 2026-08-20 14:08:13 +02:00
Terranom674
7fc038e107 Fix WebDAV root matching in derivative test path 2026-08-20 14:07:41 +02:00
Terranom674
3b2a8306ad Bump version for WebDAV diagnostic endpoint 2026-08-20 14:03:38 +02:00
Terranom674
dae5f9a610 Add isolated WebDAV derivative path diagnostics 2026-08-20 14:03:04 +02:00
Terranom674
929f18a5f5 Fix duplicate private album access function and bump version 2026-08-20 13:49:33 +02:00
Terranom674
0c45576e2f Bump plugin version for WebDAV derivative test 2026-08-20 13:46:25 +02:00
Terranom674
ee01842cb4 Add parallel WebDAV derivative materialization test endpoint 2026-08-20 13:41:17 +02:00
Terranom674
a872f9238c Merge pull request #52 from Terranom674/fix/0963-clean-webdav-orphans
0.9.6.3: verwaiste WebDAV-Bilder einmalig bereinigen
2026-08-20 11:25:39 +02:00
Terranom674
fdcf045f39 0.9.6.3: WebDAV-Pfadfilter exakt begrenzen 2026-08-20 11:24:56 +02:00
Terranom674
7831a9513f Version 0.9.6.3 2026-08-20 11:24:19 +02:00
Terranom674
fed089db4c 0.9.6.3: Altlasten-Reparatur einmalig vor WebDAV-Sync ausführen 2026-08-20 11:23:54 +02:00
Terranom674
77a295d74f 0.9.6.3: einmalige Reparatur verwaister WebDAV-Bilder 2026-08-20 11:23:33 +02:00
Terranom674
ecabf2da2f Merge PR #51: WebDAV-only connector cleanup
Remove obsolete legacy/local connector paths while preserving the WebDAV connector, shadow tree, placeholder mapping and Piwigo sync bridge.
2026-08-20 11:08:55 +02:00
Terranom674
36349a71b1 Remove takeover state from WebDAV reconcile 2026-08-20 11:06:57 +02:00
Terranom674
df8e1f6cd0 Restore mandatory multi-version and script checks 2026-08-20 11:05:29 +02:00
Terranom674
1a6094f2e2 Record WebDAV-only connector status 2026-08-20 11:02:48 +02:00
Terranom674
40bac7b910 Document WebDAV-only connector architecture 2026-08-20 11:02:25 +02:00
Terranom674
2c10f190c3 Remove legacy connector state from admin controller 2026-08-20 11:01:43 +02:00
Terranom674
d4c195856c Remove legacy fields from WebDAV connection creation 2026-08-20 11:00:52 +02:00
Terranom674
aacbd5af1d Reduce connector model to WebDAV-only state 2026-08-20 11:00:29 +02:00
Terranom674
2e9b3ee2c6 Remove obsolete database credential field from WebDAV secrets 2026-08-20 10:59:50 +02:00
Terranom674
83f44a27b9 Remove obsolete connector WS registration and bump version 2026-08-20 10:59:28 +02:00
Terranom674
1d90754de0 Remove obsolete connector sync simulation endpoint 2026-08-20 10:51:40 +02:00
Terranom674
a4130621d0 Remove legacy local connector install tool 2026-08-20 10:50:58 +02:00
Terranom674
1f1b2dbcf6 Remove legacy connector diagnose tool 2026-08-20 10:50:47 +02:00
Terranom674
173c487474 Remove legacy local connector disable tool 2026-08-20 10:50:34 +02:00
Terranom674
edd86f59f3 Remove legacy connector normalize tool 2026-08-20 10:50:22 +02:00
Terranom674
45ab33d3c4 Remove legacy connector runtime switch 2026-08-20 10:50:14 +02:00
Terranom674
b81207e406 Remove legacy connector cleanup tool 2026-08-20 10:49:59 +02:00
Terranom674
6d33f62599 Remove legacy connector migration tool 2026-08-20 10:49:48 +02:00
Terranom674
5099b154bf Remove legacy connector cutover v2 tool 2026-08-20 10:49:35 +02:00
Terranom674
54616730ca Remove legacy connector cutover tool 2026-08-20 10:49:24 +02:00
Terranom674
09b70ee317 Remove legacy runtime status checks 2026-08-20 10:44:40 +02:00
Terranom674
01f935b769 Keep only WebDAV connection-scoped Piwigo auth helpers 2026-08-20 10:43:46 +02:00
Terranom674
03afa95dc6 Remove legacy connector UI 2026-08-20 10:43:20 +02:00
Terranom674
8588c3c1c2 Remove parallel and legacy reconcile branches 2026-08-20 10:41:14 +02:00
Terranom674
1a47e82997 Make WebDAV the sole connector mode 2026-08-20 10:40:23 +02:00
Terranom674
d2fd72bbc1 Reduce connector model to WebDAV connections 2026-08-20 10:39:58 +02:00
Terranom674
c5331d275e Remove legacy global connector authentication 2026-08-20 10:39:30 +02:00
Terranom674
7c76b4f476 Remove legacy local connector management 2026-08-20 10:39:17 +02:00
Terranom674
edfd91dc29 Remove remaining legacy connector handlers 2026-08-20 10:39:04 +02:00
Terranom674
d44f6c988f Keep connection auth WebDAV-only 2026-08-20 10:38:43 +02:00
Terranom674
471df03c76 Reduce connector wizard to WebDAV only 2026-08-20 10:38:24 +02:00
Terranom674
ea2bac5cfa Remove legacy connector tools 2026-08-20 10:35:47 +02:00
Terranom674
6ba855b76c Remove legacy wizard dispatch branches 2026-08-20 10:35:27 +02:00
Terranom674
792f7bb638 Keep wizard user scope WebDAV-only 2026-08-20 10:35:03 +02:00
Terranom674
557ad16e8a Remove legacy wizard technical flow 2026-08-20 10:34:34 +02:00
Terranom674
76f9089c00 Remove legacy wizard DB bridge 2026-08-20 10:34:21 +02:00
Terranom674
6af48796eb Remove legacy generic DB scope 2026-08-20 10:34:11 +02:00
Terranom674
b331bb087c Remove legacy takeover flow 2026-08-20 10:33:57 +02:00
Terranom674
d4ad87a6df Remove legacy local connector creation 2026-08-20 10:33:48 +02:00
Terranom674
49f30f5f17 Remove legacy Piwigo admin sync helper 2026-08-20 10:33:39 +02:00
Terranom674
ba35da9b68 Remove legacy Piwigo DB checker 2026-08-20 10:33:29 +02:00
Terranom674
d862433bdb Remove legacy selected-fileid DB manifest builder 2026-08-20 10:33:19 +02:00
Terranom674
337b5c6dc7 Remove legacy DB manifest builder 2026-08-20 10:33:04 +02:00
Terranom674
1504e1dc29 Remove legacy DB activity gate 2026-08-20 10:32:43 +02:00
Terranom674
8f0b8aabf8 Remove legacy Nextcloud DB view migration 2026-08-20 10:32:33 +02:00
Terranom674
225542acd9 Remove legacy local runtime cleanup 2026-08-20 10:32:24 +02:00
Terranom674
c152ef9808 Remove legacy local sync runtime 2026-08-20 10:32:13 +02:00
Terranom674
e5b8a01367 Remove legacy local reconcile runtime 2026-08-20 10:31:59 +02:00
Terranom674
247da33e3a Isolate Piwigo sync to WebDAV sites 2026-08-20 10:31:36 +02:00
Terranom674
198b93f4e7 Remove legacy runtime orchestration 2026-08-20 10:30:37 +02:00
Terranom674
2c7cd9e780 Align WebDAV image stream version with 0.9.6.1 2026-08-19 00:13:11 +02:00
Terranom674
6155955eee Align WebDAV preview runtime version with 0.9.6.1 2026-08-19 00:12:39 +02:00
Terranom674
5179c1cc33 Align derivative builder version with 0.9.6.1 2026-08-19 00:12:08 +02:00
Terranom674
facb270b13 Refresh README for 0.9.6.1 2026-08-19 00:11:53 +02:00
Terranom674
b4f56ac04b Update current status for 0.9.6.1 2026-08-19 00:11:27 +02:00
Terranom674
16571f9322 Bump version to 0.9.6.1 2026-08-18 23:46:33 +02:00
Terranom674
d7fd99eb7c Clean stale WebDAV Piwigo content in runner 2026-08-18 23:46:16 +02:00
Terranom674
207c2ae502 Clean stale WebDAV Piwigo sites after connection deletion 2026-08-18 23:46:03 +02:00
Terranom674
4d04f115e1 Remove WebDAV Piwigo content when deleting connection 2026-08-18 23:45:42 +02:00
Terranom674
ed9088a8e2 Keep WebDAV precache on 0.9.5.x 2026-08-18 23:38:22 +02:00
Terranom674
8c7476a5d2 Keep derivative builder on 0.9.5.x 2026-08-18 23:37:54 +02:00
Terranom674
bc9d378bfd Restore 0.9.5.x version line 2026-08-18 23:37:35 +02:00
Terranom674
3da61079f2 Release 0.9.6.0 WebDAV derivative rebuild 2026-08-18 23:33:16 +02:00
Terranom674
f380ee4aec Serve WebDAV previews with their real MIME type 2026-08-18 23:32:01 +02:00
Terranom674
96dda18fc9 Build WebDAV derivatives with validated Piwigo image sources 2026-08-18 23:31:26 +02:00
Terranom674
3767620867 Make WebDAV derivatives safe and Piwigo-compatible 2026-08-18 23:30:56 +02:00
Terranom674
d18e7108dd Rebuild WebDAV previews in Piwigo-compatible formats 2026-08-18 23:30:22 +02:00
Terranom674
450f9a0ac5 Bump version to 0.9.5.22 2026-08-18 23:17:53 +02:00
Terranom674
47182a86a2 Hotfix: never build WebDAV derivatives during page rendering 2026-08-18 23:16:43 +02:00
Terranom674
907fba8c8f Expose WebDAV derivative builder runtime version 2026-08-18 23:15:24 +02:00
Terranom674
bf03fea647 Bump version to 0.9.5.21 2026-08-18 23:10:12 +02:00
Terranom674
b3aef2744f Handle WebDAV derivative identity correctly 2026-08-18 23:09:53 +02:00
Terranom674
bcf98c63ef Fix WebDAV derivative metadata and identity handling 2026-08-18 23:09:23 +02:00
Terranom674
fa3ce09589 Bump version to 0.9.5.20 2026-08-18 22:59:19 +02:00
Terranom674
fde03e66f9 Build WebDAV Piwigo derivatives during sync 2026-08-18 22:59:04 +02:00
Terranom674
b780636791 Prebuild Piwigo derivatives for WebDAV images 2026-08-18 22:58:32 +02:00
Terranom674
8785a1ccc5 Generate WebDAV derivatives from prepared previews 2026-08-18 22:58:14 +02:00
Terranom674
554778601f Bump version to 0.9.5.19 2026-08-18 22:48:46 +02:00
Terranom674
c1665e53ad Preload WebDAV previews during sync 2026-08-18 22:48:27 +02:00
Terranom674
047045ad23 Serve precached WebDAV previews 2026-08-18 22:48:03 +02:00
Terranom674
0355f4a555 Use precached WebDAV previews for derivatives 2026-08-18 22:47:44 +02:00
Terranom674
a71c07cbce Precache WebDAV previews during sync 2026-08-18 22:47:29 +02:00
Terranom674
69213adabf Bump version to 0.9.5.18 2026-08-18 22:42:38 +02:00
Terranom674
272930ead5 Fix WebDAV image lookup without private runtime map dependency 2026-08-18 22:42:23 +02:00
Terranom674
5a115e3b4a Route WebDAV photos to live Nextcloud image stream 2026-08-18 22:30:35 +02:00
Terranom674
6791b65e50 Stream Nextcloud image bytes for WebDAV-backed photos 2026-08-18 22:29:53 +02:00
Terranom674
2238845579 Serve WebDAV originals through Piwigo image URLs 2026-08-18 22:29:32 +02:00
Terranom674
4c862c77b3 Bump version to 0.9.5.16 2026-08-18 22:23:48 +02:00
Terranom674
370572c77d Register WebDAV roots as dedicated Piwigo sites 2026-08-18 22:23:30 +02:00
Terranom674
74911e473c Use dedicated WebDAV gallery roots and suppress duplicate sources 2026-08-18 22:22:51 +02:00
Terranom674
65cd8898d3 Bump version for wizard validation lifecycle hardening 2026-08-18 22:18:54 +02:00
Terranom674
e46196c143 Keep NC wizard open across validation errors and form posts 2026-08-18 22:18:34 +02:00
Terranom674
6a71532839 Bump plugin version to 0.9.5.14 2026-08-18 22:14:57 +02:00
Terranom674
3cd647ea6b Clarify WebDAV Piwigo fallback authentication failures 2026-08-18 22:14:41 +02:00
Terranom674
639e50afb5 Bump Bratonien Tools to 0.9.5.13 2026-08-18 22:12:33 +02:00
Terranom674
17f7fa8d52 Validate WebDAV wizard Piwigo fallback before saving 2026-08-18 22:12:11 +02:00
Terranom674
af527e496b Validate connection-scoped Piwigo fallback credentials 2026-08-18 22:11:36 +02:00
Terranom674
577d1ebf81 Bump plugin version to 0.9.5.12 2026-08-18 21:56:49 +02:00
Terranom674
3bd3158817 Improve WebDAV sync failure diagnostics 2026-08-18 21:56:30 +02:00
Terranom674
c916d742f5 Bump version to 0.9.5.11 2026-08-18 21:53:40 +02:00
Terranom674
6f0891f6a8 Enable Piwigo registration for parallel WebDAV connections 2026-08-18 21:53:13 +02:00
Terranom674
b8ea6b1fe2 Bump plugin version to 0.9.5.10 2026-08-18 21:45:51 +02:00
Terranom674
aeba24c6fa Clarify WebDAV registration through existing productive sync 2026-08-18 21:45:22 +02:00
Terranom674
0d81d83d12 Build WebDAV shadow trees before productive Piwigo sync 2026-08-18 21:45:04 +02:00
Terranom674
dbedb83c14 Bump plugin version for WebDAV-first wizard 2026-08-18 21:39:03 +02:00
Terranom674
04620f20a2 Persist wizard auth for WebDAV connections 2026-08-18 21:38:38 +02:00
Terranom674
2127649209 Route wizard through WebDAV-first flow 2026-08-18 21:38:18 +02:00
Terranom674
fd5b55ac53 Add WebDAV-first wizard flow 2026-08-18 21:37:55 +02:00
Terranom674
933db21d88 Release 0.9.5.8 2026-08-18 21:34:48 +02:00
Terranom674
a854bda115 Keep connector status polling from reloading admin page 2026-08-18 21:34:32 +02:00
Terranom674
08040edf8f Document WebDAV parallel runtime in 0.9.5.7 2026-08-18 21:27:24 +02:00
Terranom674
bb024000f2 Bump plugin version to 0.9.5.7 2026-08-18 21:26:27 +02:00
Terranom674
539605b19a Run WebDAV path beside existing connector runtime 2026-08-18 21:25:57 +02:00
Terranom674
a550bbd01a Add isolated WebDAV shadow tree runner 2026-08-18 21:25:44 +02:00
Terranom674
e344455e0c Add isolated WebDAV runtime reconciliation 2026-08-18 21:25:29 +02:00
Terranom674
88edd5aee9 Update README for 0.9.5.6 WebDAV parallel path 2026-08-18 21:23:05 +02:00
Terranom674
aa7ddefa0b Record parallel WebDAV connector foundation 2026-08-18 21:22:32 +02:00
Terranom674
ef37e3b612 Bump plugin version to 0.9.5.6 2026-08-18 21:21:44 +02:00
Terranom674
eadee3cc24 Preserve WebDAV credentials in scoped secret updates 2026-08-18 21:21:26 +02:00
Terranom674
d05a6f4f46 Register parallel WebDAV connector action 2026-08-18 21:20:50 +02:00
Terranom674
04b32309df Add parallel WebDAV connector mode 2026-08-18 21:20:08 +02:00
Terranom674
db28692cfb Pass WebDAV credentials from wizard into connection secret 2026-08-18 21:19:45 +02:00
Terranom674
5866824398 Store Nextcloud WebDAV credentials per connection 2026-08-18 21:19:26 +02:00
Terranom674
ac419ac56f Bring README to current 0.9.5.5 connector architecture 2026-08-18 21:17:27 +02:00
Terranom674
65910375d2 Document current connector status and WebDAV migration plan 2026-08-18 21:16:56 +02:00
Terranom674
c547c9b089 Bump plugin version to 0.9.5.5 2026-08-18 21:13:48 +02:00
Terranom674
21caddcec5 Clean deleted connector runtime before sync 2026-08-18 21:13:30 +02:00
Terranom674
237500a8fa Use safe connector deletion handler 2026-08-18 21:13:21 +02:00
Terranom674
f5dae306db Clean stale connector runtime files before sync 2026-08-18 21:13:02 +02:00
Terranom674
20bd5105f3 Fix connector deletion across runtime ownership boundaries 2026-08-18 21:12:50 +02:00
Terranom674
82019fb14d Bump plugin version for WebDAV placeholder work 2026-08-18 21:10:51 +02:00
Terranom674
17e4f66126 Add WebDAV placeholder source builder 2026-08-18 21:08:50 +02:00
Terranom674
1bb2088d06 Release 0.9.5.3 2026-08-18 19:12:15 +02:00
Terranom674
d97ac4b5db NC runtime: reconcile legacy and selected sources generically 2026-08-18 19:10:46 +02:00
Terranom674
e733b6f6e8 NC connector: register generic source scope 2026-08-18 19:09:59 +02:00
Terranom674
c7966db8f2 NC connector: persist generic fileid source scope 2026-08-18 19:09:40 +02:00
Terranom674
e1d01d02f5 NC wizard: route technical check through generic connector views 2026-08-18 19:09:17 +02:00
Terranom674
28f8bb7d96 NC wizard: resolve WebDAV selections by fileid and storage adapter 2026-08-18 19:09:03 +02:00
Terranom674
cd7d8aa2f1 NC runtime: use generic user and fileid source modes 2026-08-18 19:07:56 +02:00
Terranom674
69815b1cf4 NC runtime: scope activity checks per connection user 2026-08-18 19:07:20 +02:00
Terranom674
b301853ea2 NC runtime: make share manifest user-filterable 2026-08-18 19:07:01 +02:00
Terranom674
0e1c4faedd NC runtime: build manifest from selected Nextcloud file IDs 2026-08-18 19:06:33 +02:00
Terranom674
cfa2322d75 NC runtime: remove abandoned user filesystem manifest 2026-08-18 18:37:14 +02:00
Terranom674
1513500e2e NC runtime: remove abandoned user-filesystem mapper 2026-08-18 18:37:05 +02:00
Terranom674
2b16604e6e NC runtime: remove experimental user-filesystem reconcile 2026-08-18 18:36:54 +02:00
Terranom674
c9e8cee89e Bratonien Tools 0.9.5.2 2026-08-18 17:29:08 +02:00
Terranom674
77981a4e05 NC Status: Ergebnistext im Polling tatsächlich aktualisieren 2026-08-18 17:28:37 +02:00
Terranom674
875832b73e NC 9.5: Nextcloud Benutzerstamm unter uid/files sicher erkennen 2026-08-18 17:27:58 +02:00
Terranom674
774c82ab68 Release 0.9.5.1 2026-08-18 17:07:36 +02:00
Terranom674
7024d3cd3d 0.9.5.1: Connector-Ergebnis beim Polling aktualisieren 2026-08-18 17:07:06 +02:00
Terranom674
042a090db4 0.9.5.1: gespeicherten Nextcloud-Zugriffsbenutzer verwenden 2026-08-18 17:06:39 +02:00
Terranom674
2edacf5e0b 0.9.5.1: Benutzerisolation vor jedem Lauf anwenden 2026-08-18 17:06:07 +02:00
Terranom674
e53041f1c1 0.9.5.1: native Verbindungen auf Benutzer-Stamm isolieren 2026-08-18 17:05:53 +02:00
Terranom674
3512f60136 0.9.5.1: Runtime nach Verbindungsquelle trennen 2026-08-18 17:05:04 +02:00
Terranom674
73e4b08dbd 0.9.5.1: benutzerbezogenes Manifest ohne Showcase-View 2026-08-18 17:04:20 +02:00
Terranom674
e06539c125 Bratonien Tools 0.9.4.13 2026-08-18 16:50:13 +02:00
Terranom674
e0cd91a0b7 NC-Connector echte Runtime-Fehlerausgabe erhalten 2026-08-18 16:49:54 +02:00
Terranom674
c28a8c6f80 Version 0.9.4.12 2026-08-18 16:46:58 +02:00
Terranom674
032d9a151c Shell-Syntax im CI mitpruefen 2026-08-18 16:46:34 +02:00
Terranom674
86fad7aa1f NC Connector Laufzeitfehler aussagekraeftig erfassen 2026-08-18 16:46:08 +02:00
Terranom674
62b17fcd09 Bump version for automatic multi-connection runtime reconciliation 2026-08-18 16:22:58 +02:00
Terranom674
1e77988831 Reconcile stored connections before shared runtime 2026-08-18 16:22:31 +02:00
Terranom674
eb3bc48ceb Reconcile wizard connections into shared runtime 2026-08-18 16:22:19 +02:00
Terranom674
b8d31e37ca Version 0.9.4.10 2026-08-18 16:13:59 +02:00
Terranom674
ad90cd678b Technische NC-Anlage uebernimmt vorhandene API einmalig 2026-08-18 16:13:05 +02:00
Terranom674
1065651bee NC-Verbindungen immer loeschbar und Laufzeitfehler sichtbar machen 2026-08-18 16:12:19 +02:00
Terranom674
4e0c9007c3 Tombstone-Pfad pro NC-Verbindung aus Konfiguration bestimmen 2026-08-18 16:10:17 +02:00
Terranom674
1485acbd45 Fallback-Handler auf verbindungsspezifische Secrets umstellen 2026-08-18 16:10:03 +02:00
Terranom674
81a28a9282 Fallback-Aenderungen erhalten verbindungseigene API 2026-08-18 16:09:31 +02:00
Terranom674
201a44a890 Piwigo Sync verwendet API der jeweiligen Verbindung 2026-08-18 16:06:41 +02:00
Terranom674
a64d5b92c5 Verbindungspruefung migriert Authentifizierung auf Verbindungsumfang 2026-08-18 16:05:22 +02:00
Terranom674
14e4943102 Bestehende native Verbindungen auf eigenen Auth-Modus migrieren 2026-08-18 16:04:54 +02:00
Terranom674
b562309c6e Geloeschte NC-Verbindungen vor Laufzeitabruf entfernen 2026-08-18 16:03:40 +02:00
Terranom674
8fc0ae96d4 NC Connector Handler auf verbindungsspezifische Laufzeit umstellen 2026-08-18 16:03:19 +02:00
Terranom674
cbcaf2d575 NC Connector Laufzeit und Authentifizierung pro Verbindung kapseln 2026-08-18 16:02:53 +02:00
Terranom674
0fa5430ff6 NC Connector Authentifizierung pro Verbindung speichern 2026-08-18 16:02:23 +02:00
Terranom674
7d0d97d844 NC-Wizard sichtbare Fenster eindeutig benennen 2026-08-18 15:45:03 +02:00
Terranom674
3325efce31 Version 0.9.4.9 2026-08-18 15:42:00 +02:00
Terranom674
8b4f3193d3 NC-Wizard Flow-Handler registrieren 2026-08-18 15:41:37 +02:00
Terranom674
47ba20e247 NC-Wizard technischen Schrittfluss konsolidieren 2026-08-18 15:41:13 +02:00
Terranom674
e44cceaacc NC-Wizard sichtbare Fenster einzeln navigierbar machen 2026-08-18 15:40:34 +02:00
Terranom674
48822bc9e9 Alten NC-Wizard AJAX-Sonderweg entfernen 2026-08-18 15:30:45 +02:00
Terranom674
d638dcc590 Alten NC-Wizard JS-Sonderweg entfernen 2026-08-18 15:30:39 +02:00
Terranom674
d520209956 Bratonien Tools 0.9.4.8 serverseitiger NC-Wizard 2026-08-18 15:30:22 +02:00
Terranom674
08b33997f5 NC-Wizard Ordnerwahl und Navigation serverseitig rendern 2026-08-18 15:29:55 +02:00
Terranom674
56b18e650c NC-Wizard serverseitige Ordneraktionen registrieren 2026-08-18 15:28:29 +02:00
Terranom674
c3d40faa1e NC-Wizard Ordnerbrowser serverseitig konsolidieren 2026-08-18 15:28:05 +02:00
Terranom674
867d8e9804 Bratonien Tools 0.9.4.7 2026-08-18 15:05:22 +02:00
Terranom674
b891e06fe5 NC-Wizard sichere WebDAV-Ordnerauswahl und Navigation 2026-08-18 15:04:33 +02:00
Terranom674
5694659004 NC-Wizard Ordner per User-WebDAV laden 2026-08-18 15:03:34 +02:00
Terranom674
eeaac9caaa NC-Wizard User-Scope und Zurück-Navigation registrieren 2026-08-18 15:03:19 +02:00
Terranom674
0a7548414b NC-Wizard strikt auf angemeldeten Nextcloud-Nutzer begrenzen 2026-08-18 15:02:56 +02:00
Terranom674
f1a117818f NC-Wizard Verzeichnisdialog und Hinweise verfeinern 2026-08-18 14:56:44 +02:00
Terranom674
c2c8652557 Automatische Syntaxpruefung fuer PHP und Python einfuehren 2026-08-18 14:55:35 +02:00
Terranom674
ea3a65664d NC-Connector Verzeichnisfilter in Runtime schreiben 2026-08-18 14:54:47 +02:00
Terranom674
c85aa2e833 Bratonien Tools 0.9.4.6 Verzeichnisauswahl laden 2026-08-18 14:54:02 +02:00
Terranom674
f671e76170 NC-Wizard dynamische Verzeichnisauswahl hinzufuegen 2026-08-18 14:53:29 +02:00
Terranom674
755e7d39fa NC-Wizard Verzeichnisoptionen bereitstellen 2026-08-18 14:53:09 +02:00
Terranom674
6ed7c483e3 NC-Wizard Verzeichnisaktionen registrieren 2026-08-18 14:52:57 +02:00
Terranom674
3eef7180d0 NC-Wizard Verzeichnisauswahl und Stammverzeichnis ergaenzen 2026-08-18 14:52:38 +02:00
Terranom674
779dc3037f NC-Connector Verzeichnisfilter pro Storage ergaenzen 2026-08-18 14:51:06 +02:00
Terranom674
eeb86722ae NC-Wizard Reader vor erstem DB-Test laden 2026-08-18 14:34:49 +02:00
Terranom674
5d15f0d6ba Version auf 0.9.4.5 anheben 2026-08-18 14:33:09 +02:00
Terranom674
917a36d21e NC-Wizard Reader-Bruecke registrieren 2026-08-18 14:32:55 +02:00
Terranom674
80a25d49e7 NC-Wizard bekannte Reader-Zugangsdaten wiederverwenden 2026-08-18 14:32:10 +02:00
Terranom674
65de8020e9 Update NC wizard status for 0.9.4.4 2026-08-18 11:16:49 +02:00
Terranom674
b264f6cf8c Document unified Nextcloud and database wizard credentials 2026-08-18 11:16:27 +02:00
Terranom674
efeebf9d56 Bump Bratonien Tools to 0.9.4.4 2026-08-18 11:15:48 +02:00
Terranom674
77988184a3 Remove duplicate database credentials from NC wizard 2026-08-18 11:15:27 +02:00
Terranom674
a1373aa6a1 Reuse Nextcloud credentials for database access in wizard 2026-08-18 11:14:20 +02:00
Terranom674
18007c6853 Release 0.9.4.3 2026-08-18 09:13:19 +02:00
Terranom674
82e6757f71 Clear stale NC wizard sessions on open and close 2026-08-18 09:12:58 +02:00
Terranom674
b86e066e2a Fix NC wizard syntax and preserve fallback state 2026-08-18 09:10:55 +02:00
Terranom674
d995f6889b Make legacy cutover compatible with current connector credential format 2026-08-18 09:05:49 +02:00
Terranom674
b6fc2879a0 Remove stale hard-coded connector user agent version 2026-08-18 09:05:11 +02:00
Terranom674
9fa75f844a Bump Bratonien Tools to 0.9.4.2 2026-08-18 09:04:31 +02:00
Terranom674
2f1d6cd832 Refresh current development status for 0.9.4.2 2026-08-18 09:04:15 +02:00
Terranom674
fc6f39445e Refresh README for 0.9.4 connector architecture 2026-08-18 09:03:51 +02:00
Terranom674
6a04b33f0c Allow API-only native NC connector activation 2026-08-18 09:03:06 +02:00
Terranom674
4194cf9e3b Simplify NC wizard for end users and branch technical questions 2026-08-18 09:02:33 +02:00
Terranom674
95a64fabc5 Consolidate intelligent NC connection wizard flow 2026-08-18 09:01:17 +02:00
Terranom674
50feeccd45 Allow storage root mappings and improve connector validation 2026-08-18 09:00:16 +02:00
Terranom674
d9d6968d5a Bump Bratonien Tools to 0.9.4.1 2026-08-18 08:54:14 +02:00
Terranom674
4a6765f53e NC polling: update run timestamps in place without reloading admin page 2026-08-18 08:53:58 +02:00
Terranom674
928c270319 NC status endpoint: expose last and next run labels without page reload 2026-08-18 08:53:32 +02:00
Terranom674
812df537c3 Release consolidated NC connector hardening 0.9.3.43 2026-08-18 08:49:34 +02:00
Terranom674
2f8885f377 Clean connector-owned state when deleting connections 2026-08-18 08:49:05 +02:00
Terranom674
d9c9a88a66 Validate NC manifest SQL view identifiers 2026-08-18 08:48:11 +02:00
Terranom674
53ab96e73b Validate NC runtime SQL view identifiers 2026-08-18 08:47:51 +02:00
Terranom674
6d278c2d0d Make NC shadow tree replacement rollback-safe 2026-08-18 08:47:37 +02:00
Terranom674
73a13a87d3 Remove wizard secrets from browser storage 2026-08-18 08:47:15 +02:00
Terranom674
e9ed89555a Consolidate NC connector wizard for end users 2026-08-18 08:46:57 +02:00
Terranom674
e5a03b13bd Allow validated wizard API commit and return connection id 2026-08-18 08:45:55 +02:00
Terranom674
98a4f49b26 Fix consolidated wizard syntax 2026-08-18 08:45:37 +02:00
Terranom674
b0f5c3d571 Consolidate NC wizard state, validation and API commit 2026-08-18 08:44:41 +02:00
Terranom674
43d01d0450 Bump Bratonien Tools to 0.9.3.42 2026-08-18 08:34:35 +02:00
Terranom674
38a8e76fee Fix Nextcloud OCS success handling in connection wizard 2026-08-18 08:34:19 +02:00
Terranom674
a38035fc92 Bump version to 0.9.3.41 2026-08-18 08:28:19 +02:00
Terranom674
39776d82a3 Preserve NC wizard input state across validation errors 2026-08-18 08:28:06 +02:00
Terranom674
cce875c965 Bump version to 0.9.3.40 2026-08-18 08:24:26 +02:00
Terranom674
ae6707f3cd Make Nextcloud wizard probe HTTPS and HTTP automatically 2026-08-18 08:24:07 +02:00
Terranom674
19abb98f23 Bump version to 0.9.3.39 2026-08-18 08:20:25 +02:00
Terranom674
d307f8437f NC polling: do not reload while wizard is open 2026-08-18 08:20:12 +02:00
Terranom674
97cb0b808f Bump version to 0.9.3.38 2026-08-18 08:15:07 +02:00
Terranom674
bfda6680f8 Prevent duplicate POST actions on page reload 2026-08-18 08:14:47 +02:00
Terranom674
0f05760735 Bump Bratonien Tools to 0.9.3.37 2026-08-18 08:10:45 +02:00
Terranom674
beff765612 Fix Smarty parsing in NC Connector dialog script 2026-08-18 08:10:23 +02:00
Terranom674
e8e845e039 Bump Bratonien Tools to 0.9.3.36 2026-08-18 08:07:26 +02:00
Terranom674
3753ceb20a NC Connector: open assistant only on demand in modal dialog 2026-08-18 08:07:09 +02:00
Terranom674
e64257eeca Bump Bratonien Tools to 0.9.3.35 2026-08-18 08:04:22 +02:00
Terranom674
81b0366609 Make updater snapshot and signature aware 2026-08-18 08:04:04 +02:00
Terranom674
ee37484dd2 Normalize wizard gallery root safely 2026-08-18 08:01:29 +02:00
Terranom674
da6e9f18d5 Bump version to 0.9.3.34 2026-08-18 08:01:02 +02:00
Terranom674
cce4984ed1 Finish NC connection assistant UI 2026-08-18 08:00:40 +02:00
Terranom674
b1efa5ca4e Store wizard-discovered Nextcloud metadata 2026-08-18 07:59:39 +02:00
Terranom674
78dc8a0ad7 Register complete NC wizard actions 2026-08-18 07:59:22 +02:00
Terranom674
8c54f8c97d Complete NC connection wizard flow 2026-08-18 07:59:04 +02:00
Terranom674
1c19760643 Bump Bratonien Tools to 0.9.3.33 2026-08-18 07:53:48 +02:00
Terranom674
cf49026f68 Add simple NC wizard and connection management UI 2026-08-18 07:53:29 +02:00
Terranom674
23d4d1f781 Expose wizard state and editable connector values 2026-08-18 07:52:43 +02:00
Terranom674
d61e239a24 Register NC wizard and connection edit handlers 2026-08-18 07:52:16 +02:00
Terranom674
0a052ba770 Add NC connector wizard foundation and connection editing 2026-08-18 07:51:58 +02:00
95 changed files with 13039 additions and 5331 deletions

View File

@@ -1,122 +1,169 @@
# Aktueller Entwicklungsstand
Stand: 17.08.2026
## Version
## Plugin
**Bratonien Tools 0.9.7.1.7**
- Aktuelle Plugin-Version: **0.9.3.17**
- Aktueller Entwicklungsblock: **NC Connector Verbindungsverwaltung / laufende Optimierung**
- NC Connector ist Feature 10 und noch nicht vollständig abgeschlossen.
- Solange dieser Optimierungsblock läuft, bleibt die Version im Bereich `0.9.3.x`.
Verbindliches Versionsschema: **0.x.x.x.x**.
## Aktueller GitHub-Stand
Zielplattform der produktiven NC-Connector-Synchronisierung ist derzeit **Piwigo 16.4.0**.
Der lokale NC Connector ist für den aktuellen Bratonien-Einsatz im bisherigen Login-Weg End-to-End funktionsfähig. Mit `0.9.3.17` beginnt der Umbau auf API-first für die Piwigo-Synchronisierung.
## NC Connector
Bereits erfolgreich umgesetzt und getestet:
Der produktive Verbindungsweg ist **Nextcloud per WebDAV**.
- Nextcloud-Freigaben vom Typ `folder` und `file` werden aus der Source-View gelesen.
- Ordnerfreigaben werden als Verzeichnisbaum im Shadow Tree gespiegelt.
- Einzeldateifreigaben werden als Symlink direkt im Galerie-Root angelegt und als echte Piwigo-Orphans ohne Albumzuordnung registriert.
- Entfernte Einzeldateifreigaben werden beim normalen Connector-Lauf aus Shadow Tree und Piwigo entfernt.
- Das Nextcloud-Original bleibt bei Löschvorgängen unangetastet.
- Connector-getriggerte neue physische Alben werden standardmäßig privat angelegt.
- Der gemeinsame systemd-Timer `bratonien-nc-connector.timer` läuft produktiv.
### Verbindungsmodell
Neu in `0.9.3.17`:
- `adapter=remote`
- `source_mode=webdav-placeholder`
- Nextcloud-Adresse, Benutzer und Passwort/App-Passwort werden pro Verbindung verschlüsselt gespeichert.
- Piwigo-API und Benutzername/Passwort-Fallback werden pro Verbindung gespeichert.
- Der Assistent zeigt ausschließlich per WebDAV sichtbare Verzeichnisse.
- Ein leerer `webdav_path` ist ein gültiger Benutzer-Root.
- die Piwigo-API ist als bevorzugter Synchronisierungsweg vorgesehen;
- ein erfolgreich geprüfter API-Key wird verschlüsselt in der Piwigo-Konfiguration gespeichert;
- produktive API-Synchronisierung ist ausdrücklich an die freigegebene Piwigo-Version **16.4.0** gebunden;
- neuer Webservice `bratonien.nc.syncProductive` delegiert den freigegebenen produktiven Dateisync an Piwigos Core-Synchronisierung;
- `runtime/lib/piwigo-sync.php` versucht zuerst die API und fällt nur bei nicht nutzbarer API auf Benutzername/Passwort zurück;
- der bisherige Benutzername/Passwort-Zugang kann als verschlüsselter Fallback gespeichert oder gelöscht werden;
- ein Benutzername/Passwort-Fallback kann außerdem einmalig manuell ausgeführt werden, ohne die Zugangsdaten zu speichern;
- neue lokale Verbindungen werden intern als `api-first` angelegt; ein dauerhaft gespeicherter Login-Fallback ist technisch nicht mehr zwingend, sofern ein API-Zugang vorhanden ist.
### Root-Verhalten
## Architektur NC Connector
Bei `webdav_path=""` wird die technische Nextcloud-Benutzerebene nicht als Piwigo-Album angelegt.
- Nextcloud bleibt die einzige dauerhafte Quelle der Originalbilder.
- Piwigo erhält nur die benötigte Verzeichnis-/Symlink-Struktur und erzeugt daraus seine Derivate und Cache-Dateien.
- Der Connector arbeitet mit einem PostgreSQL-Leser und den Views `piwigo_showcase_sources` und `piwigo_showcase_activity`.
- Laufzeitdaten liegen unter `/var/lib/bratonien-tools/nc-connector/...`.
- Verbindungs-Konfigurationen liegen unter `/etc/bratonien-tools/nc-connector/connection-*.conf`.
- Der Shadow Tree enthält Verzeichnisse und Symlinks, keine Kopien der Originaldateien.
- Alle aktivierten Verbindungen werden über `runtime/run-all.sh` gemeinsam verarbeitet.
Direkte Unterordner des Nextcloud-Benutzerroots werden als Top-Level-Piwigo-Alben gespiegelt. Direkt im Root liegende Einzelbilder verbleiben auf Root-Ebene des verbindungseigenen Shadow Trees und werden durch die Orphan-Logik verarbeitet.
## Nextcloud-Freigabemodell
Es gibt keine fest verdrahteten Album-Namen.
Der Connector unterstützt komplette Ordner und einzelne Bilder.
### Laufzeit
- `folder` -> Verzeichnisstruktur spiegeln und über Piwigos Dateisynchronisierung als physische Albumstruktur einlesen;
- `file` -> Symlink direkt im Galerie-Root und anschließende Registrierung als Piwigo-Orphan.
Der gemeinsame Runner verarbeitet WebDAV-Verbindungen in dieser Reihenfolge:
Für einzelne Dateien wird kein künstlicher Unterordner erzeugt.
1. `runtime/reconcile-webdav.php`
2. `runtime/repair-webdav-orphans.php`
3. `runtime/cleanup-webdav-piwigo.php`
4. `runtime/sync-webdav.sh` für jede vorhandene WebDAV-Konfiguration
## Activity-Gate
Verbindungsspezifische Runtime-Konfigurationen liegen unter `/etc/bratonien-tools/nc-connector/`. Zustandsdaten liegen unter `/var/lib/bratonien-tools/nc-connector/connection-ID`.
Das Activity-Gate berücksichtigt neben dem Nextcloud-Aktivitätsstand auch die Signatur der aktuell sichtbaren Freigaben. Weiterhin vorhanden sind Quiet-Time, maximale Wartezeit, periodischer Full-Sync und verbindungsspezifischer State.
State-Verzeichnisse sind für die `www-data`-Gruppe traversierbar/lesbar. `webdav-map.json` wird auch nach atomaren Rewrites mit passenden Runtime-Rechten gehalten.
## Piwigo-Synchronisation
### Platzhalterquelle, Metadaten und Shadow Tree
### API-first
`runtime/lib/build_webdav_placeholder_source.py` bildet die Nextcloud-Inhalte als lokale Platzhalterquelle ab. Für Bilder existieren physische 1×1-Platzhalterdateien; Originale werden nicht dauerhaft heruntergeladen.
Der normale Runtime-Lauf verwendet ab `0.9.3.17` folgende Priorität:
Der WebDAV-Scan übernimmt `fileid`, `width`, `height`, MIME-Typ, Größe, ETag und WebDAV-Pfad in `webdav-map.json`. `runtime/lib/sync-webdav-metadata.php` überträgt die Originalmaße nach dem normalen Piwigo-Dateisync in `piwigo_images`.
1. gespeicherter Piwigo-API-Key;
2. bei API-Fehler, fehlender Freigabe für die installierte Piwigo-Version oder nicht vorhandener API: gespeicherter Benutzername/Passwort-Fallback;
3. ohne nutzbaren API- und Fallback-Zugang wird der Piwigo-Sync mit einer klaren Fehlermeldung abgebrochen.
Die physische Source-Struktur wird für den Runtime-Swap mit `root:www-data` und schreibbaren Gruppenrechten angelegt bzw. nach dem Sync gesetzt. Damit kann der Webserver die Platzhalterquelle während der On-Demand-Erzeugung temporär austauschen und anschließend wiederherstellen.
Nach einem Piwigo-Update wird die produktive API nicht automatisch für die neue Version freigeschaltet. Erst nach einem Kompatibilitätstest wird die Versionsfreigabe im Plugin angehoben. Bis dahin bleibt nur der Login-Fallback zulässig.
`runtime/lib/shadow_tree.py` erzeugt atomar die Piwigo-kompatible Dateisystemstruktur. Jede WebDAV-Verbindung besitzt ihre eigene Piwigo-Site.
### Physische Alben
### Piwigo-Synchronisierung
`bratonien.nc.syncProductive` ist aktuell nur für Piwigo **16.4.0** freigegeben. Der Endpoint läuft als Administrator-Webservice und verwendet für den eigentlichen Dateisync Piwigos Core-Synchronisierung. Neue Connector-Alben werden dabei privat angelegt.
`runtime/lib/piwigo-sync.php` bevorzugt `bratonien.nc.syncProductive` für Piwigo 16.4.0. Wenn keine Piwigo-API eingerichtet ist, wird der gespeicherte Administrator-/Webmaster-Fallback verwendet und Piwigos nativer `site_update` ausgeführt.
### Root-Dateien / Orphans
Danach läuft `bratonien.nc.syncOrphans` für die konkrete WebDAV-Site.
`bratonien.nc.syncOrphans` verarbeitet direkte Dateien im Galerie-Root separat. Neue Root-Dateien werden als Piwigo-Orphans ohne Albumzuordnung registriert. Entfernte Root-Dateien werden nur aus Piwigo entfernt; das Nextcloud-Original bleibt unberührt.
Albumdatensätze, Bilddatensätze, Bild-Kategorie-Verknüpfungen und Derivate bleiben Aufgabe von Piwigo.
## Erfolgreiche Live-Tests bis 0.9.3.16
### On-Demand-Materialisierung und Derivaterzeugung
Bestätigt wurden:
`include/webdav_materialize_runtime.inc.php` löst aus dem Piwigo-Bildpfad die konkrete Verbindung, den Nextcloud-Root, den relativen WebDAV-Pfad und die Mapping-Metadaten auf.
- Ordnerfreigaben werden korrekt eingelesen;
- Einzeldateifreigaben werden als `file` erkannt und im Galerie-Root verlinkt;
- Orphan-Anlage und Orphan-Löschung funktionieren;
- physische neue Connector-Alben werden privat angelegt;
- der automatische Timer kann regulär laufen.
Für ein noch nicht vorhandenes Derivat läuft `webdav-derivative.php`:
## Offener Test für 0.9.3.17
1. Zugriffsprüfung für das Piwigo-Bild;
2. Auswahl einer temporären Nextcloud-Quelle;
3. temporäres Bereitstellen dieser Quelle am exakten von Piwigo erwarteten Quellpfad;
4. Erzeugung des normalen Piwigo-Derivats mit Piwigos eigener `pwg_image`-/Derivative-Logik im selben PHP-Prozess;
5. Wiederherstellung des Shadow-/Platzhalterzustands;
6. Auslieferung des Piwigo-Derivats.
Vor Abschluss des API-first-Blocks muss noch live geprüft werden:
Ein interner HTTP-Self-Request auf `i.php` wird nicht verwendet.
1. Plugin-Update auf `0.9.3.17`;
2. API-Key im NC Connector prüfen und speichern;
3. produktiver Lauf verwendet `bratonien.nc.syncProductive` erfolgreich;
4. Ordner- und Orphan-Sync bleiben unverändert korrekt;
5. gespeicherter Login-Fallback übernimmt bei absichtlich nicht nutzbarer API;
6. einmaliger Fallback funktioniert ohne Speicherung;
7. gelöschter Fallback wird vom Runtime-Lauf nicht mehr verwendet.
Für `custom:s9999x250` und `standard:square` wird bevorzugt der authentifizierte Nextcloud-Endpunkt **`/index.php/core/preview`** anhand der `fileid` verwendet. Die Preview wird mit ungefähr doppelter benötigter Piwigo-Auflösung und unter Berücksichtigung des Original-Seitenverhältnisses angefordert. Varianten mit Bildrotation werden in dieser Stufe nicht über Preview erzeugt.
## Sicherheit / Betriebsmodell
Ist keine geeignete Preview planbar oder schlägt der Preview-Abruf fehl, erfolgt der vollständige WebDAV-Originaldownload. Große/originale Anforderungen verwenden weiterhin die Originalquelle.
- Nextcloud bleibt Eigentümer der Originaldateien.
- Der Connector löscht keine Originaldateien aus den Storage-Mounts.
- API- und Login-Zugangsdaten werden verschlüsselt gespeichert und nicht in das Repository geschrieben.
- Die API hat Vorrang, ist aber streng versionsgebunden.
- Benutzername/Passwort ist nur Fallback und kann dauerhaft, einmalig oder gar nicht verwendet werden.
- Neue Connector-Alben werden privat angelegt.
Die temporäre Preview bzw. das temporäre Original wird nach der Derivaterzeugung entfernt. Das fertige Derivat verbleibt ausschließlich in Piwigos normalem `_data/i`-Cache. Es gibt keinen parallelen permanenten Connector-Derivat-Cache.
## Bekannte offene Punkte
### Piwigo-Lazyload
Der NC Connector bleibt im Entwicklungsblock `0.9.3.x`. Nach erfolgreichem API-first-Livetest folgen insbesondere:
Piwigos nativer Thumbnail-Loader ruft nicht gecachte Derivate mit `ajaxload=true` per AJAX ab und erwartet JSON mit einer fertigen `url`.
- Bereinigung und Vereinfachung der Verbindungsverwaltung im Admin-UI;
- Remote-Nextcloud-Adapter;
- Entscheidung über verbleibende Legacy-/Migrationshilfen;
- weitere Komfortfunktionen für Status, Diagnose und Administration.
`webdav-derivative.php` unterstützt dieses Protokoll für:
## Repository-Fallback
- bereits vorhandene Zielderivate;
- `target_created_while_waiting`;
- frisch erzeugte Derivate.
Während der Entwicklung bleibt GitHub das führende Repository. Zusätzlich existiert auf dem privaten Gitea-System ein Pull-Mirror als Ausfall-/Fallback-Ebene.
Normale direkte Bildanforderungen liefern weiterhin das Bild selbst. Dadurch kann Piwigos eigener Placeholder nach erfolgreicher Erzeugung ohne Seiten-Reload durch das echte Thumbnail ersetzt werden.
### Bilddetail-Navigation
Die eigene Bildnavigation liegt in `js/picture_navigation.js` und `css/picture_navigation.css`. Der aktuelle Stand enthält die Behandlung des sichtbaren Zwischenzustands für WebDAV-Nachbar-Thumbnails, damit während des Nachladens kein Browser-Symbol für ein kaputtes Bild stehen bleiben soll.
### Orphan-Logik
Direkt im WebDAV-Site-Root liegende Bilder werden nicht künstlich in ein Album gezwungen. Sie werden durch `bratonien.nc.syncOrphans` als Piwigo-Orphans synchronisiert.
`runtime/repair-webdav-orphans.php` läuft vor den verbindungsspezifischen Syncs und repariert historische WebDAV-Orphan-Zustände.
### Private Top-Level-Alben
WebDAV-Unterordner können echte private Top-Level-Piwigo-Alben sein. Beim Connector-Fallback-Sync sorgt `bratonien_tools_preserve_connector_top_level_access()` dafür, dass der verwendete Piwigo-Administrator den Zugriff behält. Nach Änderungen wird der Benutzer-Cache invalidiert.
Die allgemeine Funktion `bratonien_tools_preserve_private_album_access()` in `include/album_shares.inc.php` bleibt davon getrennt.
### Administrations-Dashboard
Für Piwigo 16.4.0 wird ausschließlich die Standardtemplate-Bedingung der Album-Kachel von `NB_ALBUMS > 1` auf `NB_ALBUMS > 0` angepasst. Die Albumzahl selbst stammt unverändert aus Piwigo.
### Bildauslieferung
Fehlende Piwigo-Derivate werden durch den On-Demand-Gate erzeugt. Bereits vorhandene Derivate werden direkt aus Piwigos eigenem Derivat-Cache ausgeliefert.
Für direkte Originalanforderungen existiert weiterhin die serverseitige WebDAV-Originalauslieferung. Nextcloud-Zugangsdaten werden dem Browser nicht offengelegt.
### Diagnose
Der WebDAV-Derivative-Gate schreibt Request-bezogene `[BRAT-WD ...]`-Diagnoseeinträge. Relevante Ereignisse sind unter anderem `preview_start`, `preview_failed`, `download_done`, `swap_begin`, `swapped`, `generate_start`, `generate_done`, `restored`, `target_created_while_waiting` und `serve`.
## Self-Updater
`include/self_update.inc.php` liest den Zielstand von GitHub, bindet ihn an einen konkreten Commit, prüft die `main.inc.php` per SHA-256, erstellt vor dem Austausch ein Backup und aktualisiert nur auf eine **höhere** Plugin-Version.
Das verbindliche Versionsschema ist **0.x.x.x.x**.
## Aktuell relevante Dateien
- `main.inc.php` Plugin-Hooks und Version
- `include/self_update.inc.php` integrierter Self-Updater
- `include/webdav_materialize_runtime.inc.php` WebDAV-Quellauflösung und Gate-URL-Erzeugung
- `webdav-derivative.php` On-Demand-Gate, Preview/Original-Fallback, Piwigo-Derivaterzeugung und AJAX-Lazyload-Antwort
- `webdav-image.php` direkte WebDAV-Originalauslieferung
- `include/nc_productive_ws.inc.php` direkter Piwigo-Core-Sync für 16.4.0
- `include/nc_orphan_ws.inc.php` Root-Orphan-Synchronisierung
- `runtime/reconcile-webdav.php` Runtime-Reconcile und State-Berechtigungen
- `runtime/repair-webdav-orphans.php` Orphan-Reparatur
- `runtime/cleanup-webdav-piwigo.php` Bereinigung verwaister Piwigo-Sites
- `runtime/sync-webdav.sh` verbindungsspezifischer Sync und Runtime-/Source-Berechtigungen
- `runtime/run-all.sh` gemeinsamer Runner
- `runtime/lib/build_webdav_placeholder_source.py` WebDAV-Scan, Mapping und Platzhalterquelle
- `runtime/lib/sync-webdav-metadata.php` Übernahme der Originalmaße nach Piwigo
- `runtime/lib/shadow_tree.py` atomarer Shadow Tree
- `runtime/lib/piwigo-sync.php` Piwigo-API/Fallback-Sync
- `js/picture_navigation.js` Bilddetail-Navigation und Thumbnail-Zwischenzustand
- `css/picture_navigation.css` Bilddetail-Navigationsdarstellung
## Nicht mehr das produktive WebDAV-Modell
Nicht mehr maßgeblich sind ein separater permanenter WebDAV-Derivatbestand oder ein interner HTTP-Aufruf von `webdav-derivative.php` zurück auf Piwigos `i.php`.
Maßgeblich ist:
**physischer Platzhalter + temporäre Nextcloud-Preview bzw. Original-Fallback + Piwigos Bildverarbeitung im selben PHP-Prozess + normales Piwigo-Derivat + Wiederherstellung des Platzhalters**.
## Prüfpflicht vor Merge
Die GitHub-Actions-Konfiguration prüft mindestens:
- PHP-Syntax für 8.2, 8.3, 8.4 und 8.5
- doppelte globale `bratonien_tools_*`-Funktionen
- JavaScript-Syntax
- Python-Syntax/Compile
- Shell-Syntax mit `bash -n`

437
README.md
View File

@@ -1,303 +1,232 @@
# Piwigo Bratonien Tools
Modular aufgebautes Piwigo-Plugin mit erweiterten Werkzeugen fuer Administration, Bildverarbeitung, Nextcloud-Anbindung und Frontend-Funktionen.
Modulares Piwigo-Plugin r Administration, Bildverarbeitung, geschützte Freigaben, Fotoauswahl und die Anbindung von Nextcloud an Piwigo.
Das Projekt ist aus der Bratonien-Piwigo-Installation entstanden, wird aber bewusst so entwickelt, dass die einzelnen Funktionen moeglichst neutral und auch ausserhalb dieser Installation nutzbar bleiben.
Aktuelle Plugin-Version: **0.9.7.1.7**
Aktuelle Plugin-Version: **0.9.3.16**
## Grundprinzip
## Funktionsumfang
Bratonien Tools erweitert Piwigo um Funktionen, die in der Bratonien-Installation benötigt werden, hält die einzelnen Module aber möglichst unabhängig voneinander.
### NC Connector
Für die Administration gilt: Der normale Nutzer sieht Aufgaben, Entscheidungen und Ergebnisse. Technische Interna werden automatisch ermittelt oder bleiben hinter ausdrücklich technischen Einstellungen verborgen.
Der NC Connector verwaltet Nextcloud-Quellen fuer Piwigo und fuehrt den regelmaessigen Abgleich mit einer Plugin-eigenen Sync-Runtime aus.
## NC Connector
Aktuell vorhanden:
Der NC Connector bindet ausdrücklich ausgewählte Nextcloud-Inhalte per WebDAV an Piwigo an. Nextcloud bleibt dabei die Quelle der Originaldateien; Piwigo verwaltet Alben, Bilder und seine eigenen Derivate.
- mehrere Connector-Verbindungen im eigenen Datenmodell
- lokale Verbindungen direkt in Bratonien Tools anlegen
- verschluesselte Speicherung von PostgreSQL- und Piwigo-Sync-Zugangsdaten
- lokaler Nextcloud-Adapter ueber PostgreSQL-Reader und explizite Storage-Mounts
- Verifikation von PostgreSQL-Verbindung, Source-View, Activity-View und Storage-Mounts
- native Aktivierung einer verifizierten Verbindung ohne vorherige Legacy-Installation
- eigener State pro Verbindung unter `/var/lib/bratonien-tools/nc-connector/connection-ID`
- gemeinsame Runtime-Konfiguration unter `/etc/bratonien-tools/nc-connector/`
- Multi-Connection-Runner unter `runtime/run-all.sh`
- gemeinsame Zeitsteuerung ueber `bratonien-nc-connector.timer`
- Verbindungen koennen kontrolliert deaktiviert und danach geloescht werden
- Anzeige von Timer-Status, letztem Lauf, letztem Ergebnis und naechstem geplanten Lauf
- Plugin-eigene Sync-Runtime unter `runtime/`
- Activity-Gate mit Quiet-Time, Max-Wartezeit, Share-Fingerprint und periodischem Full-Sync
- Shadow Tree fuer Piwigo ohne Kopie der Originaldateien
- Unterstuetzung von Nextcloud-Freigaben fuer komplette Ordner und einzelne Dateien
- Ordnerfreigaben werden als physische Piwigo-Alben synchronisiert
- neu importierte Connector-Alben werden direkt als privat angelegt
- einzelne Dateifreigaben werden direkt im Galerie-Root verlinkt und als echte Piwigo-Orphans registriert
- entfernte Einzeldateifreigaben werden beim naechsten Lauf wieder aus Piwigo entfernt, ohne das Original zu loeschen
- Originalbilder bleiben an ihrer Nextcloud-/Storage-Quelle
- lokale Piwigo-Derivate und Caches bleiben davon getrennt und koennen jederzeit neu erzeugt werden
### Datenmodell
Die Runtime baut aus den freigegebenen Nextcloud-Quellen einen Piwigo-kompatiblen Shadow Tree. Dateien werden dabei nicht in eine zweite permanente Originalbibliothek kopiert, sondern ueber Symlinks auf die vorhandenen Storage-Mounts referenziert.
- Nextcloud bleibt die verbindliche Quelle der Originaldateien.
- Originalbilder werden nicht dauerhaft als zweite vollständige Bibliothek unter Piwigo gespeichert.
- Eine lokale Platzhalterquelle enthält physische 1×1-Dateien, damit Piwigo die Bilder regulär als Dateisysteminhalte erkennen kann.
- Ein Shadow Tree bildet daraus die von Piwigo erwartete Galerie-Ordnerstruktur.
- Ordner werden als physische Piwigo-Alben synchronisiert.
- Direkt im ausgewählten Nextcloud-Root liegende Einzelbilder werden über die vorhandene Orphan-Logik behandelt.
- Neu importierte physische Connector-Alben werden privat angelegt.
- Entfernte Quellen verschwinden aus Shadow Tree und Piwigo; die Nextcloud-Originale bleiben erhalten.
#### Freigabemodell
### Nextcloud-Root ohne künstliches Benutzeralbum
Der Connector unterscheidet zwei Quelltypen:
Ein leerer `webdav_path` ist ein gültiger Root und bedeutet den Dateibereich des authentifizierten Nextcloud-Benutzers.
- `folder` - komplette Ordnerfreigabe; der Verzeichnisbaum wird gespiegelt und ueber Piwigos normale Dateisynchronisierung als Albumstruktur eingelesen
- `file` - einzelne Dateifreigabe; die Datei wird direkt als Symlink im Galerie-Root angelegt und separat als Piwigo-Orphan ohne Albumzuordnung registriert
Dabei wird der Nextcloud-Benutzername nicht als künstliche Album-Ebene angelegt. Beispiel:
Fuer Einzeldateien wird kein kuenstlicher Unterordner erzeugt. Entfernt Nextcloud eine solche Freigabe, entfernt der Connector den Root-Symlink und anschliessend nur den zugehoerigen Piwigo-Datenbankeintrag. Das Original bleibt unangetastet.
```text
Nextcloud
/
├── 400 Auswahl/
├── Zweites Album/
├── einzelbild-1.jpg
└── einzelbild-2.jpg
```
#### Neuinstallation
wird in Piwigo logisch als
Eine frische Piwigo-Installation benoetigt keinen vorher vorhandenen `piwigo-sync` mehr.
```text
400 Auswahl
Zweites Album
```
Der vorgesehene Ablauf ist:
abgebildet. Die direkt im Root liegenden Einzelbilder werden separat durch die Orphan-Synchronisierung erfasst.
1. lokale Nextcloud-Verbindung in Bratonien Tools anlegen
2. PostgreSQL, Views und Storage-Mounts pruefen
3. die angezeigte Root-Aktivierung ausfuehren
4. der Installer legt Runtime-Konfiguration, Secrets, State-Verzeichnis sowie systemd-Service und -Timer an
5. vor der Aktivierung wird ein echter Lauf mit der Plugin-Runtime getestet
### Voraussetzungen
Der gemeinsame Service verarbeitet alle aktivierten `connection-*.conf`-Dateien nacheinander. Dadurch koennen mehrere Verbindungen mit einer gemeinsamen Zeitsteuerung betrieben werden.
Benötigt werden nur:
#### Migration bestehender Installationen
- Nextcloud-Adresse;
- Nextcloud-Benutzer bzw. App-Passwort;
- normaler WebDAV-Zugriff auf die Inhalte dieses Benutzers;
- eine normale Piwigo-Installation mit ihrer vorhandenen PHP-/Bildverarbeitungsumgebung.
Fuer bestehende Installationen, die zuvor den separaten `piwigo-sync` aus `Proxmox_Scripts` verwendet haben, existiert weiterhin ein kontrollierter Migrationsweg:
Nicht benötigt werden Nextcloud-Datenbankzugriff, `occ`-Adminzugriff, Storage-IDs, Backend-Pfade, zusätzliche Host-Mounts, FUSE, davfs oder rclone.
- bestehende Verbindung einmalig importieren
- Connector-Kopie unabhaengig verifizieren
- kontrollierten Cutover vorbereiten
- Connector-Timer aktivieren und Legacy-Timer deaktivieren
- Runtime vom bisherigen `/opt/piwigo-sync` auf die Plugin-eigene Runtime umstellen
- Legacy-Bestand entfernen
- den verbliebenen Laufzeit-State anschliessend mit `nc-connector-normalize.php` in die native Struktur unter `/var/lib/bratonien-tools/nc-connector/` ueberfuehren
### WebDAV-Scan und Shadow Tree
Nach abgeschlossener Migration werden `/opt/piwigo-sync`, `/etc/piwigo-sync`, `piwigo-sync.service` und `piwigo-sync.timer` nicht mehr benoetigt.
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, Originalabmessungen 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 atomar 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.
8. Piwigos Dateisynchronisierung erhält ausschließlich diese verbindungseigene Site.
9. `runtime/lib/sync-webdav-metadata.php` übernimmt die von Nextcloud gelieferten Originalmaße in Piwigos Bilddatensätze.
### Bildcache
State-Verzeichnisse und Mapping-Dateien werden so berechtigt, dass der Webserver die Laufzeitdaten lesen kann. Die physische Platzhalterquelle wird mit der für den temporären Source-Swap nötigen `www-data`-Gruppenberechtigung erzeugt bzw. nach dem Sync gesetzt.
- Piwigo-Bildcache gezielt leeren
- vorhandene Bildderivate neu erzeugen
- Cache-Aufbau als Worker-Prozess starten und abbrechen
- Worker-Einstellungen verwalten
- Originalbilder bleiben unangetastet
### On-Demand-Bildauslieferung und Piwigo-Derivate
### Wasserzeichenverwaltung
`include/webdav_materialize_runtime.inc.php` erkennt anhand des Piwigo-Bildpfads die zugehörige WebDAV-Verbindung, den Nextcloud-Root und den relativen WebDAV-Pfad. Aus dem Mapping stehen zusätzlich `fileid`, Originalbreite/-höhe, MIME-Typ, Dateigröße und ETag zur Verfügung. Der Hook `get_derivative_url` leitet fehlende WebDAV-Derivate an `webdav-derivative.php` um.
Erweiterte Wasserzeichenverwaltung als Alternative zur einfachen Piwigo-Standardkonfiguration.
Wenn ein benötigtes Piwigo-Derivat noch nicht existiert:
Unter anderem vorhanden:
1. `webdav-derivative.php` prüft den Piwigo-Zugriff auf das Bild.
2. Für `custom:s9999x250` und `standard:square` wird bevorzugt eine passende authentifizierte Nextcloud-Preview anhand der `fileid` über `/index.php/core/preview` geladen. Die Preview wird mit ungefähr doppelter benötigter Piwigo-Auflösung und erhaltenem Seitenverhältnis angefordert.
3. Ist keine passende Preview planbar oder schlägt der Preview-Abruf fehl, wird automatisch das vollständige Original per WebDAV geladen. Große bzw. originale Anforderungen verwenden weiterhin die Originalquelle.
4. Die temporäre Bildquelle ersetzt für die Dauer der Erzeugung die physische 1×1-Platzhalterdatei bzw. den Shadow-Link am von Piwigo erwarteten Quellpfad.
5. Piwigos eigene `pwg_image`-/Derivative-Logik erzeugt das normale Piwigo-Derivat direkt im selben PHP-Prozess. Ein interner HTTP-Self-Request auf `i.php` wird nicht verwendet.
6. Danach wird die temporäre Bildquelle entfernt und der Platzhalter-/Shadow-Zustand wiederhergestellt.
7. Das fertige Derivat wird ausgeliefert und künftig normal aus Piwigos `_data/i`-Derivat-Cache verwendet.
- eigene Wasserzeichendateien
- Wasserzeichenprofile
- Standardprofil
- albumbezogene Regeln
- getrennte Einstellungen fuer Positionierung und Verarbeitung
- eigener Runtime-Filter fuer Piwigo-Bildderivate
- Aktivierung und Deaktivierung der erweiterten Wasserzeichen-Engine
Piwigos nativer Thumbnail-Loader verwendet bei nicht gecachten Thumbnails `ajaxload=true` und erwartet eine JSON-Antwort mit der fertigen Derivat-URL. `webdav-derivative.php` unterstützt dieses Protokoll; normale direkte Bildanforderungen werden weiterhin als Bild ausgeliefert. Dadurch kann Piwigos eigener Placeholder nach der Erzeugung ohne Seiten-Reload durch das fertige Thumbnail ersetzt werden.
Beim Aktivieren wird die bisherige Piwigo-Wasserzeichenkonfiguration gesichert und nicht dauerhaft ueberschrieben. Beim Deaktivieren kann sie wiederhergestellt werden.
Damit bleibt Piwigo für Größen, Derivate und Lazy-Loading verantwortlich. Der Connector hält keinen parallelen eigenen vollständigen Derivat-Cache vor.
### Bilddateien & Pfade
Für Fälle, in denen Piwigo direkt die Originalquelle benötigt, steht weiterhin die serverseitige WebDAV-Auslieferung zur Verfügung. Nextcloud-Zugangsdaten werden nicht an den Browser weitergegeben.
Verwaltung eigener Bilddateien fuer die Piwigo-Installation.
### Piwigo-Synchronisierung
- Upload nach `local/bratonien/assets/`
- Vorschau vorhandener Dateien
- Anzeige von Dateiname, Pfad, Abmessungen und Dateigroesse
- Dateien loeschen
- konfigurierbare PHP-Uploadgrenzen ueber `.user.ini`
- Validierung von `upload_max_filesize` und `post_max_size`
Der Connector verwendet die vorhandene Piwigo-Dateisynchronisierung für die verbindungseigene WebDAV-Site. Der Shadow Tree ist ausschließlich die Dateisystemdarstellung, die Piwigo für Alben und Bilder benötigt.
### Oeffentliche Bildauswahl fuer Batch Downloader
`runtime/lib/piwigo-sync.php` bevorzugt die Webservice-Methode `bratonien.nc.syncProductive`. Ist keine Piwigo-API für die Verbindung eingerichtet, wird der vorhandene Administrator-/Webmaster-Benutzername/Passwort-Fallback verwendet und Piwigos nativer `site_update` ausgeführt.
Erweitert Albumseiten um die Moeglichkeit, einzelne Bilder fuer einen Download auszuwaehlen.
Nach der regulären Dateisynchronisierung läuft `bratonien.nc.syncOrphans` für direkt im Site-Root liegende Einzelbilder.
- Auswahlmodus direkt in der Albumansicht
- einzelne Bilder markieren
- alle Bilder auswaehlen oder Auswahl aufheben
- nur die ausgewaehlten Bilder an Batch Downloader uebergeben
- vorhandene Piwigo- und Batch-Downloader-Berechtigungen bleiben wirksam
- getrennte Freigabe fuer Gaeste, registrierte Benutzer und Gruppen
Die produktive Synchronisierung ist aktuell auf **Piwigo 16.4.0** abgestimmt.
**Abhaengigkeit:** Das Piwigo-Plugin Batch Downloader muss installiert und aktiv sein.
### Private Top-Level-Alben
Die ZIP-Erstellung wird nicht dupliziert. Bratonien Tools uebergibt lediglich die berechtigten Bild-IDs an Batch Downloader.
Durch das Überspringen der technischen Nextcloud-Benutzerebene können WebDAV-Unterordner zu echten Top-Level-Piwigo-Alben werden. Für den Connector-Sync wird deshalb der Zugriff des verwendeten Piwigo-Administrators auf neu erzeugte private Top-Level-Alben erhalten und der Benutzer-Cache anschließend invalidiert.
### Fortlaufende Bildtitel in der Stapelverarbeitung
### Administrations-Dashboard
Erweitert Piwigos globale Stapelverarbeitung um die Aktion **Fortlaufende Bildtitel**.
Piwigo 16.4.0 blendet seine Album-Statistik standardmäßig bei exakt einem Album aus (`NB_ALBUMS > 1`). Bratonien Tools passt ausschließlich diese Dashboard-Anzeige auf `NB_ALBUMS > 0` an. Dadurch wird auch ein einzelnes korrekt angelegtes Album in der Verwaltungsübersicht angezeigt.
- arbeitet ausschliesslich mit der aktuellen Piwigo-Auswahl
- frei waehlbares Titelpraefix
- frei waehlbare Startnummer
- einstellbare Stellenzahl mit fuehrenden Nullen
- direkte Vorschau des resultierenden Titelformats
- wahlweise alle ausgewaehlten Titel ueberschreiben oder nur leere beziehungsweise typische Kamera-/Importtitel ersetzen
- Reihenfolge nach Dateiname, Aufnahmedatum oder aktueller Albumreihenfolge
- vorhandene individuelle Titel koennen gezielt geschuetzt werden
- physische Dateinamen werden nicht veraendert
### Statusanzeige
Beispiel: `Samt 2026 - 001`, `Samt 2026 - 002`, `Samt 2026 - 003`.
Die Administration zeigt Laufzeitstatus und Fehler pro Verbindung. Fehlerdetails bleiben der betroffenen Verbindung zugeordnet.
Die Albumreihenfolge steht nur zur Verfuegung, wenn die Stapelverarbeitung auf genau ein Album ohne rekursive Unteralben gefiltert ist.
### Löschen einer Verbindung
### Albumzugriff verwalten
Beim Löschen einer WebDAV-Verbindung werden ihre zugehörige Piwigo-Site und die dazugehörigen Piwigo-Datensätze entfernt. Nextcloud-Dateien bleiben unverändert. Runtime-, Shadowtree-, Source-, Preview- und Statusdaten werden bereinigt.
In der Administrationsoberflaeche koennen Alben direkt zwischen **oeffentlich** und **privat** umgeschaltet werden.
### Runtime
- Albumliste mit Suchfeld
- paginierte Darstellung
- Umschalten des Zugriffs direkt aus Bratonien Tools
- Verwendung nativer Piwigo-Icons fuer den Zugriffsstatus
- beim Sperren eines Albums behaelt der aktuell handelnde Benutzer automatisch direkten Zugriff
Der Schutz vor versehentlichem Selbstaussperren greift auch dann, wenn ein Album ueber Piwigos eigene Album-Zugriffsverwaltung von oeffentlich auf privat gesetzt wird.
### Geschuetzte Albumfreigaben
Private Alben koennen direkt mit Bratonien Tools geteilt werden. ShareAlbum oder ein anderes Freigabe-Plugin ist dafuer nicht erforderlich.
- eigener individueller Freigabelink pro Freigabe
- Passwort **optional**; ohne Passwort reicht der nicht erratbare Link
- Passwoerter werden nur als Hash gespeichert
- integrierter Generator fuer sichere Passwoerter
- erzeugte Passwoerter koennen angezeigt und kopiert werden
- optionales Ablaufdatum
- optionaler Freigabe-Tag, um mehrere Freigaben desselben Albums auseinanderzuhalten
- eigener technischer Piwigo-Benutzer pro Freigabe
- der technische Benutzer erhaelt nur Zugriff auf das freigegebene private Album
- aktive Freigabelinks werden in der Administration angezeigt und koennen direkt kopiert werden
- bei aelteren, nicht rekonstruierbaren Links kann ein neuer Link erzeugt werden; der bisherige Link wird dabei ungueltig
- Freigaben koennen einzeln widerrufen werden
- beim Widerruf wird der technische Benutzer samt Sitzungen und Albumrecht entfernt
- wird das Album geloescht, werden zugehoerige Freigaben automatisch bereinigt
Freigabe-Tokens werden nicht im Klartext gespeichert. Fuer aktuelle Freigaben kann der Link deterministisch aus dem technischen Freigabebenutzer, dem Album und einem lokal gespeicherten Secret rekonstruiert werden; in der Datenbank liegt nur der Hash des Tokens.
### Erweiterte Bildnavigation
Auf der Bilddetailseite werden die vorhandenen Piwigo-Image-Maps weiterverwendet und responsiv neu aufgeteilt.
Die Bildflaeche besteht aus vier Navigationszonen:
- links: vorheriges Bild
- rechts: naechstes Bild
- oben mittig: zurueck zur Vorschau beziehungsweise Albumansicht
- Mitte: PhotoSwipe / Vollbildansicht
Die Zonen werden anhand der aktuell dargestellten Bildgroesse berechnet und bei Groessenaenderungen neu gesetzt.
Fuer die sichtbaren Hover-Elemente werden neutrale CSS-Klassen bereitgestellt. Das Plugin enthaelt bewusst kein Bratonien-spezifisches Farbschema. Individuelles Branding kann ueber Theme- oder Custom-CSS erfolgen.
### Selbstaktualisierung
Bratonien Tools kann den aktuellen Stand des GitHub-Repositories pruefen und sich aus der Administration heraus aktualisieren.
- Versionspruefung gegen `main.inc.php` im GitHub-Repository
- Update-Pruefung wird kurzzeitig zwischengespeichert
- Updates duerfen nur vom Piwigo-Webmaster ausgefuehrt werden
- Download des aktuellen `main`-Branches als ZIP
- Pruefung auf `ZipArchive` und Schreibrechte des Plugin-Verzeichnisses
- detailliertere Downloadfehler
- Status wird nach Update-Pruefungen und Aktionen neu eingelesen
## Architektur
Das Plugin ist modular aufgebaut. Administrative Werkzeuge werden getrennt implementiert und ueber eine zentrale Registry eingebunden. Frontend-, Runtime- und Piwigo-Integrationen liegen ebenfalls in eigenen Modulen.
Wichtige Bestandteile:
- `main.inc.php` - Plugin-Einstieg, Runtime-Module und Admin-Menue
- `admin.php` - zentraler Admin-Controller
- `include/tool_registry.inc.php` - Registry der administrativen Aktionen
- `include/nc_connector.inc.php` - Connector-Datenmodell, Legacy-Import und gemeinsame Low-Level-Funktionen
- `include/nc_connector_manage.inc.php` - native Connection-Verwaltung und Verifikation
- `include/nc_connector_takeover.inc.php` - kontrollierte Legacy-Uebergabe
- `include/nc_connector_system.inc.php` - Timer- und Laufzeitstatus ueber alle aktiven Verbindungen
- `include/nc_connector_ws.inc.php` - read-only Paritaets-/Synchronisationspruefung ueber den Piwigo-Webservice
- `include/nc_orphan_ws.inc.php` - produktive Synchronisation einzelner Root-Dateien als Piwigo-Orphans
- `runtime/sync.sh` - Plugin-eigene Sync-Runtime einer Verbindung
- `runtime/run-all.sh` - gemeinsamer Runner fuer alle installierten Verbindungen
- `runtime/lib/activity_gate.py` - Activity-Gate, Share-Fingerprint und zeitgesteuerte Reconciliation
- `runtime/lib/build_manifest.py` - Aufloesung von Ordner- und Dateifreigaben auf konfigurierte Storage-Mounts
- `runtime/lib/shadow_tree.py` - Aufbau des Piwigo-kompatiblen Shadow Trees ohne Kopieren der Originale
- `runtime/lib/piwigo-db-check.php` - Konsistenzpruefung vorhandener Piwigo-Alben
- `runtime/lib/piwigo-db-sync.pl` - Ausloesen der Piwigo-Dateisynchronisierung und anschliessender Orphan-Abgleich
- `nc-connector-install.php` - native Aktivierung einer verifizierten Verbindung
- `nc-connector-disable.php` - kontrollierte Deaktivierung einer aktiven Verbindung
- `nc-connector-normalize.php` - Ueberfuehrung einer migrierten aktiven Verbindung in den nativen State- und Multi-Connection-Aufbau
- `nc-connector-migrate.php` - einmaliger Migrationshelfer fuer bestehende Legacy-Installationen
- `nc-connector-cutover-v2.php` - kontrollierter Legacy-Cutover
- `nc-connector-runtime-switch.php` - Umstellung einer aktiven Legacy-Verbindung auf die Plugin-eigene Runtime
- `nc-connector-legacy-cleanup.php` - kontrollierte Entfernung alter Sync-Scripts und systemd-Units
- `include/public_selection.inc.php` - oeffentliche Fotoauswahl und Batch-Downloader-Anbindung
- `include/picture_navigation.inc.php` - Einbindung der erweiterten Bildnavigation
- `include/batch_titles.inc.php` - fortlaufende Titelvergabe in Piwigos Stapelverarbeitung
- `include/album_lock.inc.php` - Laden und Umschalten des Album-Zugriffsstatus
- `include/album_shares.inc.php` - Albumfreigaben, Freigabetokens und Schutz vor Selbstaussperren bei privaten Alben
- `include/cache_worker_settings.inc.php` - Einstellungen fuer den Cache-Worker
- `include/dependencies.inc.php` - Abhaengigkeitspruefungen
- `include/watermark_*.inc.php` - Wasserzeichen-Engine und Runtime
- `include/self_update.inc.php` - Versionspruefung und Selbstaktualisierung
- `tools/album_rules.inc.php` - albumbezogene Regeln
- `tools/asset_manager.inc.php` - Verwaltung eigener Bilddateien
- `tools/image_cache.inc.php` - Cache-Verwaltung
- `tools/watermark*.inc.php` - administrative Wasserzeichenmodule
- `main-cache-build.php` - Cache-Aufbau im Worker-Prozess
- `main-cache-status.php` - Statusschnittstelle fuer den Cache-Worker
- `js/` - Frontend- und Admin-JavaScript
- `css/` - strukturelles Plugin-CSS
- `template/` - Admin- und Frontend-Templates
- `maintain.class.php` - Piwigo-Lifecycle
## Neues administratives Tool hinzufuegen
1. Neue Implementierung unter `tools/` anlegen.
2. Datei in `include/tool_registry.inc.php` laden.
3. Handler in `bratonien_tools_get_tools()` registrieren.
4. Benoetigte Darstellung in der gemeinsamen Administrationsoberflaeche ergaenzen.
Funktionen sollten moeglichst eigenstaendig bleiben und keine Bratonien-spezifische Gestaltung voraussetzen.
Aktive WebDAV-Verbindungen werden über den gemeinsamen Runner verarbeitet:
- `bratonien-nc-connector.timer`
- `bratonien-nc-connector.service`
- `runtime/run-all.sh`
Verbindungsspezifische Konfigurationen liegen unter `/etc/bratonien-tools/nc-connector/`, State-Daten unter `/var/lib/bratonien-tools/nc-connector/connection-ID`.
Der gemeinsame Lauf besteht aktuell aus:
1. `runtime/reconcile-webdav.php` gespeicherte Verbindungen in Runtime-Konfigurationen überführen;
2. `runtime/repair-webdav-orphans.php` vorhandene WebDAV-Orphan-Zustände reparieren;
3. `runtime/cleanup-webdav-piwigo.php` verwaiste WebDAV-Piwigo-Daten bereinigen;
4. `runtime/sync-webdav.sh` jede vorhandene WebDAV-Verbindung synchronisieren.
Der verbindungsspezifische Lauf erzeugt Platzhalterquelle und Shadow Tree, setzt die Laufzeitberechtigungen, führt Piwigos Sync und Orphan-Sync aus und überträgt anschließend die Originalabmessungen aus dem WebDAV-Mapping in Piwigo. Eine vollständige Vorab-Erzeugung von Connector-Derivaten findet nicht statt; fehlende Derivate werden On-Demand erzeugt.
## Bildcache
Bratonien Tools kann Piwigo-Bildderivate gezielt leeren, vorhandene Bildgrößen neu erzeugen und den Cache-Aufbau als Worker-Prozess starten bzw. abbrechen. Originalbilder bleiben unangetastet.
## Wasserzeichenverwaltung
- eigene Wasserzeichendateien;
- Wasserzeichenprofile;
- globale Regeln für öffentliche/private Alben;
- Album-Ausnahmen und Vererbung;
- Position, Transparenz und Skalierung;
- eigener Runtime-Filter für Piwigo-Derivate;
- Sicherung der bisherigen Piwigo-Wasserzeichenkonfiguration beim Aktivieren.
## Bilddateien und Pfade
- Upload nach `local/bratonien/assets/`;
- Vorschau, Abmessungen und Dateigröße;
- Löschen verwalteter Assets;
- konfigurierbare PHP-Uploadgrenzen über `.user.ini`, sofern die Serverkonfiguration dies zulässt.
## Fotoauswahl und Batch Downloader
Bratonien Tools erweitert Albumseiten um eine öffentliche bzw. berechtigungsabhängige Bildauswahl und übergibt nur die ausgewählten Bild-IDs an das Piwigo-Plugin Batch Downloader.
**Abhängigkeit:** Batch Downloader muss installiert und aktiv sein.
## Fortlaufende Bildtitel
Die globale Piwigo-Stapelverarbeitung erhält die Aktion **Fortlaufende Bildtitel** mit Präfix, Startnummer, Stellenzahl, Sortierung und Schutz vorhandener individueller Titel. Physische Dateinamen werden nicht verändert.
## Albumzugriff
Alben können in Bratonien Tools zwischen öffentlich und privat umgeschaltet werden. Beim Sperren wird verhindert, dass sich der handelnde Benutzer versehentlich selbst aussperrt.
## Geschützte Albumfreigaben
Private Alben können über eigene Freigabelinks geteilt werden, optional mit Passwort und Ablaufdatum. Die Freigaben verwenden einen technischen Piwigo-Benutzer mit minimalem Albumzugriff und können widerrufen werden.
## Erweiterte Bildnavigation
Die Piwigo-Bilddetailseite erhält responsive Navigationszonen für vorheriges Bild, nächstes Bild, Rückkehr zur Übersicht und PhotoSwipe/Vollbild. Für WebDAV-Nachbar-Thumbnails wird der sichtbare Ladezustand so behandelt, dass während eines noch laufenden Bildabrufs kein Browser-Symbol für ein kaputtes Bild stehen bleiben soll.
## Selbstaktualisierung
Der integrierte Updater liest den Zielstand aus GitHub, bindet ein Update an einen konkreten Commit, prüft Version und SHA-256, erstellt vor dem Austausch ein Backup und verlangt Webmaster-Rechte sowie die notwendigen Servervoraussetzungen. Das verbindliche Versionsschema des Plugins ist **0.x.x.x.x**; Updates werden nur auf eine höhere Version angeboten.
## Wichtige Dateien und Verzeichnisse
- `main.inc.php` Plugin-Einstieg, Hooks, Connector-Sync-Hilfen und Dashboard-Prefilter
- `admin.php` zentraler Admin-Controller
- `include/nc_connector.inc.php` WebDAV-Verbindungsmodell
- `include/nc_connector_wizard.inc.php` Verbindungsassistent
- `include/nc_connector_wizard_webdav_flow.inc.php` WebDAV-Wizardablauf
- `include/nc_connector_delete_safe.inc.php` Löschen einschließlich WebDAV-Piwigo-Inhalten
- `include/nc_productive_ws.inc.php` direkter Piwigo-Core-Dateisync für Piwigo 16.4.0
- `include/nc_orphan_ws.inc.php` Orphan-Synchronisierung der konkreten WebDAV-Site
- `include/webdav_materialize_runtime.inc.php` WebDAV-Quellauflösung und On-Demand-Materialisierung einschließlich `fileid` und Originalmaßen
- `include/webdav_image_runtime.inc.php` vorhandene WebDAV-Bildzuordnung/Originalauslieferung
- `webdav-derivative.php` On-Demand-Gate, Nextcloud-Preview/Original-Fallback, Piwigo-AJAX-Loader-Antwort und Piwigo-Derivaterzeugung
- `webdav-image.php` serverseitige WebDAV-Originalauslieferung
- `runtime/reconcile-webdav.php` WebDAV-Runtime-Reconcile, einschließlich gültigem leerem Root und Runtime-Berechtigungen
- `runtime/repair-webdav-orphans.php` Reparatur vorhandener Orphan-Zustände
- `runtime/cleanup-webdav-piwigo.php` Bereinigung verwaister WebDAV-Piwigo-Sites
- `runtime/sync-webdav.sh` Ablauf einer WebDAV-Verbindung einschließlich Mapping-/Source-Berechtigungen
- `runtime/run-all.sh` gemeinsamer WebDAV-Runner
- `runtime/lib/build_webdav_placeholder_source.py` rekursiver WebDAV-Scan, Bildmetadaten und physische Platzhalterquelle
- `runtime/lib/sync-webdav-metadata.php` Übernahme der Originalabmessungen in Piwigo
- `runtime/lib/shadow_tree.py` atomarer, Piwigo-kompatibler 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 und private Albumzugriffe
- `include/public_selection.inc.php` Fotoauswahl
- `include/batch_titles.inc.php` fortlaufende Titel
- `include/watermark_*.inc.php` Wasserzeichen-Engine
- `tools/` administrative Einzelwerkzeuge
- `template/`, `js/`, `css/` Oberfläche
## Sicherheit
Administrative Aktionen pruefen Piwigo-Berechtigungen und verwenden fuer schreibende Aktionen Piwigos CSRF-Schutz.
Weitere Schutzmechanismen sind funktionsabhaengig, unter anderem:
- verschluesselte Speicherung der Connector-Zugangsdaten mit einem lokalen Connector-Secret
- PostgreSQL-Reader mit minimalen Leserechten fuer lokale Nextcloud-Verbindungen
- explizite Storage-Zuordnungen statt automatischer Freigabe beliebiger Dateipfade
- Verifikation von Datenbank, Views und Mounts vor einer Aktivierung
- Runtime-Test vor der nativen Aktivierung
- Root-only-Hilfsprogramme fuer systemd-, Secret- und State-Aenderungen
- getrennte State-Verzeichnisse pro Connector-Verbindung
- Originalbilder werden vom NC Connector nicht in eine zweite permanente Bibliothek kopiert
- Validierung von Cache- und Dateipfaden
- Filterung ausgewaehlter Bild-IDs gegen die aktuell berechtigte Bildmenge
- Nutzung der von Piwigos Stapelverarbeitung validierten Auswahl fuer die fortlaufende Titelvergabe
- gehashte Passwoerter und gehashte Freigabetokens fuer Albumfreigaben
- nicht erratbare Freigabelinks auf Basis eines lokal erzeugten Secrets
- eigene technische Benutzer mit minimalem Albumzugriff fuer Freigaben
- automatische Bereinigung widerrufener und geloeschter Albumfreigaben
- automatischer Erhalt des eigenen Zugriffs beim Umschalten eines Albums auf privat
- Connector-importierte physische Alben werden standardmaessig privat angelegt
- Beibehaltung bestehender Piwigo- und Plugin-Berechtigungen
- kontrollierte Uploadziele und Uploadgrenzen
- kein Zugriff auf Originalbilder beim Leeren des Bildcaches
- Webmaster-Pruefung, Schreibbarkeitspruefung und kontrolliertes temporaeres Arbeitsverzeichnis bei Selbstupdates
## Styling und Anpassung
Bratonien Tools soll Funktion und Gestaltung voneinander trennen. Plugin-eigene Styles dienen daher nur der technischen Darstellung und Positionierung.
Farben, Schatten, Hover-Effekte und individuelles Branding sollten ueber das aktive Piwigo-Theme oder Custom CSS umgesetzt werden.
## Entwicklungsstand
Das Plugin befindet sich weiterhin in aktiver Entwicklung. Mit Version **0.9.3.16** ist der lokale NC-Connector fuer den aktuellen Bratonien-Einsatz End-to-End funktionsfaehig: Ordner- und Einzeldateifreigaben werden erkannt, der Shadow Tree wird automatisch gepflegt, Piwigo wird synchronisiert, Einzeldateien werden als Orphans verwaltet und der regelmaessige Lauf erfolgt ueber den gemeinsamen systemd-Timer.
Als naechster groesserer Connector-Ausbauschritt bleibt der Remote-Nextcloud-Adapter offen.
- administrative Schreibaktionen verwenden Piwigos CSRF-Schutz;
- Connector-Zugangsdaten werden verschlüsselt gespeichert;
- Nextcloud-Zugangsdaten werden verbindungseigen gespeichert und nur serverseitig verwendet;
- Wizard-Geheimnisse werden nicht im Browser-Web-Storage persistiert;
- produktive Piwigo-API ist versionsgebunden;
- Originalbilder werden vom Connector nicht gelöscht;
- WebDAV-Originalbilder werden nur bei Bedarf temporär lokal materialisiert;
- kleine Derivate können stattdessen eine temporäre authentifizierte Nextcloud-Preview verwenden;
- temporäre Preview-/Originalquellen werden nach der Piwigo-Derivaterzeugung wieder entfernt;
- Update-Pakete werden an Commit und Hash gebunden.

View File

@@ -15,6 +15,32 @@ $errors = array();
$self_update_override = null;
$nc_piwigo_api_test = null;
// Post/Redirect/Get: never leave a mutating Bratonien Tools action as the
// browser's current request. Otherwise a normal reload can submit the same
// action again (for example an update, delete or create action).
if ($_SERVER['REQUEST_METHOD'] !== 'POST' && !empty($_SESSION['bratonien_tools_flash']) && is_array($_SESSION['bratonien_tools_flash']))
{
$flash = $_SESSION['bratonien_tools_flash'];
unset($_SESSION['bratonien_tools_flash']);
if (!empty($flash['messages']) && is_array($flash['messages']))
{
$messages = array_values($flash['messages']);
}
if (!empty($flash['errors']) && is_array($flash['errors']))
{
$errors = array_values($flash['errors']);
}
if (!empty($flash['self_update']) && is_array($flash['self_update']))
{
$self_update_override = $flash['self_update'];
}
if (!empty($flash['nc_piwigo_api_test']) && is_array($flash['nc_piwigo_api_test']))
{
$nc_piwigo_api_test = $flash['nc_piwigo_api_test'];
}
}
if (
$_SERVER['REQUEST_METHOD'] === 'POST'
&& empty($_POST)
@@ -59,6 +85,20 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['bratonien_tool']))
$errors[] = $e->getMessage();
}
}
$_SESSION['bratonien_tools_flash'] = array(
'messages' => $messages,
'errors' => $errors,
'self_update' => $self_update_override,
'nc_piwigo_api_test' => $nc_piwigo_api_test,
);
$redirect_url = get_root_url().'admin.php?page=plugin-'.BRATONIEN_TOOLS_ID;
if (!headers_sent())
{
header('Location: '.$redirect_url, true, 303);
exit;
}
}
$watermark = bratonien_tools_get_watermark_data();
@@ -70,6 +110,47 @@ $engine = bratonien_tools_get_watermark_engine_config();
$cache_workers = bratonien_tools_get_cache_worker_settings();
$public_selection = bratonien_tools_get_public_selection_settings();
$public_selection_groups = bratonien_tools_get_piwigo_groups();
$customer_qr = bratonien_tools_customer_qr_admin_data();
$customer_qr['friendship_codes'] = bratonien_tools_friendship_code_admin_data();
$qr_present = array();
foreach ($customer_qr['uploads'] as $qr_upload)
{
$qr_year = (int)$qr_upload['year'];
$qr_number = (int)$qr_upload['number'];
if ($qr_year < 1 || $qr_number < 1)
{
continue;
}
if (!isset($qr_present[$qr_year]))
{
$qr_present[$qr_year] = array();
}
$qr_present[$qr_year][$qr_number] = $qr_upload;
}
$qr_batch_base = get_absolute_root_url(true).'plugins/'.BRATONIEN_TOOLS_ID.'/customer-qr-admin-batch.php';
$customer_qr['batch_download_available'] = class_exists('ZipArchive');
$customer_qr['batch_download_url'] = $qr_batch_base;
foreach ($customer_qr['years'] as &$qr_year)
{
$year = (int)$qr_year['year'];
$capacity = (int)$qr_year['capacity'];
$qr_year['batch_download_url'] = $qr_batch_base.'?year='.$year;
$qr_year['slots'] = array();
for ($number = 1; $number <= $capacity; $number++)
{
$present = isset($qr_present[$year][$number]);
$qr_year['slots'][] = array(
'number' => $number,
'present' => $present,
'preview_url' => $present ? (string)$qr_present[$year][$number]['preview_url'] : '',
);
}
}
unset($qr_year);
$assets = bratonien_tools_get_assets();
$asset_environment = bratonien_tools_get_asset_environment();
$album_shares = bratonien_tools_get_album_shares();
@@ -78,18 +159,15 @@ $nc_connector = bratonien_tools_nc_connector_status();
foreach ($nc_connector['connections'] as &$nc_connection)
{
$nc_connection['last_sync'] = bratonien_tools_nc_connector_connection_last_status($nc_connection);
$nc_connection['display_name'] = $nc_connection['name'];
if (!empty($nc_connection['fallback_stored']))
{
$nc_connection['name'] .= ' · Fallback gespeichert';
$nc_connection['verification_checks'][] = array(
'name' => 'Piwigo-Fallback',
'ok' => true,
'detail' => 'Benutzername/Passwort verschluesselt gespeichert',
);
$nc_connection['display_name'] .= ' · Fallback gespeichert';
}
}
unset($nc_connection);
$nc_connector['piwigo_api_test'] = $nc_piwigo_api_test;
$nc_connector['wizard'] = bratonien_tools_nc_wizard_state();
$nc_system_defaults = array(
'timer_name' => 'bratonien-nc-connector.timer',
'timer_active' => false,
@@ -106,10 +184,6 @@ $nc_system_defaults = array(
'last_run_error_detail' => '',
'next_run_timestamp' => 0,
'next_run_label' => 'Nicht verfügbar',
'legacy_runtime_exists' => false,
'legacy_config_exists' => false,
'legacy_service_exists' => false,
'legacy_timer_exists' => false,
);
$nc_connector['system'] = array_merge(
$nc_system_defaults,
@@ -211,6 +285,7 @@ $template->assign(array(
'CACHE_WORKERS' => $cache_workers,
'PUBLIC_SELECTION' => $public_selection,
'PUBLIC_SELECTION_GROUPS' => $public_selection_groups,
'CUSTOMER_QR' => $customer_qr,
'BRATONIEN_ASSETS' => $assets,
'ASSET_ENV' => $asset_environment,
'BRATONIEN_ALBUM_SHARES' => $album_shares,
@@ -226,7 +301,9 @@ $template->assign(array(
$template->set_filename('admin_tabs_content', BRATONIEN_TOOLS_PATH . 'template/admin_tabs.tpl');
$template->set_filename('plugin_admin_content', BRATONIEN_TOOLS_PATH . 'template/admin.tpl');
$template->set_filename('webdav_warmup_admin_content', BRATONIEN_TOOLS_PATH . 'template/webdav_warmup_admin.tpl');
$template->set_filename('public_selection_admin_content', BRATONIEN_TOOLS_PATH . 'template/public_selection_admin.tpl');
$template->set_filename('customer_qr_admin_content', BRATONIEN_TOOLS_PATH . 'template/customer_qr_admin.tpl');
$template->set_filename('asset_manager_admin_content', BRATONIEN_TOOLS_PATH . 'template/asset_manager_admin.tpl');
$template->set_filename('album_shares_admin_content', BRATONIEN_TOOLS_PATH . 'template/album_shares_admin.tpl');
$template->set_filename('nc_connector_admin_content', BRATONIEN_TOOLS_PATH . 'template/nc_connector_admin.tpl');
@@ -234,7 +311,9 @@ $template->set_filename('system_admin_content', BRATONIEN_TOOLS_PATH . 'template
$admin_content = $template->parse('admin_tabs_content', true);
$admin_content .= $template->parse('plugin_admin_content', true);
$admin_content .= $template->parse('webdav_warmup_admin_content', true);
$admin_content .= $template->parse('public_selection_admin_content', true);
$admin_content .= $template->parse('customer_qr_admin_content', true);
$admin_content .= $template->parse('asset_manager_admin_content', true);
$admin_content .= $template->parse('album_shares_admin_content', true);
$admin_content .= $template->parse('nc_connector_admin_content', true);

View File

@@ -17,3 +17,12 @@
.bratonien-picture-zone.is-active {
opacity: 1;
}
#theImageAndInfos img[src*="plugins/bratonien_tools/webdav-derivative.php"]:not(#theMainImage):not(.bratonien-webdav-thumbnail-ready),
#theImageAndInfos img.bratonien-webdav-thumbnail-pending {
visibility: hidden;
}
#theImageAndInfos img.bratonien-webdav-thumbnail-ready {
visibility: visible;
}

122
customer-qr-admin-batch.php Normal file
View File

@@ -0,0 +1,122 @@
<?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');
if (!defined('BRATONIEN_TOOLS_PATH'))
{
http_response_code(404);
exit;
}
check_status(ACCESS_ADMINISTRATOR);
require_once(BRATONIEN_TOOLS_PATH.'include/customer_qr_upload.inc.php');
if (!class_exists('ZipArchive'))
{
http_response_code(500);
header('Content-Type: text/plain; charset=utf-8');
exit('ZIP-Unterstützung ist auf diesem Server nicht verfügbar.');
}
bratonien_tools_customer_qr_ensure_storage();
$limits = bratonien_tools_customer_qr_year_limits();
$table = bratonien_tools_customer_qr_table();
$requested_year = isset($_GET['year']) && $_GET['year'] !== '' ? bratonien_tools_customer_qr_year($_GET['year']) : 0;
$query = 'SELECT upload_year, code_number, stored_name FROM `'.$table.'`';
if ($requested_year > 0)
{
$query .= ' WHERE upload_year='.(int)$requested_year;
}
$query .= ' ORDER BY upload_year ASC, CAST(code_number AS UNSIGNED) ASC, id ASC';
$result = pwg_query($query);
$files = array();
$root = bratonien_tools_customer_qr_storage_root();
while ($row = pwg_db_fetch_assoc($result))
{
$year = (int)$row['upload_year'];
if (!isset($limits[$year]))
{
continue;
}
$number = bratonien_tools_customer_qr_number_for_year($year, $row['code_number']);
$stored_name = (string)$row['stored_name'];
if ($stored_name === '' || basename($stored_name) !== $stored_name)
{
continue;
}
$path = $root.DIRECTORY_SEPARATOR.$year.DIRECTORY_SEPARATOR.$stored_name;
if (!is_file($path) || !is_readable($path))
{
continue;
}
$extension = strtolower((string)pathinfo($stored_name, PATHINFO_EXTENSION));
if (!in_array($extension, array('png', 'jpg', 'jpeg', 'webp', 'gif'), true))
{
continue;
}
$width = max(2, strlen((string)$limits[$year]));
$archive_name = 'qr-'.str_pad($number, $width, '0', STR_PAD_LEFT).'.'.$extension;
if ($requested_year === 0)
{
$archive_name = $year.'/'.$archive_name;
}
$files[] = array(
'path' => $path,
'archive_name' => $archive_name,
);
}
if (empty($files))
{
http_response_code(404);
header('Content-Type: text/plain; charset=utf-8');
exit('Keine QR-Codes für den Batch-Download vorhanden.');
}
$temp = tempnam(sys_get_temp_dir(), 'bratonien-qr-');
if ($temp === false)
{
http_response_code(500);
exit;
}
$zip = new ZipArchive();
if ($zip->open($temp, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true)
{
@unlink($temp);
http_response_code(500);
exit;
}
foreach ($files as $file)
{
$zip->addFile($file['path'], $file['archive_name']);
}
$zip->close();
$download_name = $requested_year > 0
? 'qr-codes-'.$requested_year.'.zip'
: 'qr-codes-alle-jahre.zip';
header('Content-Type: application/zip');
header('Content-Length: '.filesize($temp));
header('Content-Disposition: attachment; filename="'.$download_name.'"');
header('Cache-Control: private, no-store, max-age=0');
header('X-Content-Type-Options: nosniff');
readfile($temp);
@unlink($temp);
exit;

View File

@@ -0,0 +1,70 @@
<?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');
if (!defined('BRATONIEN_TOOLS_PATH'))
{
http_response_code(404);
exit;
}
check_status(ACCESS_ADMINISTRATOR);
require_once(BRATONIEN_TOOLS_PATH.'include/customer_qr_upload.inc.php');
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($id < 1)
{
http_response_code(404);
exit;
}
$table = bratonien_tools_customer_qr_table();
$result = pwg_query('SELECT id, upload_year, code_number, stored_name, mime_type FROM `'.$table.'` WHERE id='.$id.' LIMIT 1');
$row = pwg_db_fetch_assoc($result);
if (!$row)
{
http_response_code(404);
exit;
}
$year = (int)$row['upload_year'];
$number = (string)$row['code_number'];
$stored_name = (string)$row['stored_name'];
$mime = strtolower((string)$row['mime_type']);
$allowed_mimes = array('image/png', 'image/jpeg', 'image/webp', 'image/gif');
if (
$stored_name === ''
|| basename($stored_name) !== $stored_name
|| !in_array($mime, $allowed_mimes, true)
)
{
http_response_code(404);
exit;
}
$path = bratonien_tools_customer_qr_storage_root().DIRECTORY_SEPARATOR.$year.DIRECTORY_SEPARATOR.$stored_name;
if (!is_file($path) || !is_readable($path))
{
http_response_code(404);
exit;
}
$extension = strtolower((string)pathinfo($stored_name, PATHINFO_EXTENSION));
$download = isset($_GET['download']) && (string)$_GET['download'] === '1';
$filename = 'qr-'.$year.'-'.$number.'.'.$extension;
header('Content-Type: '.$mime);
header('Content-Length: '.filesize($path));
header('Cache-Control: private, no-store, max-age=0');
header('X-Content-Type-Options: nosniff');
header('Content-Disposition: '.($download ? 'attachment' : 'inline').'; filename="'.$filename.'"');
readfile($path);
exit;

584
customer-qr-upload.php Normal file
View File

@@ -0,0 +1,584 @@
<?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');
if (!defined('BRATONIEN_TOOLS_PATH'))
{
http_response_code(404);
exit('Bratonien Tools ist nicht aktiv.');
}
require_once(BRATONIEN_TOOLS_PATH.'include/customer_qr_upload.inc.php');
require_once(BRATONIEN_TOOLS_PATH.'include/friendship_code_upload.inc.php');
$settings = bratonien_tools_customer_qr_settings();
if (empty($settings['enabled']))
{
http_response_code(404);
header('Content-Type: text/html; charset=utf-8');
echo '<!doctype html><html lang="de"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>QR-Code Upload</title></head><body><main style="max-width:720px;margin:48px auto;padding:24px;font-family:system-ui,sans-serif"><h1>QR-Code Upload</h1><p>Dieses Formular ist derzeit nicht aktiviert.</p></main></body></html>';
exit;
}
bratonien_tools_customer_qr_ensure_storage();
bratonien_tools_friendship_code_ensure_storage();
$year_limits = bratonien_tools_customer_qr_year_limits();
$action = (string)($_GET['action'] ?? '');
function bratonien_tools_customer_qr_public_inventory($year)
{
$year = bratonien_tools_customer_qr_year($year);
$limits = bratonien_tools_customer_qr_year_limits();
$limit = (int)$limits[$year];
$present = array();
$table = bratonien_tools_customer_qr_table();
$result = pwg_query(
'SELECT code_number FROM `'.$table.'` '
.'WHERE upload_year='.(int)$year.' '
.'ORDER BY CAST(code_number AS UNSIGNED) ASC'
);
while ($row = pwg_db_fetch_assoc($result))
{
$number = (int)$row['code_number'];
if ($number >= 1 && $number <= $limit)
{
$present[$number] = true;
}
}
$slots = array();
for ($number = 1; $number <= $limit; $number++)
{
$slots[] = array(
'number' => $number,
'present' => isset($present[$number]),
);
}
$present_count = count($present);
return array(
'year' => $year,
'limit' => $limit,
'present_count' => $present_count,
'missing_count' => max(0, $limit - $present_count),
'slots' => $slots,
);
}
if ($action === 'inventory')
{
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, max-age=0');
try
{
$inventory = bratonien_tools_customer_qr_public_inventory($_GET['year'] ?? '');
echo json_encode(array(
'ok' => true,
'inventory' => $inventory,
), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
catch (Throwable $e)
{
http_response_code(400);
echo json_encode(array('ok' => false, 'message' => $e->getMessage()), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
exit;
}
if ($action === 'check')
{
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, max-age=0');
try
{
$year = bratonien_tools_customer_qr_year($_GET['year'] ?? '');
$number = bratonien_tools_customer_qr_number_for_year($year, $_GET['number'] ?? '');
$exists = bratonien_tools_customer_qr_exists($year, $number);
echo json_encode(array(
'ok' => true,
'available' => !$exists,
'year' => $year,
'number' => $number,
'limit' => (int)$year_limits[$year],
'message' => $exists
? 'Diese QR-Code-Nummer ist für '.$year.' bereits vorhanden.'
: 'Nummer ist für '.$year.' frei.',
), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
catch (Throwable $e)
{
http_response_code(400);
echo json_encode(array('ok' => false, 'message' => $e->getMessage()), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
exit;
}
if ($action === 'check_friendship')
{
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, max-age=0');
try
{
$name = bratonien_tools_friendship_code_name($_GET['name'] ?? '');
$exists = bratonien_tools_friendship_code_exists_for_name($name);
echo json_encode(array(
'ok' => true,
'available' => !$exists,
'name' => $name,
'message' => $exists
? 'Für diesen Namen ist bereits ein Freundschaftscode hinterlegt.'
: 'Für diesen Namen kann ein Freundschaftscode hinterlegt werden.',
), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
catch (Throwable $e)
{
http_response_code(400);
echo json_encode(array('ok' => false, 'message' => $e->getMessage()), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
exit;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
$results = array();
$year = bratonien_tools_customer_qr_default_year();
$upload_type = (string)($_POST['upload_type'] ?? 'qr');
try
{
if (
empty($_POST)
&& empty($_FILES)
&& !empty($_SERVER['CONTENT_LENGTH'])
)
{
throw new RuntimeException('Der Upload überschreitet das PHP-Limit post_max_size ('.ini_get('post_max_size').').');
}
if (function_exists('check_pwg_token'))
{
check_pwg_token();
}
if ($upload_type === 'friendship')
{
$name = bratonien_tools_friendship_code_name($_POST['friend_name'] ?? '');
if (empty($_FILES['friend_file']))
{
throw new RuntimeException('Es wurde keine Freundschaftscode-Datei ausgewählt.');
}
$results[] = bratonien_tools_friendship_code_process_upload($name, $_FILES['friend_file']);
}
else
{
$upload_type = 'qr';
$year = bratonien_tools_customer_qr_year($_POST['upload_year'] ?? '');
if (empty($_FILES['qr_files']))
{
throw new RuntimeException('Es wurden keine QR-Code-Dateien ausgewählt.');
}
$numbers = isset($_POST['qr_numbers']) && is_array($_POST['qr_numbers'])
? array_values($_POST['qr_numbers'])
: array();
$results = bratonien_tools_customer_qr_process_uploads($year, $_FILES['qr_files'], $numbers);
}
}
catch (Throwable $e)
{
$results[] = array(
'status' => 'error',
'kind' => $upload_type === 'friendship' ? 'friendship' : 'qr',
'file' => '',
'name' => $upload_type === 'friendship' ? trim((string)($_POST['friend_name'] ?? '')) : '',
'year' => $year,
'number' => '',
'message' => $e->getMessage(),
);
}
$_SESSION['bratonien_customer_qr_flash'] = array(
'type' => $upload_type,
'year' => $year,
'results' => $results,
);
$target = strtok($_SERVER['REQUEST_URI'], '?');
header('Location: '.$target, true, 303);
exit;
}
$flash = array();
if (!empty($_SESSION['bratonien_customer_qr_flash']) && is_array($_SESSION['bratonien_customer_qr_flash']))
{
$flash = $_SESSION['bratonien_customer_qr_flash'];
unset($_SESSION['bratonien_customer_qr_flash']);
}
$selected_year = isset($flash['year']) ? (int)$flash['year'] : bratonien_tools_customer_qr_default_year();
if (!isset($year_limits[$selected_year]))
{
$selected_year = bratonien_tools_customer_qr_default_year();
}
$selected_limit = (int)$year_limits[$selected_year];
$inventory = bratonien_tools_customer_qr_public_inventory($selected_year);
$results = isset($flash['results']) && is_array($flash['results']) ? $flash['results'] : array();
$token = function_exists('get_pwg_token') ? get_pwg_token() : '';
$max_files = max(1, (int)ini_get('max_file_uploads'));
$endpoint = strtok($_SERVER['REQUEST_URI'], '?');
header('Content-Type: text/html; charset=utf-8');
header('Cache-Control: no-store, max-age=0');
?>
<!doctype html>
<html lang="de">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>QR-Code Upload</title>
<style>
:root{color-scheme:light dark;--bg:#111214;--card:#1a1c20;--text:#f2f2f2;--muted:#a9adb5;--border:#383c44;--accent:#d99a43;--ok:#67b779;--bad:#d46b6b;--wait:#c7a65a}
*{box-sizing:border-box}
body{margin:0;background:var(--bg);color:var(--text);font:16px/1.5 system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}
main{max-width:860px;margin:0 auto;padding:34px 18px 60px}
h1{font-size:clamp(1.8rem,5vw,2.6rem);margin:0 0 8px}
h2{font-size:1.12rem;margin:0 0 12px}
p{margin:0 0 16px}.muted{color:var(--muted)}
.card{background:var(--card);border:1px solid var(--border);border-radius:14px;padding:20px;margin-top:18px}
.grid{display:grid;grid-template-columns:minmax(0,180px) minmax(0,1fr);gap:14px 18px;align-items:center}
label{font-weight:650}.control{min-width:0}
select,input[type="text"],input[type="file"]{width:100%;font:inherit;color:inherit;background:#121418;border:1px solid var(--border);border-radius:9px;padding:11px 12px}
input[type="file"]{padding:9px}
input:focus,select:focus,button:focus{outline:2px solid var(--accent);outline-offset:2px}
.file-list{display:grid;gap:10px;margin-top:16px}
.file-row{display:grid;grid-template-columns:minmax(0,1fr) minmax(120px,180px) minmax(170px,220px);gap:10px;align-items:center;padding:12px;border:1px solid var(--border);border-radius:10px;background:#15171b}
.file-name{overflow-wrap:anywhere}.status{font-size:.92rem;color:var(--muted)}.status.ok{color:var(--ok)}.status.bad{color:var(--bad)}.status.wait{color:var(--wait)}
.actions{display:flex;gap:12px;align-items:center;flex-wrap:wrap;margin-top:18px}
button{border:0;border-radius:9px;padding:12px 18px;background:var(--accent);color:#1a140d;font:inherit;font-weight:750;cursor:pointer}
button:disabled{opacity:.45;cursor:not-allowed}
.result{padding:12px 14px;border-radius:9px;margin-top:8px;border:1px solid var(--border)}
.result.ok{border-color:color-mix(in srgb,var(--ok),transparent 45%)}.result.duplicate,.result.error{border-color:color-mix(in srgb,var(--bad),transparent 45%)}
.result strong{display:block}.meta{color:var(--muted);font-size:.92rem}
.inventory{margin-top:20px;padding-top:18px;border-top:1px solid var(--border)}
.inventory-head{display:flex;align-items:baseline;justify-content:space-between;gap:12px;flex-wrap:wrap;margin-bottom:10px}
.inventory-head h2{margin:0}
.inventory-legend{display:flex;gap:14px;align-items:center;flex-wrap:wrap;margin-bottom:12px;font-size:.92rem;color:var(--muted)}
.inventory-legend span{display:inline-flex;align-items:center;gap:6px}
.inventory-dot{width:14px;height:14px;border-radius:3px;border:1px solid}
.inventory-dot.present{background:rgba(62,170,94,.30);border-color:#58c878}
.inventory-dot.missing{background:rgba(205,72,72,.28);border-color:#db6d6d}
.inventory-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(42px,1fr));gap:6px}
.inventory-slot{min-height:38px;display:flex;align-items:center;justify-content:center;border:1px solid;border-radius:6px;font-weight:750}
.inventory-slot.present{background:rgba(62,170,94,.30);border-color:#58c878;color:#dff7e6}
.inventory-slot.missing{background:rgba(205,72,72,.28);border-color:#db6d6d;color:#ffdede}
@media(max-width:680px){.grid{grid-template-columns:1fr}.file-row{grid-template-columns:1fr}.card{padding:16px}.inventory-grid{grid-template-columns:repeat(auto-fill,minmax(38px,1fr))}}
</style>
</head>
<body>
<main>
<header>
<h1>QR-Code Upload</h1>
<p class="muted">QR-Codes und persönliche Freundschaftscodes hochladen.</p>
</header>
<?php if (!empty($results)): ?>
<section class="card" aria-labelledby="upload-result-title">
<h2 id="upload-result-title">Ergebnis</h2>
<?php foreach ($results as $result): ?>
<?php
$status = in_array(($result['status'] ?? ''), array('ok','duplicate','error'), true) ? $result['status'] : 'error';
$kind = (string)($result['kind'] ?? 'qr');
if ($status === 'ok') $headline = 'Gespeichert';
elseif ($status === 'duplicate') $headline = $kind === 'friendship' ? 'Nicht gespeichert: bereits vorhanden' : 'Nicht gespeichert: Nummer bereits vergeben';
else $headline = 'Nicht gespeichert';
?>
<div class="result <?php echo htmlspecialchars($status, ENT_QUOTES, 'UTF-8'); ?>">
<strong><?php echo htmlspecialchars($headline, ENT_QUOTES, 'UTF-8'); ?></strong>
<?php if (!empty($result['file'])): ?><div><?php echo htmlspecialchars($result['file'], ENT_QUOTES, 'UTF-8'); ?></div><?php endif; ?>
<?php if ($kind === 'friendship' && !empty($result['name'])): ?><div class="meta">Name: <?php echo htmlspecialchars($result['name'], ENT_QUOTES, 'UTF-8'); ?></div><?php endif; ?>
<?php if ($kind !== 'friendship' && !empty($result['number'])): ?><div class="meta">Jahr <?php echo (int)$result['year']; ?> · QR-Code #<?php echo htmlspecialchars($result['number'], ENT_QUOTES, 'UTF-8'); ?></div><?php endif; ?>
<div class="meta"><?php echo htmlspecialchars((string)($result['message'] ?? ''), ENT_QUOTES, 'UTF-8'); ?></div>
</div>
<?php endforeach; ?>
</section>
<?php endif; ?>
<form class="card" method="post" enctype="multipart/form-data" id="qr-upload-form" novalidate>
<input type="hidden" name="pwg_token" value="<?php echo htmlspecialchars($token, ENT_QUOTES, 'UTF-8'); ?>">
<input type="hidden" name="upload_type" value="qr">
<h2>QR-Code</h2>
<div class="grid">
<label for="upload-year">Jahr</label>
<div class="control">
<select id="upload-year" name="upload_year" required>
<?php foreach ($year_limits as $year => $limit): ?>
<option value="<?php echo (int)$year; ?>"<?php echo (int)$year === $selected_year ? ' selected' : ''; ?>><?php echo (int)$year; ?></option>
<?php endforeach; ?>
</select>
<div id="year-limit-note" class="muted" style="margin-top:6px">Für <?php echo $selected_year; ?> sind QR-Code-Nummern 1 bis <?php echo $selected_limit; ?> vorgesehen.</div>
</div>
<label for="qr-files">QR-Code-Datei(en)</label>
<div class="control">
<input id="qr-files" name="qr_files[]" type="file" accept="image/png,image/jpeg,image/webp,image/gif" multiple required>
<div class="muted" style="margin-top:6px">PNG, JPG, WEBP oder GIF. Batch-Upload bis zum Serverlimit von <?php echo $max_files; ?> Dateien pro Anfrage.</div>
</div>
</div>
<section class="inventory" aria-labelledby="inventory-title">
<div class="inventory-head">
<h2 id="inventory-title">QR-Code-Bestand <span id="inventory-year"><?php echo (int)$inventory['year']; ?></span></h2>
<span id="inventory-count" class="muted"><?php echo (int)$inventory['present_count']; ?> vorhanden · <?php echo (int)$inventory['missing_count']; ?> fehlen</span>
</div>
<div class="inventory-legend" aria-hidden="true">
<span><i class="inventory-dot present"></i>Vorhanden</span>
<span><i class="inventory-dot missing"></i>Fehlt</span>
</div>
<div id="inventory-grid" class="inventory-grid" aria-live="polite">
<?php foreach ($inventory['slots'] as $slot): ?>
<span class="inventory-slot <?php echo !empty($slot['present']) ? 'present' : 'missing'; ?>" title="QR-Code #<?php echo (int)$slot['number']; ?> <?php echo !empty($slot['present']) ? 'vorhanden' : 'fehlt'; ?>"><?php echo (int)$slot['number']; ?></span>
<?php endforeach; ?>
</div>
</section>
<div id="file-list" class="file-list" aria-live="polite"></div>
<div class="actions">
<button id="submit-button" type="submit" disabled>QR-Code(s) hochladen</button>
<span class="muted">Eine Nummer kann innerhalb eines Jahres nur einmal verwendet werden.</span>
</div>
</form>
<form class="card" method="post" enctype="multipart/form-data" id="friendship-upload-form" novalidate>
<input type="hidden" name="pwg_token" value="<?php echo htmlspecialchars($token, ENT_QUOTES, 'UTF-8'); ?>">
<input type="hidden" name="upload_type" value="friendship">
<h2>Persönlicher Freundschaftscode</h2>
<div class="grid">
<label for="friend-name">Name</label>
<div class="control">
<input id="friend-name" name="friend_name" type="text" maxlength="120" autocomplete="name" required>
<div id="friend-name-status" class="status" style="margin-top:6px">Bitte Namen eingeben.</div>
</div>
<label for="friend-file">Freundschaftscode</label>
<div class="control">
<input id="friend-file" name="friend_file" type="file" accept="image/png,image/jpeg,image/webp,image/gif" required>
<div class="muted" style="margin-top:6px">Ein Bild pro Person. PNG, JPG, WEBP oder GIF.</div>
</div>
</div>
<div class="actions">
<button id="friend-submit-button" type="submit" disabled>Freundschaftscode hochladen</button>
<span class="muted">Pro Name wird genau ein persönlicher Freundschaftscode gespeichert.</span>
</div>
</form>
</main>
<script>
(function(){
'use strict';
var form=document.getElementById('qr-upload-form');
var fileInput=document.getElementById('qr-files');
var yearInput=document.getElementById('upload-year');
var yearNote=document.getElementById('year-limit-note');
var list=document.getElementById('file-list');
var submit=document.getElementById('submit-button');
var inventoryYear=document.getElementById('inventory-year');
var inventoryCount=document.getElementById('inventory-count');
var inventoryGrid=document.getElementById('inventory-grid');
var endpoint=<?php echo json_encode($endpoint, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); ?>;
var limits=<?php echo json_encode($year_limits, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); ?>;
var timers=new WeakMap();
function yearLimit(){return Number(limits[String(yearInput.value)]||limits[yearInput.value]||0);}
function canonical(value){
value=String(value||'').trim();
if(!/^\d+$/.test(value))return '';
value=value.replace(/^0+(?=\d)/,'');
if(value==='0')return '';
return value;
}
function rows(){return Array.prototype.slice.call(list.querySelectorAll('.file-row'));}
function setStatus(row,text,kind){
var node=row.querySelector('.status');
node.textContent=text;
node.className='status'+(kind?' '+kind:'');
row.dataset.valid=kind==='ok'?'1':'0';
updateSubmit();
}
function updateSubmit(){
var all=rows();
submit.disabled=!all.length||all.some(function(row){return row.dataset.valid!=='1';});
}
function renderInventory(inventory){
inventoryYear.textContent=String(inventory.year);
inventoryCount.textContent=String(inventory.present_count)+' vorhanden · '+String(inventory.missing_count)+' fehlen';
inventoryGrid.textContent='';
(inventory.slots||[]).forEach(function(slot){
var node=document.createElement('span');
node.className='inventory-slot '+(slot.present?'present':'missing');
node.textContent=String(slot.number);
node.title='QR-Code #'+slot.number+' '+(slot.present?'vorhanden':'fehlt');
inventoryGrid.appendChild(node);
});
}
function loadInventory(){
inventoryCount.textContent='Bestand wird geladen …';
var requestedYear=yearInput.value;
var url=endpoint+'?action=inventory&year='+encodeURIComponent(requestedYear)+'&_='+Date.now();
fetch(url,{credentials:'same-origin',cache:'no-store',headers:{'Accept':'application/json'}})
.then(function(response){return response.json().then(function(data){return {response:response,data:data};});})
.then(function(result){
if(!result.response.ok||!result.data.ok||!result.data.inventory)throw new Error(result.data.message||'Bestand konnte nicht geladen werden.');
if(String(yearInput.value)!==String(requestedYear))return;
renderInventory(result.data.inventory);
})
.catch(function(error){inventoryCount.textContent=error.message||'Bestand konnte nicht geladen werden.';});
}
function markBatchDuplicates(){
var grouped={};
rows().forEach(function(row){
var input=row.querySelector('input[name="qr_numbers[]"]');
var value=canonical(input.value);
if(!value)return;
if(!grouped[value])grouped[value]=[];
grouped[value].push(row);
});
Object.keys(grouped).forEach(function(key){
if(grouped[key].length>1){
grouped[key].forEach(function(row){setStatus(row,'Nummer ist in diesem Batch doppelt.','bad');});
}
});
return grouped;
}
function checkRow(row){
var input=row.querySelector('input[name="qr_numbers[]"]');
var value=canonical(input.value);
var limit=yearLimit();
if(!value){setStatus(row,'Bitte eine QR-Code-Nummer ab 1 eingeben.','bad');return;}
if(!limit||Number(value)>limit){setStatus(row,'Für '+yearInput.value+' sind nur die Nummern 1 bis '+limit+' vorgesehen.','bad');return;}
var grouped=markBatchDuplicates();
if(grouped[value]&&grouped[value].length>1)return;
setStatus(row,'Nummer wird geprüft …','wait');
var url=endpoint+'?action=check&year='+encodeURIComponent(yearInput.value)+'&number='+encodeURIComponent(value)+'&_='+Date.now();
fetch(url,{credentials:'same-origin',cache:'no-store',headers:{'Accept':'application/json'}})
.then(function(response){return response.json().then(function(data){return {response:response,data:data};});})
.then(function(result){
if(!result.response.ok||!result.data.ok)throw new Error(result.data.message||'Prüfung fehlgeschlagen.');
if(result.data.available)setStatus(row,result.data.message,'ok');
else setStatus(row,result.data.message,'bad');
})
.catch(function(error){setStatus(row,error.message||'Prüfung fehlgeschlagen.','bad');});
}
function scheduleCheck(row){
var old=timers.get(row);if(old)window.clearTimeout(old);
timers.set(row,window.setTimeout(function(){checkRow(row);},250));
}
function scheduleAll(){rows().forEach(function(row){scheduleCheck(row);});}
function updateYearNote(){
yearNote.textContent='Für '+yearInput.value+' sind QR-Code-Nummern 1 bis '+yearLimit()+' vorgesehen.';
}
function rebuild(){
list.textContent='';
Array.prototype.slice.call(fileInput.files||[]).forEach(function(file,index){
var row=document.createElement('div');row.className='file-row';row.dataset.valid='0';
var name=document.createElement('div');name.className='file-name';name.textContent=file.name;
var input=document.createElement('input');input.type='text';input.name='qr_numbers[]';input.inputMode='numeric';input.autocomplete='off';input.placeholder='QR-Nummer';input.setAttribute('aria-label','QR-Code-Nummer für '+file.name);input.maxLength=3;input.required=true;
var status=document.createElement('div');status.className='status';status.textContent='Nummer fehlt.';
row.appendChild(name);row.appendChild(input);row.appendChild(status);list.appendChild(row);
input.addEventListener('input',scheduleAll);
if(index===0)window.setTimeout(function(){input.focus();},0);
});
updateSubmit();
}
fileInput.addEventListener('change',rebuild);
yearInput.addEventListener('change',function(){updateYearNote();scheduleAll();loadInventory();});
form.addEventListener('submit',function(event){
var invalid=rows().some(function(row){return row.dataset.valid!=='1';});
if(invalid){event.preventDefault();scheduleAll();}
else{submit.disabled=true;submit.textContent='Upload läuft …';}
});
})();
(function(){
'use strict';
var form=document.getElementById('friendship-upload-form');
var nameInput=document.getElementById('friend-name');
var fileInput=document.getElementById('friend-file');
var status=document.getElementById('friend-name-status');
var submit=document.getElementById('friend-submit-button');
var endpoint=<?php echo json_encode($endpoint, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); ?>;
var timer=null;
var nameValid=false;
function updateSubmit(){
submit.disabled=!nameValid||!fileInput.files||fileInput.files.length!==1;
}
function setStatus(text,kind){
status.textContent=text;
status.className='status'+(kind?' '+kind:'');
nameValid=kind==='ok';
updateSubmit();
}
function checkName(){
var name=String(nameInput.value||'').trim().replace(/\s+/g,' ');
if(!name){setStatus('Bitte Namen eingeben.','bad');return;}
setStatus('Name wird geprüft …','wait');
var url=endpoint+'?action=check_friendship&name='+encodeURIComponent(name)+'&_='+Date.now();
fetch(url,{credentials:'same-origin',cache:'no-store',headers:{'Accept':'application/json'}})
.then(function(response){return response.json().then(function(data){return {response:response,data:data};});})
.then(function(result){
if(!result.response.ok||!result.data.ok)throw new Error(result.data.message||'Prüfung fehlgeschlagen.');
if(result.data.available)setStatus(result.data.message,'ok');
else setStatus(result.data.message,'bad');
})
.catch(function(error){setStatus(error.message||'Prüfung fehlgeschlagen.','bad');});
}
nameInput.addEventListener('input',function(){
nameValid=false;updateSubmit();
if(timer)window.clearTimeout(timer);
timer=window.setTimeout(checkName,250);
});
fileInput.addEventListener('change',updateSubmit);
form.addEventListener('submit',function(event){
if(!nameValid||!fileInput.files||fileInput.files.length!==1){event.preventDefault();checkName();return;}
submit.disabled=true;submit.textContent='Upload läuft …';
});
})();
</script>
</body>
</html>

View File

@@ -0,0 +1,111 @@
# HANDOFF Piwigo / WebDAV Cache-Worker 2026-09-03
## Warum hier gestoppt wurde
Die aktuelle Cache-Worker-Entwicklung ist in einen Architektur-/Debugging-Kreis geraten. Der beobachtete produktive Zustand ist eindeutig falsch: Nach dem Leeren des Bildcaches meldet der manuelle Cache-Aufbau praktisch sofort "fertig", obwohl der eigentliche Piwigo-Bildcache nicht aufgebaut wurde. Weitere Patchversuche an Anzeige, Statusaggregation oder Legacy-Worker-Zählung würden den Fehler nur weiter überdecken.
Ab hier **nicht weiterpatchen**, bevor der reale Ausführungspfad von Button bis Piwigo-Derivaterzeugung vollständig nachvollzogen ist.
## Gesicherte Architekturvorgaben
- Nextcloud ist die autoritative Quelle der Originalbilder.
- Piwigo arbeitet produktiv mit einem Shadow-Tree und 1x1-Placeholdern.
- Der Worker darf Piwigo nicht nachbauen und selbst keine Derivate rendern.
- Richtiger Ablauf: Worker erkennt Arbeit -> Original temporär materialisieren -> Piwigo nativen Derivatpfad aufrufen -> Ergebnis prüfen -> Original wieder entfernen / Placeholder restaurieren.
- Piwigo allein bestimmt Dimensionen, Crop, Sharpening, Wasserzeichen, Qualität, Format und Cachepfad.
- On-Demand bleibt Fallback.
- Materialisierung erfolgt batchweise, Standard 10 Originale pro Batch.
- Stage 1 vor Stage 2; neue Sync-Arbeit darf Stage 2 zwischen Batches priorisieren.
- Connector/Shadow-Tree bleibt Wahrheit darüber, welche Quellen existieren.
## Neuer Quellenindex Konzept weiterhin sinnvoll
Die Trennung des Worker-Entscheidungszustands vom Piwigo-Cache ist weiterhin sinnvoll:
- eigener kleiner Quellenindex je WebDAV-Verbindung
- Identität primär über `fileid`, Fallback Root/Pfad
- Vergleich über `etag`, Dateigröße, MIME/Format, Pfad, Breite/Höhe
- Quelle neu/geändert -> Worker darf Piwigo beauftragen
- Quelle unverändert -> normaler periodischer Lauf tut nichts
- gelöschte Quelle -> beim Abgleich aus Worker-Index entfernen; eigentliche Quellenentfernung bleibt Connector/Shadow-Tree-Aufgabe
- manueller Full-Rebuild darf den Quellenindex bewusst ignorieren und alle aktuellen Quellen erneut an Piwigo reichen
Datei dafür aktuell:
`include/webdav_source_index.inc.php`
## Aktueller problematischer Stand
### Version
Aktuell zuletzt auf `0.9.7.1.16` erhöht.
### Relevante Dateien
- `runtime/lib/webdav-cache-warmup.php`
- `runtime/webdav-warmup-dispatch.php`
- `include/webdav_source_index.inc.php`
- `include/webdav_warmup_settings.inc.php`
- `main-cache-build.php`
- `main-cache-status.php`
- `tools/image_cache.inc.php`
- `template/admin.tpl`
- `include/tool_registry.inc.php`
### Letzte Architekturänderungen
1. Legacy `main-cache-build.php` zählt WebDAV-Bilder nicht mehr als normale lokale Cachearbeit.
2. Eigener WebDAV-Quellenindex wurde eingeführt.
3. Warmup-Auswahl wurde auf diesen Quellenindex umgestellt.
4. Kombinierter Admin-Button startet lokalen Piwigo-Teil plus WebDAV-Rebuild.
5. Statusanzeige wurde zusammengeführt.
6. Bei reiner WebDAV-Installation sollte der lokale Legacy-Worker gar nicht mehr gestartet werden.
Trotzdem beobachtet der Nutzer nach Cache-Leeren weiterhin einen praktisch sofort fertigen Aufbau. Das beweist: **Der tatsächliche WebDAV-Rebuild-Pfad erzeugt die erwarteten Piwigo-Derivate nicht bzw. läuft nicht so, wie die Architektur es annimmt.**
## Wichtige letzte Commits
- `ac6353b050cdf30db79ab20716e66e6a6c841abb` eigener WebDAV-Quellenindex
- `6783974c7dfab9d11a0f1e43419de84e92141fd5` Warmup auf Quellenindex umgestellt
- `9f80c4aa974da01d606292c479487bce13b403fa` Quelle erst nach beiden Stufen vollständig
- `030d0c1be7ef8cafdab3f3d46e01ec90d5fd3bdc` kombinierte Statusanzeige
- `e831301650ee2a80c969e6c9b783d37a3c4f593d` Syntaxkorrektur Status
- `479cdbc4734605db3861908286426c76468d12a3` Quellenindex-Baseline blockiert Aktivierung nicht mehr
- `116b710d5d35311eeae261e5ae3cf405c5f51ce3` Legacy-Worker bei reiner WebDAV-Installation nicht mehr starten
- `81e0a9e185a14c08230b4f8fa0f36809c5b2b9a7` Version 0.9.7.1.16
## NICHT weiter tun
- Keine weiteren UI-/Statuspatches, bevor der echte Workerpfad bewiesen ist.
- Nicht wieder Cache-Dateiexistenz als Quelle für "neu/geändert" verwenden.
- Nicht den Placeholder selbst rendern.
- Nicht den Legacy-Full-Cache-Builder für WebDAV reaktivieren.
- Nicht weiter an Symptomen wie 45-Sekunden-Stall, "übersprungen" oder Prozentanzeige herumoptimieren.
## Nächster Einstieg zwingend
Der nächste Chat/Entwickler soll **zuerst den tatsächlichen Rebuild-Ausführungspfad beweisen**:
1. Admin-Handler `image_cache_build` verfolgen.
2. `bratonien_tools_start_combined_image_cache_build()` verfolgen.
3. Start des `runtime/webdav-warmup-dispatch.php --mode=rebuild` beweisen.
4. Verifizieren, dass Dispatcher die aktive WebDAV-Verbindung findet.
5. Verifizieren, dass `runtime/lib/webdav-cache-warmup.php --mode=rebuild` wirklich gestartet wird.
6. Verifizieren, wie viele Quellen `bratonien_tools_cache_warmup_scan()` tatsächlich liefert.
7. Verifizieren, wie viele Varianten Stage 1 und Stage 2 pro Bild tatsächlich liefern.
8. Erst an **einem einzigen Bild** nachweisen:
- Original wird aus Nextcloud heruntergeladen.
- Placeholder wird korrekt gesichert.
- Original wird am produktiven Quellpfad eingesetzt.
- `piwigo-derivative-call.php` ruft wirklich Piwigos nativen `i.php`-Pfad auf.
- Piwigo erzeugt tatsächlich eine konkrete Datei unter `_data/i`.
- strikter Validator erkennt sie als gültig.
- Placeholder wird exakt restauriert.
9. Erst wenn dieser Ein-Bild-Test nachweislich funktioniert, Batchbetrieb und UI wieder anfassen.
## Entscheidender Verdacht
Der derzeit wichtigste Verdacht ist **nicht mehr die Anzeige**, sondern dass der Rebuild intern sehr früh keine Arbeit findet oder Piwigo über den aufgerufenen `i.php`-Pfad keine Derivate erzeugt, obwohl der Worker dies erwartet. Genau diese Stelle muss mit realem Lauf/Log belegt werden.
## Produktionsvalidierung
Von ChatGPT wurde kein echter Serverlauf durchgeführt. Ohne reale Serverausgaben darf nicht behauptet werden, dass Pfadaudit, Materialisierung, Piwigo-Aufruf oder Cache-Erzeugung funktionieren.

View File

@@ -0,0 +1,68 @@
# WebDAV-Cache-Warmup Patch 0.9.7.1.8
## Ziel
Fehlende Piwigo-Derivate für neue Nextcloud-Inhalte im Hintergrund vorbereiten, ohne einen zweiten dauerhaften Bildbestand anzulegen und ohne Piwigo-Datenbankeinträge, Albumzuordnungen oder Bildpfade durch Bratonien Tools zu verändern.
## Zuständigkeiten
Bratonien Tools übernimmt ausschließlich Orchestrierung:
1. neue Alben bzw. neue/geänderte Bilder erkennen;
2. Originale in konfigurierbaren Batches temporär aus Nextcloud laden;
3. die bereits bestehende Piwigo-Quellzuordnung validieren;
4. die lokale Quelle für genau ein Bild atomar bereitstellen;
5. Piwigos eigenes `i.php` für die gewünschten, von Piwigo definierten Derivate aufrufen;
6. den ursprünglichen Placeholder exakt wiederherstellen und verifizieren;
7. temporäre Batch-Dateien löschen.
Piwigo bleibt allein zuständig für Derivatgrößen, Bildverarbeitung, Qualität, Format und Cache-Dateien.
## Trigger
- Neues Album: unmittelbar nach vollständig erfolgreichem Connector-Sync dieser Verbindung (`sync`-Modus).
- Einzelne neue/geänderte Bilder in bekannten Alben: periodische Eingangsprüfung, Standard 12 Stunden (`periodic`-Modus).
- Administration: `Jetzt auf neue Bilder prüfen` (`manual`-Modus).
- On-Demand bleibt parallel aktiv und wird nicht durch den Warmup ersetzt.
## Batches und Stufen
- Batchgröße ist konfigurierbar, Standard **10 Bilder**.
- Ein Batch wird zuerst vollständig aus Nextcloud geladen.
- Anschließend werden die Bilder einzeln am bereits bestehenden Piwigo-Pfad bereitgestellt und von Piwigo verarbeitet.
- Stufe 1: von Piwigo definierte Standard-/Custom-Derivate bis einschließlich 1920 px längster Kante.
- Erst wenn Stufe 1 abgearbeitet ist, folgt Stufe 2 mit den übrigen von Piwigo definierten Derivaten.
## Schutz produktiver Daten
Der Warmup darf keine Piwigo-Bild-/Albumdatensätze schreiben oder neue Piwigo-Sites/Zuordnungen anlegen.
Vor jedem Lauf wird die bestehende Pfadkette von Piwigo aus validiert:
`Piwigo image.id -> images.path -> realpath() -> nc-webdav-source/connection-ID/root-fileid -> webdav-map.json`
Unsichere oder widersprüchliche Zuordnungen führen zum Abbruch, nicht zu einer Rekonstruktion auf Verdacht.
Zusätzliche Sicherungen:
- vorhandener per-image Lock `upload/bratonien-webdav-materialize/image-ID.lock` wird auch vom Warmup benutzt;
- `webdav-sync.lock` wird für den gesamten Warmup-Lauf geteilt gehalten; der Connector-Sync benötigt denselben Lock exklusiv;
- zwei Piwigo-IDs auf derselben physischen Connector-Quelle führen zum Sicherheitsabbruch;
- Placeholder wird nie in-place überschrieben;
- Swap erfolgt über Dateien im selben Verzeichnis und `rename()`;
- Größe und SHA-1 des Placeholders werden vor dem Swap erfasst;
- nach jedem Restore müssen Größe und SHA-1 exakt dem Ausgangszustand entsprechen;
- Restore-Fehler beendet den Worker sofort als fatal;
- bestehende produktive Daten werden beim ersten Lauf nur als Baseline erfasst und nicht automatisch neu aufgebaut.
## Patchphase
Die automatische Warmup-Funktion ist in 0.9.7.1.8 standardmäßig **deaktiviert**. Vor Aktivierung sind vorgesehen:
1. Plugin aktualisieren;
2. schreibgeschützten `Produktive Pfade prüfen`-Audit ausführen;
3. ersten manuellen Lauf durchführen, der den vorhandenen Bestand nur als Baseline erfasst;
4. gezielten Test mit neuem Testalbum / neuen Bildern;
5. erst nach bestätigtem Restore- und Piwigo-Cache-Verhalten Automatik aktivieren.
Die Entwicklung bleibt bis zum vollständig validierten Endstand in Patch-Versionen. Die geplante Finalversion ist **0.10.1**.

View File

@@ -0,0 +1,74 @@
<?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');
if (!defined('BRATONIEN_TOOLS_PATH'))
{
http_response_code(404);
exit;
}
check_status(ACCESS_ADMINISTRATOR);
require_once(BRATONIEN_TOOLS_PATH.'include/friendship_code_upload.inc.php');
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($id < 1)
{
http_response_code(404);
exit;
}
$table = bratonien_tools_friendship_code_table();
$result = pwg_query('SELECT id, person_name, stored_name, mime_type FROM `'.$table.'` WHERE id='.$id.' LIMIT 1');
$row = pwg_db_fetch_assoc($result);
if (!$row)
{
http_response_code(404);
exit;
}
$stored_name = (string)$row['stored_name'];
$mime = strtolower((string)$row['mime_type']);
$allowed_mimes = array('image/png', 'image/jpeg', 'image/webp', 'image/gif');
if ($stored_name === '' || basename($stored_name) !== $stored_name || !in_array($mime, $allowed_mimes, true))
{
http_response_code(404);
exit;
}
$path = bratonien_tools_friendship_code_storage_root().DIRECTORY_SEPARATOR.$stored_name;
if (!is_file($path) || !is_readable($path))
{
http_response_code(404);
exit;
}
$extension = strtolower((string)pathinfo($stored_name, PATHINFO_EXTENSION));
if ($extension === '')
{
$extension = 'png';
}
header('Content-Type: '.$mime);
header('Content-Length: '.filesize($path));
header('Cache-Control: private, no-store, max-age=0');
header('X-Content-Type-Options: nosniff');
if (!empty($_GET['download']))
{
header('Content-Disposition: attachment; filename="freundschaftscode-'.$id.'.'.$extension.'"');
}
else
{
header('Content-Disposition: inline; filename="freundschaftscode-'.$id.'.'.$extension.'"');
}
readfile($path);
exit;

View File

@@ -0,0 +1,342 @@
<?php
if (!defined('PHPWG_ROOT_PATH'))
{
die('Hacking attempt!');
}
function bratonien_tools_atomic_cache_remove_tree($root, array &$failed)
{
if (!file_exists($root) && !is_link($root)) return;
// Niemals einem Symlink folgen. Auch ein Link auf ein Verzeichnis ist nur
// ein einzelner Eintrag des ausgelagerten Cachebaums und wird per unlink()
// entfernt. So kann das Cleanup kein Ziel ausserhalb des Cachebaums beruehren.
if (is_link($root))
{
if (!@unlink($root)) $failed[] = $root;
return;
}
if (is_file($root))
{
if (!@unlink($root)) $failed[] = $root;
return;
}
if (!is_dir($root))
{
$failed[] = $root;
return;
}
$entries = @scandir($root);
if ($entries === false)
{
$failed[] = $root;
return;
}
foreach ($entries as $entry)
{
if ($entry === '.' || $entry === '..') continue;
$path = $root.DIRECTORY_SEPARATOR.$entry;
if (is_link($path) || is_file($path))
{
if (!@unlink($path)) $failed[] = $path;
continue;
}
if (is_dir($path))
{
bratonien_tools_atomic_cache_remove_tree($path, $failed);
continue;
}
// Sonderdateien werden wie einzelne Cacheeintraege behandelt. unlink()
// ist hier sicherer als ein rekursiver Iterator, der Verweise interpretieren
// koennte.
if (!@unlink($path)) $failed[] = $path;
}
if (!@rmdir($root) && is_dir($root)) $failed[] = $root;
}
function bratonien_tools_atomic_cache_acquire_lock($path, $label, $timeout_seconds=10.0)
{
$directory = dirname($path);
if (!is_dir($directory) && !@mkdir($directory, 0775, true) && !is_dir($directory))
{
throw new RuntimeException($label.'-Lockverzeichnis konnte nicht angelegt werden.');
}
$handle = @fopen($path, 'c');
if (!$handle)
{
throw new RuntimeException($label.'-Lock konnte nicht geöffnet werden: '.$path);
}
$deadline = microtime(true) + max(0.1, (float)$timeout_seconds);
do
{
if (@flock($handle, LOCK_EX | LOCK_NB))
{
return $handle;
}
usleep(100000);
}
while (microtime(true) < $deadline);
fclose($handle);
throw new RuntimeException($label.' ist noch aktiv. Der Cache wurde nicht angefasst; bitte den laufenden Vorgang kurz abschließen lassen und erneut leeren.');
}
function bratonien_tools_atomic_cache_release_locks(array &$locks)
{
foreach (array_reverse($locks) as $handle)
{
if (!is_resource($handle)) continue;
@flock($handle, LOCK_UN);
fclose($handle);
}
$locks = array();
}
function bratonien_tools_atomic_cache_prepare_webdav_guards(array &$locks, array &$cancel_files)
{
if (!function_exists('bratonien_tools_webdav_warmup_connections')) return 0;
$connections = bratonien_tools_webdav_warmup_connections();
if (!$connections) return 0;
ksort($connections, SORT_NUMERIC);
// Jeder aktive WebDAV-Worker bekommt zuerst sein reguläres Abbruchsignal.
// Ein bereits gestarteter 10er-Batch darf sauber fertig werden; ein neuer
// Batch darf danach nicht mehr beginnen.
if (function_exists('bratonien_tools_request_webdav_cache_cancel'))
{
bratonien_tools_request_webdav_cache_cancel();
}
// Das Signal wird für alle Verbindungen gesetzt, auch wenn deren Statusdatei
// veraltet sein sollte. Sobald wir anschließend den Prozess-Lock besitzen,
// kann garantiert kein WebDAV-Worker während des Cache-Leerens schreiben.
foreach ($connections as $connection_id=>$runtime)
{
$cancel = function_exists('bratonien_tools_webdav_warmup_cancel_file_for_connection')
? bratonien_tools_webdav_warmup_cancel_file_for_connection($connection_id)
: PHPWG_ROOT_PATH.PWG_LOCAL_DIR.'bratonien-webdav-warmup.cancel-'.(int)$connection_id;
if (@file_put_contents($cancel, (string)time()."\n", LOCK_EX) === false)
{
throw new RuntimeException('WebDAV-Abbruchsignal für Verbindung #'.(int)$connection_id.' konnte nicht geschrieben werden.');
}
@chmod($cancel, 0664);
$cancel_files[] = $cancel;
}
foreach ($connections as $connection_id=>$runtime)
{
$state_dir = rtrim((string)($runtime['state_dir'] ?? ''), '/');
if ($state_dir === '')
{
throw new RuntimeException('WebDAV-State-Verzeichnis für Verbindung #'.(int)$connection_id.' fehlt.');
}
$locks[] = bratonien_tools_atomic_cache_acquire_lock(
$state_dir.'/webdav-cache-warmup.lock',
'WebDAV-Cache-Worker #'.(int)$connection_id,
10.0
);
}
return count($connections);
}
function bratonien_tools_atomic_cache_prepare_presentation_guard(array &$locks)
{
if (!function_exists('bratonien_tools_presentation_refresh_queue_dir')) return false;
$queue_dir = bratonien_tools_presentation_refresh_queue_dir();
if (!is_dir($queue_dir)) return false;
// Der Presentation-Worker erzeugt Bratonien-Wasserzeichen-Vorschauen im
// selben Derivatbaum. Deshalb muss auch er während des atomaren Leerens
// vollständig draußen bleiben.
$locks[] = bratonien_tools_atomic_cache_acquire_lock(
rtrim($queue_dir, '/').'/.worker.lock',
'Vorschau-Aktualisierung',
10.0
);
return true;
}
function bratonien_tools_clear_image_cache_atomic()
{
global $conf;
if (!defined('PWG_DERIVATIVE_DIR'))
{
throw new RuntimeException('PWG_DERIVATIVE_DIR ist nicht definiert.');
}
$held_locks = array();
$webdav_cancel_files = array();
$webdav_guards_ready = false;
try
{
// 1. Lokalen Cache-Builder sauber anhalten und seinen Prozess-Lock selbst
// halten. Damit kann zwischen Prüfung und atomarem Rename kein neuer
// lokaler Builder starten.
if (bratonien_tools_main_cache_process_active() || bratonien_tools_main_cache_is_running())
{
bratonien_tools_request_main_cache_cancel();
if (!bratonien_tools_wait_main_cache_stopped(10.0))
{
throw new RuntimeException('Der laufende Cache-Aufbau konnte noch nicht beendet werden. Bitte den Abbruch kurz abschließen lassen und erneut leeren.');
}
}
@unlink(bratonien_tools_main_cache_cancel_file());
$held_locks[] = bratonien_tools_atomic_cache_acquire_lock(
bratonien_tools_main_cache_lock_file(),
'Lokaler Piwigo-Cache-Worker',
10.0
);
// 2. WebDAV-Warmup regulär abbrechen und danach alle Verbindungs-Locks
// exklusiv halten. Der laufende Batch wird nicht hart beendet.
bratonien_tools_atomic_cache_prepare_webdav_guards($held_locks, $webdav_cancel_files);
$webdav_guards_ready = true;
// 3. Seit der Presentation-Refresh-Einführung kann auch dieser Worker
// Derivate erzeugen. Ohne seinen Lock konnte ein gerade geleerter Cache
// sofort wieder gefüllt werden und wie ein fehlgeschlagenes Löschen wirken.
bratonien_tools_atomic_cache_prepare_presentation_guard($held_locks);
$piwigo_root = realpath(PHPWG_ROOT_PATH);
if ($piwigo_root === false)
{
throw new RuntimeException('Piwigo-Root konnte für die Cache-Sicherheitsprüfung nicht aufgelöst werden.');
}
$cache_root = rtrim(PHPWG_ROOT_PATH, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR.trim(PWG_DERIVATIVE_DIR, '/\\');
$real_cache_root = realpath($cache_root);
if ($real_cache_root === false || !is_dir($real_cache_root))
{
throw new RuntimeException('Bildcache-Verzeichnis wurde nicht gefunden: '.$cache_root);
}
$root_prefix = rtrim($piwigo_root, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR;
if (strpos(rtrim($real_cache_root, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR, $root_prefix) !== 0)
{
throw new RuntimeException('Bildcache liegt außerhalb der Piwigo-Installation. Abbruch.');
}
if (rtrim($real_cache_root, DIRECTORY_SEPARATOR) === rtrim($piwigo_root, DIRECTORY_SEPARATOR))
{
throw new RuntimeException('Bildcache-Pfad entspricht dem Piwigo-Root. Sicherheitsabbruch.');
}
$before = bratonien_tools_scan_image_cache($real_cache_root);
$parent = dirname($real_cache_root);
if (!is_dir($parent) || !is_writable($parent))
{
throw new RuntimeException('Übergeordnetes Bildcache-Verzeichnis ist nicht beschreibbar: '.$parent);
}
$detached = $parent.'/.'.basename($real_cache_root).'.bratonien-clear-'.date('YmdHis').'-'.bin2hex(random_bytes(4));
if (file_exists($detached) || is_link($detached))
{
throw new RuntimeException('Temporäres Cache-Auslagerungsverzeichnis existiert bereits. Abbruch.');
}
if (!@rename($real_cache_root, $detached))
{
throw new RuntimeException('Bildcache konnte nicht atomar aus dem aktiven Pfad ausgelagert werden.');
}
$mode = isset($conf['chmod_value']) ? (int)$conf['chmod_value'] : 0755;
$umask = umask(0);
$created = @mkdir($real_cache_root, $mode, true);
umask($umask);
if (!$created && !is_dir($real_cache_root))
{
if (!file_exists($real_cache_root) && @rename($detached, $real_cache_root))
{
throw new RuntimeException('Neuer Bildcache konnte nicht angelegt werden; der bisherige Cache wurde vollständig wiederhergestellt.');
}
throw new RuntimeException('Neuer Bildcache konnte nicht angelegt und der bisherige Cache nicht automatisch wiederhergestellt werden. Manueller Eingriff erforderlich.');
}
@chmod($real_cache_root, $mode);
@file_put_contents($real_cache_root.'/index.htm', 'Not allowed!');
// Der Quellenindex selbst bleibt bestehen, weil sich die Quellen durch ein
// Cache-Leeren nicht ändern. Seine Fertigmarkierungen sind danach aber
// zwingend ungültig. Der Worker darf sonst einen leeren Piwigo-Cache als
// bereits verarbeitet ansehen, ohne den Cache selbst anzuschauen.
$webdav_invalidated = 0;
if (function_exists('bratonien_tools_invalidate_webdav_cache_completion'))
{
$webdav_invalidated = bratonien_tools_invalidate_webdav_cache_completion('Piwigo-Bildcache wurde atomar geleert.');
}
$failed = array();
bratonien_tools_atomic_cache_remove_tree($detached, $failed);
$active = bratonien_tools_scan_image_cache($real_cache_root);
bratonien_tools_write_main_cache_status(array(
'state'=>'idle',
'message'=>'Bildcache wurde atomar geleert. Kein Cache-Worker schreibt während des Löschvorgangs in den Derivatbaum.',
));
if ($failed)
{
throw new RuntimeException(sprintf(
'Der aktive Bildcache wurde erfolgreich geleert und neu angelegt, aber %d Datei(en)/Verzeichnis(se) des ausgelagerten Altbestands konnten nicht entfernt werden. Erste problematische Stelle: %s',
count($failed),
$failed[0]
));
}
$message = sprintf(
'Bildcache atomar geleert: %d alte Datei(en) (%s) entfernt, davon %d Custom-Derivate.',
$before['files'],
bratonien_tools_format_bytes($before['bytes']),
$before['custom']
);
if ($webdav_invalidated > 0)
{
$message .= sprintf(' Die Cache-Fertigmarkierungen von %d WebDAV-Worker-Index(en) wurden verworfen; die Quellenindizes selbst bleiben erhalten.', $webdav_invalidated);
}
if ($active['files'] > 0)
{
$message .= sprintf(
' Unmittelbar nach dem atomaren Umschalten wurden bereits %d neue Derivatdatei(en) durch normale Piwigo-Anfragen erzeugt; die eigenen Cache-Worker waren während des Löschens gesperrt und der alte Cachebaum wurde vollständig entfernt.',
$active['files']
);
}
else
{
$message .= ' Der neu aktive Cache ist zum Abschluss der Prüfung leer.';
}
return array('message'=>$message);
}
finally
{
// Nur wenn wirklich alle WebDAV-Prozess-Locks gesichert wurden, sind die
// Cancel-Dateien nicht mehr nötig. Bei einem Timeout bleiben sie bestehen,
// damit der noch laufende Worker nach seinem aktuellen Batch tatsächlich
// stoppt und das fehlgeschlagene Cache-Leeren nicht durch einen Folgebatch
// verschärft wird.
if ($webdav_guards_ready)
{
foreach ($webdav_cancel_files as $cancel)
{
@unlink($cancel);
}
}
bratonien_tools_atomic_cache_release_locks($held_locks);
}
}

View File

@@ -4,6 +4,8 @@ if (!defined('PHPWG_ROOT_PATH'))
die('Hacking attempt!');
}
require_once(BRATONIEN_TOOLS_PATH.'include/webdav_warmup_settings.inc.php');
function bratonien_tools_cache_worker_settings_file()
{
return PHPWG_ROOT_PATH.PWG_LOCAL_DIR.'bratonien-tools-cache-workers.json';
@@ -136,6 +138,8 @@ function bratonien_tools_get_cache_worker_settings()
$settings['auto_workers'] = min($settings['max_workers'], $settings['cpu_count']);
$settings['manual_workers'] = min($settings['max_workers'], $settings['manual_workers']);
$settings['worker_count'] = $settings['auto'] ? $settings['auto_workers'] : $settings['manual_workers'];
$settings['webdav_warmup'] = bratonien_tools_get_webdav_warmup_settings();
$settings['webdav_warmup']['status'] = bratonien_tools_get_webdav_warmup_status();
return $settings;
}

View File

@@ -0,0 +1,105 @@
<?php
if (!defined('PHPWG_ROOT_PATH'))
{
die('Hacking attempt!');
}
function bratonien_tools_customer_qr_register_frontend_menu($menu_ref_array)
{
if (defined('IN_ADMIN'))
{
return;
}
$settings = bratonien_tools_customer_qr_settings();
if (empty($settings['enabled']))
{
return;
}
if (!is_array($menu_ref_array) || empty($menu_ref_array[0]) || !is_object($menu_ref_array[0]))
{
return;
}
$menu = $menu_ref_array[0];
if (!method_exists($menu, 'get_id') || $menu->get_id() !== 'menubar' || !method_exists($menu, 'register_block'))
{
return;
}
if (!class_exists('RegisteredBlock'))
{
return;
}
$menu->register_block(new RegisteredBlock(
'mbBratonienCustomerQr',
'QR-Code hochladen',
BRATONIEN_TOOLS_ID
));
}
function bratonien_tools_customer_qr_prepare_frontend_menu($menu_ref_array)
{
if (defined('IN_ADMIN'))
{
return;
}
$settings = bratonien_tools_customer_qr_settings();
if (empty($settings['enabled']))
{
return;
}
if (!is_array($menu_ref_array) || empty($menu_ref_array[0]) || !is_object($menu_ref_array[0]))
{
return;
}
$menu = $menu_ref_array[0];
if (!method_exists($menu, 'get_id') || $menu->get_id() !== 'menubar')
{
return;
}
$block = $menu->get_block('mbBratonienCustomerQr');
if ($block === null)
{
return;
}
$url = htmlspecialchars(
get_root_url().'plugins/'.BRATONIEN_TOOLS_ID.'/customer-qr-upload.php',
ENT_QUOTES,
'UTF-8'
);
// Bootstrap Darkroom renders raw-content blocks directly in the root navbar.
// Keeping this as a separate Piwigo menu block avoids hiding the customer
// action inside mbMenu/"Entdecken" and still follows the normal menubar
// lifecycle instead of modifying the theme.
$block->raw_content = '<li class="nav-item bratonien-customer-qr-nav">'
.'<a class="nav-link" href="'.$url.'" title="QR-Code hochladen">'
.'<i class="fas fa-qrcode fa-fw" aria-hidden="true"></i> QR-Code hochladen'
.'</a></li>';
if (method_exists($menu, 'set_block_position'))
{
// Core defaults: Specials=200, Menu=250. Darkroom combines those two as
// "Entdecken"; 225 therefore places QR upload directly after it.
$menu->set_block_position('mbBratonienCustomerQr', 225);
}
}
add_event_handler(
'blockmanager_register_blocks',
'bratonien_tools_customer_qr_register_frontend_menu',
EVENT_HANDLER_PRIORITY_NEUTRAL + 10
);
add_event_handler(
'blockmanager_prepare_display',
'bratonien_tools_customer_qr_prepare_frontend_menu',
EVENT_HANDLER_PRIORITY_NEUTRAL + 10
);

View File

@@ -0,0 +1,503 @@
<?php
if (!defined('PHPWG_ROOT_PATH'))
{
die('Hacking attempt!');
}
function bratonien_tools_customer_qr_table()
{
return $GLOBALS['prefixeTable'].'bratonien_tools_customer_qr_uploads';
}
function bratonien_tools_customer_qr_year_limits()
{
return array(
2023 => 100,
2024 => 50,
2025 => 30,
2026 => 30,
);
}
function bratonien_tools_customer_qr_settings()
{
$default = array(
'enabled' => false,
);
if (!function_exists('conf_get_param'))
{
return $default;
}
$raw = conf_get_param('bratonien_customer_qr_upload', null);
if ($raw === null || $raw === '')
{
return $default;
}
$decoded = json_decode($raw, true);
return is_array($decoded) ? array_merge($default, $decoded) : $default;
}
function bratonien_tools_customer_qr_save_settings()
{
if (!function_exists('conf_update_param'))
{
throw new RuntimeException('Piwigo-Konfiguration ist nicht verfügbar.');
}
$settings = array(
'enabled' => !empty($_POST['customer_qr_enabled']),
);
conf_update_param('bratonien_customer_qr_upload', json_encode($settings));
return array(
'message' => $settings['enabled']
? 'QR-Upload aktiviert.'
: 'QR-Upload deaktiviert.',
);
}
function bratonien_tools_customer_qr_storage_root()
{
return PHPWG_ROOT_PATH.PWG_LOCAL_DIR.'bratonien-customer-qr';
}
function bratonien_tools_customer_qr_ensure_storage()
{
$table = bratonien_tools_customer_qr_table();
pwg_query("CREATE TABLE IF NOT EXISTS `$table` (
id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
upload_year smallint(5) unsigned NOT NULL,
code_number varchar(32) NOT NULL,
original_name varchar(255) NOT NULL,
stored_name varchar(255) NOT NULL,
mime_type varchar(100) NOT NULL,
file_size bigint(20) unsigned NOT NULL DEFAULT 0,
created datetime NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY year_code (upload_year, code_number),
KEY upload_year (upload_year)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
$root = bratonien_tools_customer_qr_storage_root();
if (!is_dir($root) && !@mkdir($root, 0770, true) && !is_dir($root))
{
throw new RuntimeException('QR-Upload-Verzeichnis konnte nicht angelegt werden.');
}
return $root;
}
function bratonien_tools_customer_qr_year($value)
{
$year = (int)$value;
$limits = bratonien_tools_customer_qr_year_limits();
if (!isset($limits[$year]))
{
throw new InvalidArgumentException('Erlaubt sind nur die Jahre 2023, 2024, 2025 und 2026.');
}
return $year;
}
function bratonien_tools_customer_qr_default_year()
{
$limits = bratonien_tools_customer_qr_year_limits();
$current = (int)date('Y');
if (isset($limits[$current]))
{
return $current;
}
$years = array_keys($limits);
sort($years, SORT_NUMERIC);
return (int)end($years);
}
function bratonien_tools_customer_qr_number($value)
{
$value = trim((string)$value);
if ($value === '' || !preg_match('/^[0-9]{1,32}$/', $value))
{
throw new InvalidArgumentException('Die QR-Code-Nummer darf nur aus Ziffern bestehen.');
}
$value = ltrim($value, '0');
if ($value === '' || $value === '0')
{
throw new InvalidArgumentException('Die QR-Code-Nummer muss mindestens 1 sein.');
}
return $value;
}
function bratonien_tools_customer_qr_number_for_year($year, $value)
{
$year = bratonien_tools_customer_qr_year($year);
$number = bratonien_tools_customer_qr_number($value);
$limits = bratonien_tools_customer_qr_year_limits();
$limit = (int)$limits[$year];
if (strlen($number) > strlen((string)$limit) || (int)$number > $limit)
{
throw new InvalidArgumentException('Für '.$year.' sind nur QR-Code-Nummern 1 bis '.$limit.' vorgesehen.');
}
return $number;
}
function bratonien_tools_customer_qr_exists($year, $number)
{
bratonien_tools_customer_qr_ensure_storage();
$year = bratonien_tools_customer_qr_year($year);
$number = bratonien_tools_customer_qr_number_for_year($year, $number);
$table = bratonien_tools_customer_qr_table();
$query = 'SELECT id FROM `'.$table.'` WHERE upload_year='.(int)$year
." AND code_number='".pwg_db_real_escape_string($number)."' LIMIT 1";
return pwg_db_num_rows(pwg_query($query)) > 0;
}
function bratonien_tools_customer_qr_files_array(array $files)
{
if (!isset($files['name']))
{
return array();
}
if (!is_array($files['name']))
{
return array($files);
}
$normalized = array();
$count = count($files['name']);
for ($i = 0; $i < $count; $i++)
{
$normalized[] = array(
'name' => isset($files['name'][$i]) ? $files['name'][$i] : '',
'type' => isset($files['type'][$i]) ? $files['type'][$i] : '',
'tmp_name' => isset($files['tmp_name'][$i]) ? $files['tmp_name'][$i] : '',
'error' => isset($files['error'][$i]) ? $files['error'][$i] : UPLOAD_ERR_NO_FILE,
'size' => isset($files['size'][$i]) ? $files['size'][$i] : 0,
);
}
return $normalized;
}
function bratonien_tools_customer_qr_validate_image(array $file)
{
if ((int)$file['error'] !== UPLOAD_ERR_OK)
{
throw new RuntimeException('Datei-Upload fehlgeschlagen (Code '.(int)$file['error'].').');
}
if (empty($file['tmp_name']) || !is_uploaded_file($file['tmp_name']))
{
throw new RuntimeException('Die hochgeladene Datei konnte nicht verifiziert werden.');
}
$image = @getimagesize($file['tmp_name']);
$mime = is_array($image) && !empty($image['mime']) ? strtolower((string)$image['mime']) : '';
$extensions = array(
'image/png' => 'png',
'image/jpeg' => 'jpg',
'image/webp' => 'webp',
'image/gif' => 'gif',
);
if (!isset($extensions[$mime]))
{
throw new RuntimeException('Erlaubt sind PNG, JPG, WEBP und GIF.');
}
return array(
'mime' => $mime,
'extension' => $extensions[$mime],
);
}
function bratonien_tools_customer_qr_unique_name($number, $extension)
{
try
{
$suffix = bin2hex(random_bytes(6));
}
catch (Throwable $e)
{
$suffix = str_replace('.', '', uniqid('', true));
}
return 'qr-'.$number.'-'.$suffix.'.'.$extension;
}
function bratonien_tools_customer_qr_process_uploads($year, array $files, array $numbers)
{
$year = bratonien_tools_customer_qr_year($year);
$root = bratonien_tools_customer_qr_ensure_storage();
$year_dir = $root.DIRECTORY_SEPARATOR.$year;
if (!is_dir($year_dir) && !@mkdir($year_dir, 0770, true) && !is_dir($year_dir))
{
throw new RuntimeException('Jahresverzeichnis für den QR-Upload konnte nicht angelegt werden.');
}
$lock_dir = $root.DIRECTORY_SEPARATOR.'.locks';
if (!is_dir($lock_dir) && !@mkdir($lock_dir, 0770, true) && !is_dir($lock_dir))
{
throw new RuntimeException('QR-Lockverzeichnis konnte nicht angelegt werden.');
}
$items = bratonien_tools_customer_qr_files_array($files);
$results = array();
$seen = array();
foreach ($items as $index => $file)
{
$display_name = trim((string)($file['name'] ?? ''));
$number = '';
if ($display_name === '')
{
$display_name = 'Datei '.($index + 1);
}
try
{
$number = bratonien_tools_customer_qr_number_for_year($year, isset($numbers[$index]) ? $numbers[$index] : '');
if (isset($seen[$number]))
{
$results[] = array(
'status' => 'duplicate',
'file' => $display_name,
'year' => $year,
'number' => $number,
'message' => 'Nummer ist innerhalb dieses Batches doppelt.',
);
continue;
}
$seen[$number] = true;
$lock_path = $lock_dir.DIRECTORY_SEPARATOR.$year.'-'.$number.'.lock';
$lock = @fopen($lock_path, 'c+');
if ($lock === false || !@flock($lock, LOCK_EX))
{
if (is_resource($lock)) fclose($lock);
throw new RuntimeException('Die Nummer konnte nicht sicher reserviert werden.');
}
try
{
if (bratonien_tools_customer_qr_exists($year, $number))
{
$results[] = array(
'status' => 'duplicate',
'file' => $display_name,
'year' => $year,
'number' => $number,
'message' => 'Diese QR-Code-Nummer ist für das gewählte Jahr bereits vorhanden.',
);
continue;
}
$image = bratonien_tools_customer_qr_validate_image($file);
$stored_name = bratonien_tools_customer_qr_unique_name($number, $image['extension']);
$target = $year_dir.DIRECTORY_SEPARATOR.$stored_name;
if (!@move_uploaded_file($file['tmp_name'], $target))
{
throw new RuntimeException('Die Datei konnte nicht dauerhaft gespeichert werden.');
}
@chmod($target, 0660);
$table = bratonien_tools_customer_qr_table();
$query = "INSERT INTO `$table` (upload_year, code_number, original_name, stored_name, mime_type, file_size, created) VALUES ("
.(int)$year.", '".pwg_db_real_escape_string($number)."', '"
.pwg_db_real_escape_string($display_name)."', '"
.pwg_db_real_escape_string($stored_name)."', '"
.pwg_db_real_escape_string($image['mime'])."', "
.max(0, (int)($file['size'] ?? 0)).", NOW())";
if (pwg_query($query) === false)
{
@unlink($target);
throw new RuntimeException('Der Upload konnte nicht in der QR-Code-Liste gespeichert werden.');
}
$results[] = array(
'status' => 'ok',
'file' => $display_name,
'year' => $year,
'number' => $number,
'message' => 'QR-Code erfolgreich gespeichert.',
);
}
finally
{
@flock($lock, LOCK_UN);
fclose($lock);
}
}
catch (Throwable $e)
{
$results[] = array(
'status' => 'error',
'file' => $display_name,
'year' => $year,
'number' => $number,
'message' => $e->getMessage(),
);
}
}
return $results;
}
function bratonien_tools_customer_qr_delete_upload()
{
$id = isset($_POST['customer_qr_id']) ? (int)$_POST['customer_qr_id'] : 0;
if ($id < 1)
{
throw new InvalidArgumentException('Ungültiger QR-Upload.');
}
$root = bratonien_tools_customer_qr_ensure_storage();
$table = bratonien_tools_customer_qr_table();
$result = pwg_query('SELECT id, upload_year, code_number, stored_name FROM `'.$table.'` WHERE id='.$id.' LIMIT 1');
$row = pwg_db_fetch_assoc($result);
if (!$row)
{
throw new RuntimeException('Der QR-Upload wurde nicht gefunden.');
}
$year = bratonien_tools_customer_qr_year($row['upload_year']);
$number = bratonien_tools_customer_qr_number_for_year($year, $row['code_number']);
$stored_name = (string)$row['stored_name'];
if ($stored_name === '' || basename($stored_name) !== $stored_name)
{
throw new RuntimeException('Der gespeicherte Dateiname ist ungültig.');
}
$lock_dir = $root.DIRECTORY_SEPARATOR.'.locks';
if (!is_dir($lock_dir) && !@mkdir($lock_dir, 0770, true) && !is_dir($lock_dir))
{
throw new RuntimeException('QR-Lockverzeichnis konnte nicht angelegt werden.');
}
$lock_path = $lock_dir.DIRECTORY_SEPARATOR.$year.'-'.$number.'.lock';
$lock = @fopen($lock_path, 'c+');
if ($lock === false || !@flock($lock, LOCK_EX))
{
if (is_resource($lock)) fclose($lock);
throw new RuntimeException('Der QR-Upload konnte nicht sicher gesperrt werden.');
}
try
{
$file = $root.DIRECTORY_SEPARATOR.$year.DIRECTORY_SEPARATOR.$stored_name;
if (is_file($file) && !@unlink($file))
{
throw new RuntimeException('Die QR-Datei konnte nicht gelöscht werden. Der Datenbankeintrag bleibt erhalten.');
}
if (pwg_query('DELETE FROM `'.$table.'` WHERE id='.$id.' LIMIT 1') === false)
{
throw new RuntimeException('Der QR-Datenbankeintrag konnte nicht gelöscht werden.');
}
}
finally
{
@flock($lock, LOCK_UN);
fclose($lock);
}
return array(
'message' => 'QR-Code '.$number.' aus '.$year.' gelöscht. Die Nummer ist wieder frei.',
);
}
function bratonien_tools_customer_qr_size_label($bytes)
{
$bytes = max(0, (int)$bytes);
if ($bytes >= 1048576)
{
return number_format($bytes / 1048576, 1, ',', '.').' MB';
}
if ($bytes >= 1024)
{
return number_format($bytes / 1024, 0, ',', '.').' KB';
}
return $bytes.' B';
}
function bratonien_tools_customer_qr_admin_data()
{
bratonien_tools_customer_qr_ensure_storage();
$settings = bratonien_tools_customer_qr_settings();
$table = bratonien_tools_customer_qr_table();
$limits = bratonien_tools_customer_qr_year_limits();
$counts = array_fill_keys(array_keys($limits), 0);
$total = 0;
$current_year = bratonien_tools_customer_qr_default_year();
$result = pwg_query('SELECT upload_year, COUNT(*) AS cnt FROM `'.$table.'` GROUP BY upload_year');
while ($row = pwg_db_fetch_assoc($result))
{
$year = (int)$row['upload_year'];
$count = (int)$row['cnt'];
$total += $count;
if (isset($counts[$year]))
{
$counts[$year] = $count;
}
}
$years = array();
foreach ($limits as $year => $capacity)
{
$used = (int)$counts[$year];
$years[] = array(
'year' => (int)$year,
'capacity' => (int)$capacity,
'used' => $used,
'remaining' => max(0, (int)$capacity - $used),
);
}
$uploads = array();
$upload_result = pwg_query(
'SELECT id, upload_year, code_number, original_name, file_size, created '
.'FROM `'.$table.'` '
.'ORDER BY upload_year DESC, CAST(code_number AS UNSIGNED) ASC, id ASC'
);
while ($row = pwg_db_fetch_assoc($upload_result))
{
$id = (int)$row['id'];
$uploads[] = array(
'id' => $id,
'year' => (int)$row['upload_year'],
'number' => (string)$row['code_number'],
'original_name' => (string)$row['original_name'],
'file_size' => (int)$row['file_size'],
'file_size_label' => bratonien_tools_customer_qr_size_label($row['file_size']),
'created' => (string)$row['created'],
'preview_url' => get_absolute_root_url(true).'plugins/'.BRATONIEN_TOOLS_ID.'/customer-qr-admin-file.php?id='.$id,
);
}
$year_keys = array_keys($limits);
sort($year_keys, SORT_NUMERIC);
return array(
'enabled' => !empty($settings['enabled']),
'url' => get_absolute_root_url(true).'plugins/'.BRATONIEN_TOOLS_ID.'/customer-qr-upload.php',
'year_min' => (int)reset($year_keys),
'year_max' => (int)end($year_keys),
'default_year' => $current_year,
'years' => $years,
'uploads' => $uploads,
'total' => $total,
'current_year_total' => (int)$counts[$current_year],
'current_year_capacity' => (int)$limits[$current_year],
'max_files' => max(1, (int)ini_get('max_file_uploads')),
);
}

View File

@@ -20,6 +20,7 @@ function bratonien_tools_create_tables()
$profiles = bratonien_tools_table('watermark_profiles');
$rules = bratonien_tools_table('watermark_rules');
$nc_connections = bratonien_tools_table('nc_connections');
$customer_qr = bratonien_tools_table('customer_qr_uploads');
pwg_query("CREATE TABLE IF NOT EXISTS `$profiles` (
id int(11) NOT NULL AUTO_INCREMENT,
@@ -81,6 +82,20 @@ function bratonien_tools_create_tables()
UNIQUE KEY connection_key (connection_key)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
pwg_query("CREATE TABLE IF NOT EXISTS `$customer_qr` (
id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
upload_year smallint(5) unsigned NOT NULL,
code_number varchar(32) NOT NULL,
original_name varchar(255) NOT NULL,
stored_name varchar(255) NOT NULL,
mime_type varchar(100) NOT NULL,
file_size bigint(20) unsigned NOT NULL DEFAULT 0,
created datetime NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY year_code (upload_year, code_number),
KEY upload_year (upload_year)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
if (function_exists('bratonien_tools_create_album_shares_table'))
{
bratonien_tools_create_album_shares_table();
@@ -92,6 +107,7 @@ function bratonien_tools_drop_tables()
pwg_query('DROP TABLE IF EXISTS `'.bratonien_tools_table('watermark_profiles').'`');
pwg_query('DROP TABLE IF EXISTS `'.bratonien_tools_table('watermark_rules').'`');
pwg_query('DROP TABLE IF EXISTS `'.bratonien_tools_table('nc_connections').'`');
pwg_query('DROP TABLE IF EXISTS `'.bratonien_tools_table('customer_qr_uploads').'`');
if (function_exists('bratonien_tools_drop_album_shares_table'))
{

View File

@@ -0,0 +1,320 @@
<?php
if (!defined('PHPWG_ROOT_PATH'))
{
die('Hacking attempt!');
}
function bratonien_tools_friendship_code_table()
{
return $GLOBALS['prefixeTable'].'bratonien_tools_friendship_codes';
}
function bratonien_tools_friendship_code_storage_root()
{
return PHPWG_ROOT_PATH.PWG_LOCAL_DIR.'bratonien-friendship-codes';
}
function bratonien_tools_friendship_code_ensure_storage()
{
$table = bratonien_tools_friendship_code_table();
pwg_query("CREATE TABLE IF NOT EXISTS `$table` (
id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
person_name varchar(190) NOT NULL,
normalized_name varchar(190) NOT NULL,
original_name varchar(255) NOT NULL,
stored_name varchar(255) NOT NULL,
mime_type varchar(100) NOT NULL,
file_size bigint(20) unsigned NOT NULL DEFAULT 0,
file_sha256 char(64) NOT NULL,
created datetime NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY normalized_name (normalized_name),
UNIQUE KEY file_sha256 (file_sha256)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
$root = bratonien_tools_friendship_code_storage_root();
if (!is_dir($root) && !@mkdir($root, 0770, true) && !is_dir($root))
{
throw new RuntimeException('Verzeichnis für Freundschaftscodes konnte nicht angelegt werden.');
}
return $root;
}
function bratonien_tools_friendship_code_name($value)
{
$name = trim((string)$value);
$name = preg_replace('/\s+/u', ' ', $name);
if ($name === '')
{
throw new InvalidArgumentException('Bitte einen Namen eingeben.');
}
$length = function_exists('mb_strlen') ? mb_strlen($name, 'UTF-8') : strlen($name);
if ($length > 120)
{
throw new InvalidArgumentException('Der Name darf höchstens 120 Zeichen lang sein.');
}
if (preg_match('/[\x00-\x1F\x7F]/u', $name))
{
throw new InvalidArgumentException('Der Name enthält ungültige Steuerzeichen.');
}
return $name;
}
function bratonien_tools_friendship_code_normalized_name($value)
{
$name = bratonien_tools_friendship_code_name($value);
return function_exists('mb_strtolower')
? mb_strtolower($name, 'UTF-8')
: strtolower($name);
}
function bratonien_tools_friendship_code_exists_for_name($name)
{
bratonien_tools_friendship_code_ensure_storage();
$normalized = bratonien_tools_friendship_code_normalized_name($name);
$table = bratonien_tools_friendship_code_table();
$query = "SELECT id FROM `$table` WHERE normalized_name='"
.pwg_db_real_escape_string($normalized)."' LIMIT 1";
return pwg_db_num_rows(pwg_query($query)) > 0;
}
function bratonien_tools_friendship_code_validate_image(array $file)
{
if ((int)($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK)
{
throw new RuntimeException('Datei-Upload fehlgeschlagen (Code '.(int)($file['error'] ?? UPLOAD_ERR_NO_FILE).').');
}
if (empty($file['tmp_name']) || !is_uploaded_file($file['tmp_name']))
{
throw new RuntimeException('Die hochgeladene Datei konnte nicht verifiziert werden.');
}
$image = @getimagesize($file['tmp_name']);
$mime = is_array($image) && !empty($image['mime']) ? strtolower((string)$image['mime']) : '';
$extensions = array(
'image/png' => 'png',
'image/jpeg' => 'jpg',
'image/webp' => 'webp',
'image/gif' => 'gif',
);
if (!isset($extensions[$mime]))
{
throw new RuntimeException('Erlaubt sind PNG, JPG, WEBP und GIF.');
}
return array(
'mime' => $mime,
'extension' => $extensions[$mime],
);
}
function bratonien_tools_friendship_code_unique_name($extension)
{
try
{
$suffix = bin2hex(random_bytes(8));
}
catch (Throwable $e)
{
$suffix = str_replace('.', '', uniqid('', true));
}
return 'friendship-'.$suffix.'.'.$extension;
}
function bratonien_tools_friendship_code_process_upload($name, array $file)
{
$name = bratonien_tools_friendship_code_name($name);
$normalized = bratonien_tools_friendship_code_normalized_name($name);
$root = bratonien_tools_friendship_code_ensure_storage();
$table = bratonien_tools_friendship_code_table();
$lock_dir = $root.DIRECTORY_SEPARATOR.'.locks';
if (!is_dir($lock_dir) && !@mkdir($lock_dir, 0770, true) && !is_dir($lock_dir))
{
throw new RuntimeException('Lockverzeichnis für Freundschaftscodes konnte nicht angelegt werden.');
}
$lock_path = $lock_dir.DIRECTORY_SEPARATOR.sha1($normalized).'.lock';
$lock = @fopen($lock_path, 'c+');
if ($lock === false || !@flock($lock, LOCK_EX))
{
if (is_resource($lock)) fclose($lock);
throw new RuntimeException('Der Freundschaftscode konnte nicht sicher reserviert werden.');
}
try
{
if (bratonien_tools_friendship_code_exists_for_name($name))
{
return array(
'status' => 'duplicate',
'kind' => 'friendship',
'name' => $name,
'file' => trim((string)($file['name'] ?? '')),
'message' => 'Für diesen Namen ist bereits ein Freundschaftscode hinterlegt.',
);
}
$image = bratonien_tools_friendship_code_validate_image($file);
$sha256 = @hash_file('sha256', $file['tmp_name']);
if (!is_string($sha256) || !preg_match('/^[a-f0-9]{64}$/', $sha256))
{
throw new RuntimeException('Der Freundschaftscode konnte nicht eindeutig geprüft werden.');
}
$hash_query = "SELECT person_name FROM `$table` WHERE file_sha256='"
.pwg_db_real_escape_string($sha256)."' LIMIT 1";
$hash_result = pwg_query($hash_query);
if (pwg_db_num_rows($hash_result) > 0)
{
$existing = pwg_db_fetch_assoc($hash_result);
return array(
'status' => 'duplicate',
'kind' => 'friendship',
'name' => $name,
'file' => trim((string)($file['name'] ?? '')),
'message' => 'Dieser Freundschaftscode wurde bereits hinterlegt'.(!empty($existing['person_name']) ? ' ('.(string)$existing['person_name'].')' : '').'.',
);
}
$stored_name = bratonien_tools_friendship_code_unique_name($image['extension']);
$target = $root.DIRECTORY_SEPARATOR.$stored_name;
if (!@move_uploaded_file($file['tmp_name'], $target))
{
throw new RuntimeException('Die Datei konnte nicht dauerhaft gespeichert werden.');
}
@chmod($target, 0660);
$original_name = trim((string)($file['name'] ?? ''));
if ($original_name === '')
{
$original_name = 'Freundschaftscode.'.$image['extension'];
}
$query = "INSERT INTO `$table` (person_name, normalized_name, original_name, stored_name, mime_type, file_size, file_sha256, created) VALUES ('"
.pwg_db_real_escape_string($name)."', '"
.pwg_db_real_escape_string($normalized)."', '"
.pwg_db_real_escape_string($original_name)."', '"
.pwg_db_real_escape_string($stored_name)."', '"
.pwg_db_real_escape_string($image['mime'])."', "
.max(0, (int)($file['size'] ?? 0)).", '"
.pwg_db_real_escape_string($sha256)."', NOW())";
if (pwg_query($query) === false)
{
@unlink($target);
throw new RuntimeException('Der Freundschaftscode konnte nicht in der Liste gespeichert werden.');
}
return array(
'status' => 'ok',
'kind' => 'friendship',
'name' => $name,
'file' => $original_name,
'message' => 'Freundschaftscode erfolgreich gespeichert.',
);
}
finally
{
@flock($lock, LOCK_UN);
fclose($lock);
}
}
function bratonien_tools_friendship_code_delete_upload()
{
$id = isset($_POST['friendship_code_id']) ? (int)$_POST['friendship_code_id'] : 0;
if ($id < 1)
{
throw new InvalidArgumentException('Ungültiger Freundschaftscode.');
}
$root = bratonien_tools_friendship_code_ensure_storage();
$table = bratonien_tools_friendship_code_table();
$result = pwg_query('SELECT id, person_name, normalized_name, stored_name FROM `'.$table.'` WHERE id='.$id.' LIMIT 1');
$row = pwg_db_fetch_assoc($result);
if (!$row)
{
throw new RuntimeException('Der Freundschaftscode wurde nicht gefunden.');
}
$stored_name = (string)$row['stored_name'];
if ($stored_name === '' || basename($stored_name) !== $stored_name)
{
throw new RuntimeException('Der gespeicherte Dateiname ist ungültig.');
}
$normalized = (string)$row['normalized_name'];
$lock_dir = $root.DIRECTORY_SEPARATOR.'.locks';
if (!is_dir($lock_dir) && !@mkdir($lock_dir, 0770, true) && !is_dir($lock_dir))
{
throw new RuntimeException('Lockverzeichnis für Freundschaftscodes konnte nicht angelegt werden.');
}
$lock = @fopen($lock_dir.DIRECTORY_SEPARATOR.sha1($normalized).'.lock', 'c+');
if ($lock === false || !@flock($lock, LOCK_EX))
{
if (is_resource($lock)) fclose($lock);
throw new RuntimeException('Der Freundschaftscode konnte nicht sicher gesperrt werden.');
}
try
{
$file = $root.DIRECTORY_SEPARATOR.$stored_name;
if (is_file($file) && !@unlink($file))
{
throw new RuntimeException('Die Datei konnte nicht gelöscht werden. Der Datenbankeintrag bleibt erhalten.');
}
if (pwg_query('DELETE FROM `'.$table.'` WHERE id='.$id.' LIMIT 1') === false)
{
throw new RuntimeException('Der Datenbankeintrag konnte nicht gelöscht werden.');
}
}
finally
{
@flock($lock, LOCK_UN);
fclose($lock);
}
return array(
'message' => 'Freundschaftscode von '.(string)$row['person_name'].' gelöscht.',
);
}
function bratonien_tools_friendship_code_admin_data()
{
bratonien_tools_friendship_code_ensure_storage();
$table = bratonien_tools_friendship_code_table();
$uploads = array();
$result = pwg_query(
'SELECT id, person_name, original_name, file_size, created FROM `'.$table.'` ORDER BY person_name ASC, id ASC'
);
while ($row = pwg_db_fetch_assoc($result))
{
$id = (int)$row['id'];
$base_url = get_absolute_root_url(true).'plugins/'.BRATONIEN_TOOLS_ID.'/friendship-code-admin-file.php?id='.$id;
$uploads[] = array(
'id' => $id,
'name' => (string)$row['person_name'],
'original_name' => (string)$row['original_name'],
'file_size' => (int)$row['file_size'],
'file_size_label' => function_exists('bratonien_tools_customer_qr_size_label')
? bratonien_tools_customer_qr_size_label($row['file_size'])
: (string)((int)$row['file_size']).' B',
'created' => (string)$row['created'],
'preview_url' => $base_url,
'download_url' => $base_url.'&download=1',
);
}
return array(
'total' => count($uploads),
'uploads' => $uploads,
);
}

View File

@@ -4,15 +4,6 @@ if (!defined('PHPWG_ROOT_PATH'))
die('Hacking attempt!');
}
/**
* NC Connector migration and verification phase.
*
* The existing /etc/piwigo-sync installation remains the production path.
* Bratonien Tools imports a copy of its configuration into its own connection
* store and verifies that copy independently. Importing and verification never
* change or stop the legacy sync.
*/
function bratonien_tools_nc_connector_table()
{
if (function_exists('bratonien_tools_table'))
@@ -30,9 +21,8 @@ function bratonien_tools_nc_connector_ensure_table()
id int(11) NOT NULL AUTO_INCREMENT,
connection_key varchar(64) NOT NULL,
name varchar(255) NOT NULL,
adapter enum('local','remote') NOT NULL DEFAULT 'local',
enabled tinyint(1) NOT NULL DEFAULT 0,
takeover_state enum('imported','verified','active','disabled') NOT NULL DEFAULT 'imported',
adapter enum('remote') NOT NULL DEFAULT 'remote',
enabled tinyint(1) NOT NULL DEFAULT 1,
config_json mediumtext NOT NULL,
secret_blob mediumtext DEFAULT NULL,
created datetime NOT NULL,
@@ -64,139 +54,59 @@ function bratonien_tools_nc_connector_secret_key()
function bratonien_tools_nc_connector_encrypt_secret($plain)
{
$plain = (string)$plain;
if ($plain === '')
{
return '';
}
if (!function_exists('openssl_encrypt'))
{
throw new RuntimeException('OpenSSL wird zum sicheren Speichern der Connector-Zugangsdaten benoetigt.');
}
if ($plain === '') return '';
if (!function_exists('openssl_encrypt')) throw new RuntimeException('OpenSSL wird zum sicheren Speichern der Connector-Zugangsdaten benötigt.');
$iv = random_bytes(12);
$tag = '';
$cipher = openssl_encrypt(
$plain,
'aes-256-gcm',
bratonien_tools_nc_connector_secret_key(),
OPENSSL_RAW_DATA,
$iv,
$tag
);
if ($cipher === false)
{
throw new RuntimeException('Connector-Zugangsdaten konnten nicht verschluesselt werden.');
}
$cipher = openssl_encrypt($plain, 'aes-256-gcm', bratonien_tools_nc_connector_secret_key(), OPENSSL_RAW_DATA, $iv, $tag);
if ($cipher === false) throw new RuntimeException('Connector-Zugangsdaten konnten nicht verschlüsselt werden.');
return base64_encode(json_encode(array(
'v' => 1,
'iv' => base64_encode($iv),
'tag' => base64_encode($tag),
'data' => base64_encode($cipher),
'v'=>1,
'iv'=>base64_encode($iv),
'tag'=>base64_encode($tag),
'data'=>base64_encode($cipher),
)));
}
function bratonien_tools_nc_connector_decrypt_secret($blob)
{
$blob = trim((string)$blob);
if ($blob === '')
{
return '';
}
if (!function_exists('openssl_decrypt'))
{
throw new RuntimeException('OpenSSL wird zum Lesen der Connector-Zugangsdaten benoetigt.');
}
if ($blob === '') return '';
if (!function_exists('openssl_decrypt')) throw new RuntimeException('OpenSSL wird zum Lesen der Connector-Zugangsdaten benötigt.');
$outer = base64_decode($blob, true);
$payload = is_string($outer) ? json_decode($outer, true) : null;
if (!is_array($payload) || (int)($payload['v'] ?? 0) !== 1)
{
throw new RuntimeException('Gespeicherte Connector-Zugangsdaten haben ein unbekanntes Format.');
}
if (!is_array($payload) || (int)($payload['v'] ?? 0) !== 1) throw new RuntimeException('Gespeicherte 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);
if (!is_string($iv) || !is_string($tag) || !is_string($cipher))
{
throw new RuntimeException('Gespeicherte Connector-Zugangsdaten sind beschaedigt.');
}
$plain = openssl_decrypt(
$cipher,
'aes-256-gcm',
bratonien_tools_nc_connector_secret_key(),
OPENSSL_RAW_DATA,
$iv,
$tag
);
if ($plain === false)
{
throw new RuntimeException('Connector-Zugangsdaten konnten nicht entschluesselt werden.');
}
if (!is_string($iv) || !is_string($tag) || !is_string($cipher)) throw new RuntimeException('Gespeicherte Connector-Zugangsdaten sind beschädigt.');
$plain = openssl_decrypt($cipher, 'aes-256-gcm', bratonien_tools_nc_connector_secret_key(), OPENSSL_RAW_DATA, $iv, $tag);
if ($plain === false) throw new RuntimeException('Connector-Zugangsdaten konnten nicht entschlüsselt werden.');
return (string)$plain;
}
function bratonien_tools_nc_connector_read_config($path)
function bratonien_tools_nc_connector_is_webdav(array $row)
{
$config = array();
if (!is_readable($path))
{
return $config;
}
$lines = @file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if (!is_array($lines))
{
return $config;
}
foreach ($lines as $line)
{
$line = trim($line);
if ($line === '' || $line[0] === '#')
{
continue;
}
if (!preg_match('/^([A-Z0-9_]+)=(.*)$/', $line, $matches))
{
continue;
}
$value = trim($matches[2]);
$length = strlen($value);
if ($length >= 2)
{
$first = $value[0];
$last = $value[$length - 1];
if (($first === '"' && $last === '"') || ($first === "'" && $last === "'"))
{
$value = substr($value, 1, -1);
}
}
$config[$matches[1]] = $value;
}
return $config;
$config = isset($row['config']) && is_array($row['config']) ? $row['config'] : array();
return (string)($row['adapter'] ?? '') === 'remote' && (string)($config['source_mode'] ?? '') === 'webdav-placeholder';
}
function bratonien_tools_nc_connector_connections()
{
bratonien_tools_nc_connector_ensure_table();
$table = bratonien_tools_nc_connector_table();
$result = pwg_query("SELECT id, connection_key, name, adapter, enabled, takeover_state, config_json, secret_blob, created, updated FROM `$table` ORDER BY id");
$result = pwg_query("SELECT id, connection_key, name, adapter, enabled, config_json, secret_blob, created, updated FROM `$table` WHERE adapter='remote' ORDER BY id");
$connections = array();
while ($row = pwg_db_fetch_assoc($result))
{
$config = json_decode((string)$row['config_json'], true);
if (!is_array($config))
{
$config = array();
}
$verification = isset($config['verification']) && is_array($config['verification']) ? $config['verification'] : array();
if (!is_array($config) || (string)($config['source_mode'] ?? '') !== 'webdav-placeholder') continue;
$has_fallback = false;
try
@@ -205,8 +115,7 @@ function bratonien_tools_nc_connector_connections()
$credentials = json_decode($plain, true);
if (is_array($credentials))
{
$has_fallback = trim((string)($credentials['piwigo_user'] ?? '')) !== ''
&& (string)($credentials['piwigo_password'] ?? '') !== '';
$has_fallback = trim((string)($credentials['piwigo_user'] ?? '')) !== '' && (string)($credentials['piwigo_password'] ?? '') !== '';
}
}
catch (Throwable $e)
@@ -218,17 +127,9 @@ function bratonien_tools_nc_connector_connections()
$row['id'] = (int)$row['id'];
$row['enabled'] = (bool)$row['enabled'];
$row['config'] = $config;
$row['host'] = isset($config['host']) ? (string)$config['host'] : '';
$row['database'] = isset($config['database']) ? (string)$config['database'] : '';
$row['user'] = isset($config['user']) ? (string)$config['user'] : '';
$row['source_view'] = isset($config['source_view']) ? (string)$config['source_view'] : '';
$row['storage_count'] = isset($config['storages']) && is_array($config['storages']) ? count($config['storages']) : 0;
$row['user'] = (string)($config['nextcloud_access_user'] ?? $config['access_user'] ?? '');
$row['storage_count'] = isset($config['roots']) && is_array($config['roots']) ? count($config['roots']) : 0;
$row['fallback_stored'] = $has_fallback;
$row['verification'] = $verification;
$row['verified_ok'] = !empty($verification['ok']);
$row['verified_at'] = isset($verification['checked_at']) ? (string)$verification['checked_at'] : '';
$row['source_count'] = isset($verification['source_count']) ? (int)$verification['source_count'] : null;
$row['verification_checks'] = isset($verification['checks']) && is_array($verification['checks']) ? $verification['checks'] : array();
$connections[] = $row;
}
@@ -240,233 +141,24 @@ function bratonien_tools_nc_connector_connection($id, $with_secret = false)
bratonien_tools_nc_connector_ensure_table();
$table = bratonien_tools_nc_connector_table();
$id = (int)$id;
if ($id <= 0)
{
return null;
}
if ($id <= 0) return null;
$columns = 'id, connection_key, name, adapter, enabled, takeover_state, config_json, created, updated';
if ($with_secret)
{
$columns .= ', secret_blob';
}
$result = pwg_query("SELECT $columns FROM `$table` WHERE id = $id LIMIT 1");
if (!pwg_db_num_rows($result))
{
return null;
}
$columns = 'id, connection_key, name, adapter, enabled, config_json, created, updated';
if ($with_secret) $columns .= ', secret_blob';
$result = pwg_query("SELECT $columns FROM `$table` WHERE id = $id AND adapter='remote' LIMIT 1");
if (!pwg_db_num_rows($result)) return null;
$row = pwg_db_fetch_assoc($result);
$row['id'] = (int)$row['id'];
$row['enabled'] = (bool)$row['enabled'];
$row['config'] = json_decode((string)$row['config_json'], true);
if (!is_array($row['config']))
{
$row['config'] = array();
}
if (!is_array($row['config']) || (string)($row['config']['source_mode'] ?? '') !== 'webdav-placeholder') return null;
return $row;
}
function bratonien_tools_nc_connector_import_bundle_path()
{
return '/tmp/bratonien-tools-nc-import.json';
}
function bratonien_tools_nc_connector_import_legacy()
{
$path = bratonien_tools_nc_connector_import_bundle_path();
if (!is_readable($path))
{
throw new RuntimeException('Kein lesbares Migrationspaket gefunden. Fuehre zuerst den angezeigten Connector-Migrationsbefehl im Piwigo-LXC aus.');
}
$raw = @file_get_contents($path);
$bundle = is_string($raw) ? json_decode($raw, true) : null;
if (!is_array($bundle) || (int)($bundle['format'] ?? 0) !== 1 || !is_array($bundle['config'] ?? null))
{
throw new RuntimeException('Das Migrationspaket ist ungueltig oder unvollstaendig.');
}
$legacy = $bundle['config'];
$required = array('NC_DB_HOST', 'NC_DB_PORT', 'NC_DB_NAME', 'NC_DB_USER', 'NC_DB_VIEW');
foreach ($required as $key)
{
if (!isset($legacy[$key]) || trim((string)$legacy[$key]) === '')
{
throw new RuntimeException('Im Migrationspaket fehlt '.$key.'.');
}
}
$password = isset($bundle['db_password']) ? (string)$bundle['db_password'] : '';
if ($password === '')
{
throw new RuntimeException('Das Migrationspaket enthaelt kein Datenbankpasswort.');
}
$config = array(
'host' => (string)$legacy['NC_DB_HOST'],
'port' => (string)$legacy['NC_DB_PORT'],
'database' => (string)$legacy['NC_DB_NAME'],
'user' => (string)$legacy['NC_DB_USER'],
'source_view' => (string)$legacy['NC_DB_VIEW'],
'activity_view' => isset($legacy['NC_ACTIVITY_VIEW']) ? (string)$legacy['NC_ACTIVITY_VIEW'] : 'piwigo_showcase_activity',
'gallery_root' => isset($legacy['GALLERY_ROOT']) ? (string)$legacy['GALLERY_ROOT'] : '',
'state_dir' => isset($legacy['STATE_DIR']) ? (string)$legacy['STATE_DIR'] : '',
'status_file' => isset($legacy['STATUS_FILE']) ? (string)$legacy['STATUS_FILE'] : '',
'quiet_seconds' => isset($legacy['QUIET_SECONDS']) ? (int)$legacy['QUIET_SECONDS'] : 120,
'max_wait_seconds' => isset($legacy['MAX_WAIT_SECONDS']) ? (int)$legacy['MAX_WAIT_SECONDS'] : 900,
'full_sync_seconds' => isset($legacy['FULL_SYNC_SECONDS']) ? (int)$legacy['FULL_SYNC_SECONDS'] : 86400,
'storages' => isset($bundle['storages']) && is_array($bundle['storages']) ? $bundle['storages'] : array(),
'imported_from' => '/etc/piwigo-sync/piwigo.conf',
'legacy_sync_enabled' => isset($legacy['PIWIGO_SYNC_ENABLED']) && (string)$legacy['PIWIGO_SYNC_ENABLED'] === '1',
);
$key_material = $config['host'].'|'.$config['database'].'|'.$config['user'].'|'.$config['source_view'];
$connection_key = 'legacy-'.substr(hash('sha256', $key_material), 0, 24);
$table = bratonien_tools_nc_connector_table();
bratonien_tools_nc_connector_ensure_table();
$now = date('Y-m-d H:i:s');
$config_json = json_encode($config, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$secret_blob = bratonien_tools_nc_connector_encrypt_secret($password);
$escaped_key = pwg_db_real_escape_string($connection_key);
$existing = pwg_query("SELECT id FROM `$table` WHERE connection_key = '$escaped_key' LIMIT 1");
if (pwg_db_num_rows($existing))
{
$row = pwg_db_fetch_assoc($existing);
$id = (int)$row['id'];
pwg_query("UPDATE `$table` SET
name = 'Bestehende Nextcloud',
adapter = 'local',
enabled = 0,
takeover_state = 'imported',
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");
}
else
{
pwg_query("INSERT INTO `$table`
(connection_key, name, adapter, enabled, takeover_state, config_json, secret_blob, created, updated)
VALUES (
'$escaped_key',
'Bestehende Nextcloud',
'local',
0,
'imported',
'".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)."'
)");
}
@unlink($path);
return array(
'message' => 'Bestehende Nextcloud-Verbindung wurde in den NC Connector importiert. Der produktive Legacy-Sync bleibt unveraendert aktiv; die importierte Verbindung ist noch nicht aktiviert.',
);
}
function bratonien_tools_nc_connector_view_name($name)
{
$name = trim((string)$name);
if (!preg_match('/^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)?$/', $name))
{
throw new RuntimeException('Ungueltiger PostgreSQL-View-Name in der Connector-Konfiguration.');
}
$parts = explode('.', $name);
$quoted = array();
foreach ($parts as $part)
{
$quoted[] = '"'.str_replace('"', '""', $part).'"';
}
return implode('.', $quoted);
}
function bratonien_tools_nc_connector_psql($config, $password, $query)
{
$psql = '/usr/bin/psql';
if (!is_executable($psql))
{
throw new RuntimeException('PostgreSQL-Client /usr/bin/psql ist nicht installiert oder nicht ausfuehrbar.');
}
if (!function_exists('proc_open'))
{
throw new RuntimeException('PHP-Funktion proc_open ist deaktiviert; Connector-Verifikation kann nicht ausgefuehrt werden.');
}
$command = array(
$psql,
'-X', '-A', '-t',
'-v', 'ON_ERROR_STOP=1',
'-h', (string)$config['host'],
'-p', (string)$config['port'],
'-U', (string)$config['user'],
'-d', (string)$config['database'],
'-c', (string)$query,
);
$descriptors = array(
0 => array('pipe', 'r'),
1 => array('pipe', 'w'),
2 => array('pipe', 'w'),
);
$env = array(
'PGPASSWORD' => (string)$password,
'PGCONNECT_TIMEOUT' => '5',
'LC_ALL' => 'C',
);
$process = @proc_open($command, $descriptors, $pipes, null, $env);
if (!is_resource($process))
{
throw new RuntimeException('PostgreSQL-Pruefprozess konnte nicht gestartet werden.');
}
fclose($pipes[0]);
$stdout = stream_get_contents($pipes[1]);
$stderr = stream_get_contents($pipes[2]);
fclose($pipes[1]);
fclose($pipes[2]);
$exit = proc_close($process);
$stdout = trim((string)$stdout);
$stderr = trim((string)$stderr);
if ($exit !== 0)
{
$detail = $stderr !== '' ? $stderr : 'psql Exit-Code '.$exit;
throw new RuntimeException('PostgreSQL-Abfrage fehlgeschlagen: '.$detail);
}
return $stdout;
}
function bratonien_tools_nc_connector_mount_points()
{
$mounts = array();
$content = @file_get_contents('/proc/self/mountinfo');
if (!is_string($content))
{
return $mounts;
}
foreach (preg_split('/\r\n|\r|\n/', $content) as $line)
{
if ($line === '') continue;
$parts = explode(' ', $line);
if (count($parts) < 5) continue;
$mount = str_replace(array('\\040','\\011','\\012','\\134'), array(' ',"\t","\n",'\\'), $parts[4]);
$mounts[rtrim($mount, '/')] = true;
}
return $mounts;
}
function bratonien_tools_nc_connector_status()
{
$connections = bratonien_tools_nc_connector_connections();
$legacy_config = '/etc/piwigo-sync/piwigo.conf';
$legacy_present = is_readable($legacy_config);
$active_count = 0;
foreach ($connections as $connection)
{
@@ -474,11 +166,9 @@ function bratonien_tools_nc_connector_status()
}
return array(
'phase' => 'native-runtime',
'legacy_config_path' => $legacy_config,
'legacy_present' => $legacy_present,
'connections' => $connections,
'connection_count' => count($connections),
'active_count' => $active_count,
'phase'=>'webdav',
'connections'=>$connections,
'connection_count'=>count($connections),
'active_count'=>$active_count,
);
}

View File

@@ -1,246 +0,0 @@
<?php
if (!defined('PHPWG_ROOT_PATH'))
{
die('Hacking attempt!');
}
function bratonien_tools_nc_api_credentials()
{
global $conf;
$blob = isset($conf['bratonien_nc_piwigo_api']) ? trim((string)$conf['bratonien_nc_piwigo_api']) : '';
if ($blob === '')
{
return array('key_id'=>'', 'key_secret'=>'');
}
try
{
$plain = bratonien_tools_nc_connector_decrypt_secret($blob);
$decoded = json_decode($plain, true);
if (!is_array($decoded))
{
return array('key_id'=>'', 'key_secret'=>'');
}
return array(
'key_id' => (string)($decoded['key_id'] ?? ''),
'key_secret' => (string)($decoded['key_secret'] ?? ''),
);
}
catch (Throwable $e)
{
return array('key_id'=>'', 'key_secret'=>'');
}
}
function bratonien_tools_nc_api_credentials_store($key_id, $key_secret)
{
global $conf;
$key_id = trim((string)$key_id);
$key_secret = trim((string)$key_secret);
if ($key_id === '' || $key_secret === '')
{
throw new RuntimeException('API-Schluessel-ID und Geheimnis muessen angegeben werden.');
}
$payload = json_encode(array(
'v' => 1,
'key_id' => $key_id,
'key_secret' => $key_secret,
), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
if (!is_string($payload))
{
throw new RuntimeException('API-Zugangsdaten konnten nicht serialisiert werden.');
}
$blob = bratonien_tools_nc_connector_encrypt_secret($payload);
conf_update_param('bratonien_nc_piwigo_api', $blob);
$conf['bratonien_nc_piwigo_api'] = $blob;
}
function bratonien_tools_nc_connector_api_delete()
{
global $conf;
conf_update_param('bratonien_nc_piwigo_api', '');
$conf['bratonien_nc_piwigo_api'] = '';
return array('message'=>'Gespeicherte Piwigo-API-Zugangsdaten wurden geloescht.');
}
function bratonien_tools_nc_connector_auth_credentials($connection)
{
$credentials = bratonien_tools_nc_connector_credentials_from_blob($connection['secret_blob'] ?? '');
return array(
'db_password' => (string)($credentials['db_password'] ?? ''),
'piwigo_user' => (string)($credentials['piwigo_user'] ?? ''),
'piwigo_password' => (string)($credentials['piwigo_password'] ?? ''),
);
}
function bratonien_tools_nc_connector_fallback_save()
{
$id = (int)($_POST['connection_id'] ?? 0);
$username = trim((string)($_POST['nc_fallback_user'] ?? ''));
$password = (string)($_POST['nc_fallback_password'] ?? '');
if ($username === '' || $password === '')
{
throw new RuntimeException('Benutzername und Passwort fuer den Fallback muessen angegeben werden.');
}
$connection = bratonien_tools_nc_connector_connection($id, true);
if (!$connection)
{
throw new RuntimeException('Connector-Verbindung wurde nicht gefunden.');
}
$credentials = bratonien_tools_nc_connector_auth_credentials($connection);
if ($credentials['db_password'] === '')
{
throw new RuntimeException('Das Datenbankpasswort der Verbindung fehlt.');
}
$blob = bratonien_tools_nc_connector_encrypt_credentials(
$credentials['db_password'],
$username,
$password
);
$table = bratonien_tools_nc_connector_table();
$now = date('Y-m-d H:i:s');
pwg_query("UPDATE `$table` SET secret_blob='".pwg_db_real_escape_string($blob)."', updated='".pwg_db_real_escape_string($now)."' WHERE id=".$id." LIMIT 1");
return array('message'=>'Piwigo-Benutzername und Passwort wurden verschluesselt als API-Fallback gespeichert.');
}
function bratonien_tools_nc_connector_fallback_delete()
{
$id = (int)($_POST['connection_id'] ?? 0);
$connection = bratonien_tools_nc_connector_connection($id, true);
if (!$connection)
{
throw new RuntimeException('Connector-Verbindung wurde nicht gefunden.');
}
$credentials = bratonien_tools_nc_connector_auth_credentials($connection);
if ($credentials['db_password'] === '')
{
throw new RuntimeException('Das Datenbankpasswort der Verbindung fehlt.');
}
$blob = bratonien_tools_nc_connector_encrypt_credentials($credentials['db_password'], '', '');
$table = bratonien_tools_nc_connector_table();
$now = date('Y-m-d H:i:s');
pwg_query("UPDATE `$table` SET secret_blob='".pwg_db_real_escape_string($blob)."', updated='".pwg_db_real_escape_string($now)."' WHERE id=".$id." LIMIT 1");
return array('message'=>'Gespeicherter Benutzername/Passwort-Fallback wurde geloescht.');
}
function bratonien_tools_nc_connector_fallback_http_request($url, array $fields, $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 => 900,
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_USERAGENT => 'Bratonien-Tools-NC-Fallback/'.(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);
curl_close($ch);
if ($body === false || $errno !== 0)
{
throw new RuntimeException('Piwigo-Fallback konnte nicht ausgefuehrt werden: '.$error);
}
if ($http < 200 || $http >= 300)
{
throw new RuntimeException('Piwigo-Fallback antwortete mit HTTP '.$http.'.');
}
return (string)$body;
}
function bratonien_tools_nc_connector_fallback_once()
{
if (!function_exists('curl_init'))
{
throw new RuntimeException('cURL ist in PHP nicht verfuegbar.');
}
$username = trim((string)($_POST['nc_fallback_user'] ?? ''));
$password = (string)($_POST['nc_fallback_password'] ?? '');
if ($username === '' || $password === '')
{
throw new RuntimeException('Benutzername und Passwort fuer den einmaligen Fallback muessen angegeben werden.');
}
$base = rtrim(get_absolute_root_url(true), '/');
$cookie_file = tempnam(sys_get_temp_dir(), 'br-nc-fallback-');
if ($cookie_file === false)
{
throw new RuntimeException('Temporare Fallback-Sitzung konnte nicht angelegt werden.');
}
try
{
$login_body = bratonien_tools_nc_connector_fallback_http_request(
$base.'/ws.php?format=json',
array(
'method'=>'pwg.session.login',
'username'=>$username,
'password'=>$password,
),
$cookie_file
);
$login = json_decode($login_body, true);
if (!is_array($login) || ($login['stat'] ?? '') !== 'ok')
{
throw new RuntimeException('Piwigo-Anmeldung fuer den einmaligen Fallback wurde abgelehnt.');
}
bratonien_tools_nc_connector_fallback_http_request(
$base.'/admin.php?page=site_update&site=1',
array(
'sync'=>'files',
'display_info'=>1,
'privacy_level'=>0,
'sync_meta'=>1,
'simulate'=>0,
'subcats-included'=>1,
'bratonien_connector'=>1,
'submit'=>1,
),
$cookie_file
);
$orphan_body = bratonien_tools_nc_connector_fallback_http_request(
$base.'/ws.php?format=json',
array(
'method'=>'bratonien.nc.syncOrphans',
'site_id'=>1,
'simulate'=>0,
),
$cookie_file
);
$orphan = json_decode($orphan_body, true);
if (!is_array($orphan) || ($orphan['stat'] ?? '') !== 'ok')
{
throw new RuntimeException('Orphan-Synchronisierung im einmaligen Fallback wurde abgelehnt.');
}
}
finally
{
@unlink($cookie_file);
}
return array('message'=>'Einmaliger Benutzername/Passwort-Fallback wurde ausgefuehrt. Die Zugangsdaten wurden nicht gespeichert.');
}

View File

@@ -0,0 +1,90 @@
<?php
if (!defined('PHPWG_ROOT_PATH'))
{
die('Hacking attempt!');
}
function bratonien_tools_nc_connector_scoped_secret(array $connection)
{
$config = is_array($connection['config'] ?? null) ? $connection['config'] : array();
if ((string)($connection['adapter'] ?? '') !== 'remote' || (string)($config['source_mode'] ?? '') !== 'webdav-placeholder')
{
throw new RuntimeException('Die Verbindung ist keine WebDAV-Verbindung.');
}
$plain = bratonien_tools_nc_connector_decrypt_secret($connection['secret_blob'] ?? '');
$decoded = json_decode($plain, true);
if (!is_array($decoded))
{
throw new RuntimeException('WebDAV-Zugangsdaten haben ein unbekanntes Format.');
}
return array(
'v'=>3,
'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'] ?? ''),
);
}
function bratonien_tools_nc_connector_store_scoped_secret($id, array $connection, array $credentials)
{
$config = is_array($connection['config'] ?? null) ? $connection['config'] : array();
if ((string)($connection['adapter'] ?? '') !== 'remote' || (string)($config['source_mode'] ?? '') !== 'webdav-placeholder')
{
throw new RuntimeException('Die Verbindung ist keine WebDAV-Verbindung.');
}
if (trim((string)($credentials['nextcloud_user'] ?? '')) === '' || (string)($credentials['nextcloud_password'] ?? '') === '')
{
throw new RuntimeException('Die Nextcloud-Zugangsdaten der WebDAV-Verbindung fehlen.');
}
$credentials['v'] = 3;
unset($credentials['db_password']);
$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['piwigo_auth'] = 'connection-scoped';
$config['api_enabled'] = trim((string)($credentials['api_key_id'] ?? '')) !== '' && trim((string)($credentials['api_key_secret'] ?? '')) !== '';
$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.');
$table = bratonien_tools_nc_connector_table();
$now = date('Y-m-d H:i:s');
pwg_query("UPDATE `$table` SET secret_blob='".pwg_db_real_escape_string($blob)."', config_json='".pwg_db_real_escape_string($config_json)."', updated='".pwg_db_real_escape_string($now)."' WHERE id=".(int)$id." LIMIT 1");
}
function bratonien_tools_nc_connector_fallback_save_scoped()
{
$id = (int)($_POST['connection_id'] ?? 0);
$username = trim((string)($_POST['nc_fallback_user'] ?? ''));
$password = (string)($_POST['nc_fallback_password'] ?? '');
if ($username === '' || $password === '') throw new RuntimeException('Benutzername und Passwort für den Fallback müssen angegeben werden.');
$connection = bratonien_tools_nc_connector_connection($id, true);
if (!$connection) throw new RuntimeException('Connector-Verbindung wurde nicht gefunden.');
bratonien_tools_nc_connector_validate_fallback_credentials($username, $password);
$credentials = bratonien_tools_nc_connector_scoped_secret($connection);
$credentials['piwigo_user'] = $username;
$credentials['piwigo_password'] = $password;
bratonien_tools_nc_connector_store_scoped_secret($id, $connection, $credentials);
return array('message'=>'Piwigo-Benutzername und Passwort wurden als Fallback dieser WebDAV-Verbindung gespeichert.');
}
function bratonien_tools_nc_connector_fallback_delete_scoped()
{
$id = (int)($_POST['connection_id'] ?? 0);
$connection = bratonien_tools_nc_connector_connection($id, true);
if (!$connection) throw new RuntimeException('Connector-Verbindung wurde nicht gefunden.');
$credentials = bratonien_tools_nc_connector_scoped_secret($connection);
$credentials['piwigo_user'] = '';
$credentials['piwigo_password'] = '';
bratonien_tools_nc_connector_store_scoped_secret($id, $connection, $credentials);
return array('message'=>'Fallback dieser WebDAV-Verbindung wurde gelöscht. Ein vorhandener API-Zugang blieb unverändert.');
}

View File

@@ -1,110 +0,0 @@
<?php
if (!defined('PHPWG_ROOT_PATH'))
{
die('Hacking attempt!');
}
function bratonien_tools_nc_connector_create_local_api_first()
{
$required = array(
'nc_name' => 'Name',
'nc_host' => 'PostgreSQL-Host',
'nc_database' => 'Datenbank',
'nc_user' => 'Reader-Benutzer',
'nc_db_password' => 'Reader-Passwort',
'nc_source_view' => 'Source-View',
'nc_activity_view' => 'Activity-View',
'nc_gallery_root' => 'Galerie-Pfad',
);
foreach ($required as $field => $label)
{
if (trim((string)($_POST[$field] ?? '')) === '')
{
throw new RuntimeException($label.' fehlt.');
}
}
$fallback_user = trim((string)($_POST['nc_piwigo_user'] ?? ''));
$fallback_password = (string)($_POST['nc_piwigo_password'] ?? '');
if (($fallback_user === '') !== ($fallback_password === ''))
{
throw new RuntimeException('Fallback-Benutzer und Fallback-Passwort muessen entweder beide angegeben oder beide leer gelassen werden.');
}
$api = bratonien_tools_nc_api_credentials();
if (($api['key_id'] ?? '') === '' && $fallback_user === '')
{
throw new RuntimeException('Es ist weder ein gespeicherter Piwigo-API-Zugang noch ein Benutzername/Passwort-Fallback vorhanden.');
}
$port = (int)($_POST['nc_port'] ?? 5432);
if ($port < 1 || $port > 65535)
{
throw new RuntimeException('Ungueltiger PostgreSQL-Port.');
}
$gallery_root = rtrim(trim((string)$_POST['nc_gallery_root']), '/');
if ($gallery_root === '' || $gallery_root[0] !== '/')
{
throw new RuntimeException('Der Galerie-Pfad muss ein absoluter Pfad sein.');
}
$config = array(
'host' => trim((string)$_POST['nc_host']),
'port' => (string)$port,
'database' => trim((string)$_POST['nc_database']),
'user' => trim((string)$_POST['nc_user']),
'source_view' => trim((string)$_POST['nc_source_view']),
'activity_view' => trim((string)$_POST['nc_activity_view']),
'gallery_root' => $gallery_root,
'state_dir' => '',
'status_file' => '',
'quiet_seconds' => max(0, (int)($_POST['nc_quiet_seconds'] ?? 120)),
'max_wait_seconds' => max(60, (int)($_POST['nc_max_wait_seconds'] ?? 900)),
'full_sync_seconds' => max(300, (int)($_POST['nc_full_sync_seconds'] ?? 86400)),
'storages' => bratonien_tools_nc_connector_parse_storages($_POST['nc_storages'] ?? ''),
'origin' => 'native',
'piwigo_auth' => 'api-first',
);
bratonien_tools_nc_connector_view_name($config['source_view']);
bratonien_tools_nc_connector_view_name($config['activity_view']);
$table = bratonien_tools_nc_connector_table();
bratonien_tools_nc_connector_ensure_table();
$now = date('Y-m-d H:i:s');
$connection_key = 'local-'.bin2hex(random_bytes(12));
$secret_blob = bratonien_tools_nc_connector_encrypt_credentials(
(string)$_POST['nc_db_password'],
$fallback_user,
$fallback_password
);
$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.');
}
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(trim((string)$_POST['nc_name']))."',
'local', 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();
$config['state_dir'] = '/var/lib/bratonien-tools/nc-connector/connection-'.$id;
$config['status_file'] = $config['state_dir'].'/connector-status.json';
$config_json = json_encode($config, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
pwg_query("UPDATE `$table` SET config_json='".pwg_db_real_escape_string($config_json)."' WHERE id=".$id);
return array(
'message' => $fallback_user === ''
? 'Nextcloud-Verbindung wurde API-first ohne dauerhaft gespeicherten Benutzername/Passwort-Fallback angelegt. Bitte technisch pruefen und danach im LXC aktivieren.'
: 'Nextcloud-Verbindung wurde API-first mit verschluesseltem Benutzername/Passwort-Fallback angelegt. Bitte technisch pruefen und danach im LXC aktivieren.'
);
}

View 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.',
);
}

View File

@@ -1,310 +0,0 @@
<?php
if (!defined('PHPWG_ROOT_PATH'))
{
die('Hacking attempt!');
}
function bratonien_tools_nc_connector_credentials_from_blob($blob)
{
$plain = bratonien_tools_nc_connector_decrypt_secret($blob);
if ($plain === '')
{
return array('db_password'=>'', 'piwigo_user'=>'', 'piwigo_password'=>'');
}
$decoded = json_decode($plain, true);
if (is_array($decoded) && isset($decoded['db_password']))
{
return array(
'db_password' => (string)($decoded['db_password'] ?? ''),
'piwigo_user' => (string)($decoded['piwigo_user'] ?? ''),
'piwigo_password' => (string)($decoded['piwigo_password'] ?? ''),
);
}
// Backwards compatibility for migrated 0.14.x connections.
return array('db_password'=>$plain, 'piwigo_user'=>'', 'piwigo_password'=>'');
}
function bratonien_tools_nc_connector_encrypt_credentials($db_password, $piwigo_user, $piwigo_password)
{
$payload = json_encode(array(
'v' => 1,
'db_password' => (string)$db_password,
'piwigo_user' => (string)$piwigo_user,
'piwigo_password' => (string)$piwigo_password,
), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
if (!is_string($payload))
{
throw new RuntimeException('Connector-Zugangsdaten konnten nicht serialisiert werden.');
}
return bratonien_tools_nc_connector_encrypt_secret($payload);
}
function bratonien_tools_nc_connector_parse_storages($raw)
{
$storages = array();
$lines = preg_split('/\r\n|\r|\n/', trim((string)$raw));
foreach ($lines as $line)
{
$line = trim($line);
if ($line === '')
{
continue;
}
$parts = array_map('trim', explode('|', $line));
if (count($parts) !== 3 || $parts[0] === '' || $parts[1] === '' || $parts[2] === '')
{
throw new RuntimeException('Storage-Zeilen muessen das Format storage_id | source_prefix | local_mount verwenden.');
}
if ($parts[2][0] !== '/')
{
throw new RuntimeException('Der lokale Storage-Mount muss ein absoluter Pfad sein.');
}
$storages[] = array(
'storage_id' => $parts[0],
'source_prefix' => $parts[1],
'local_mount' => rtrim($parts[2], '/'),
);
}
if (!$storages)
{
throw new RuntimeException('Mindestens ein Storage muss konfiguriert werden.');
}
return $storages;
}
function bratonien_tools_nc_connector_create_local()
{
$required = array(
'nc_name' => 'Name',
'nc_host' => 'PostgreSQL-Host',
'nc_database' => 'Datenbank',
'nc_user' => 'Reader-Benutzer',
'nc_db_password' => 'Reader-Passwort',
'nc_source_view' => 'Source-View',
'nc_activity_view' => 'Activity-View',
'nc_gallery_root' => 'Galerie-Pfad',
'nc_piwigo_user' => 'Piwigo-Benutzer',
'nc_piwigo_password' => 'Piwigo-Passwort',
);
foreach ($required as $field => $label)
{
if (trim((string)($_POST[$field] ?? '')) === '')
{
throw new RuntimeException($label.' fehlt.');
}
}
$port = (int)($_POST['nc_port'] ?? 5432);
if ($port < 1 || $port > 65535)
{
throw new RuntimeException('Ungueltiger PostgreSQL-Port.');
}
$gallery_root = rtrim(trim((string)$_POST['nc_gallery_root']), '/');
if ($gallery_root === '' || $gallery_root[0] !== '/')
{
throw new RuntimeException('Der Galerie-Pfad muss ein absoluter Pfad sein.');
}
$config = array(
'host' => trim((string)$_POST['nc_host']),
'port' => (string)$port,
'database' => trim((string)$_POST['nc_database']),
'user' => trim((string)$_POST['nc_user']),
'source_view' => trim((string)$_POST['nc_source_view']),
'activity_view' => trim((string)$_POST['nc_activity_view']),
'gallery_root' => $gallery_root,
'state_dir' => '',
'status_file' => '',
'quiet_seconds' => max(0, (int)($_POST['nc_quiet_seconds'] ?? 120)),
'max_wait_seconds' => max(60, (int)($_POST['nc_max_wait_seconds'] ?? 900)),
'full_sync_seconds' => max(300, (int)($_POST['nc_full_sync_seconds'] ?? 86400)),
'storages' => bratonien_tools_nc_connector_parse_storages($_POST['nc_storages'] ?? ''),
'origin' => 'native',
);
bratonien_tools_nc_connector_view_name($config['source_view']);
bratonien_tools_nc_connector_view_name($config['activity_view']);
$table = bratonien_tools_nc_connector_table();
bratonien_tools_nc_connector_ensure_table();
$now = date('Y-m-d H:i:s');
$connection_key = 'local-'.bin2hex(random_bytes(12));
$secret_blob = bratonien_tools_nc_connector_encrypt_credentials(
(string)$_POST['nc_db_password'],
trim((string)$_POST['nc_piwigo_user']),
(string)$_POST['nc_piwigo_password']
);
$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.');
}
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(trim((string)$_POST['nc_name']))."',
'local', 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();
$config['state_dir'] = '/var/lib/bratonien-tools/nc-connector/connection-'.$id;
$config['status_file'] = $config['state_dir'].'/connector-status.json';
$config_json = json_encode($config, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
pwg_query("UPDATE `$table` SET config_json='".pwg_db_real_escape_string($config_json)."' WHERE id=".$id);
return array('message'=>'Nextcloud-Verbindung wurde angelegt. Bitte zuerst technisch pruefen und danach im LXC aktivieren.');
}
function bratonien_tools_nc_connector_verify_managed()
{
$id = isset($_POST['connection_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 Verifikation ist derzeit nur fuer lokale Connector-Verbindungen verfuegbar.');
}
$config = $connection['config'];
foreach (array('host','port','database','user','source_view','activity_view') as $key)
{
if (trim((string)($config[$key] ?? '')) === '')
{
throw new RuntimeException('Connector-Konfiguration ist unvollstaendig: '.$key.' fehlt.');
}
}
$credentials = bratonien_tools_nc_connector_credentials_from_blob($connection['secret_blob'] ?? '');
if ($credentials['db_password'] === '')
{
throw new RuntimeException('Fuer diese Verbindung ist kein Datenbankpasswort gespeichert.');
}
$checks = array();
$ok = true;
$source_count = null;
try
{
bratonien_tools_nc_connector_psql($config, $credentials['db_password'], 'SELECT 1');
$checks[] = array('name'=>'PostgreSQL-Verbindung', 'ok'=>true, 'detail'=>'Reader-Anmeldung erfolgreich');
}
catch (Throwable $e)
{
$checks[] = array('name'=>'PostgreSQL-Verbindung', 'ok'=>false, 'detail'=>$e->getMessage());
$ok = false;
}
if ($ok)
{
try
{
$source_view = bratonien_tools_nc_connector_view_name($config['source_view']);
$value = bratonien_tools_nc_connector_psql($config, $credentials['db_password'], 'SELECT COUNT(*) FROM '.$source_view);
if (!preg_match('/^\d+$/', $value))
{
throw new RuntimeException('Source-View lieferte keinen gueltigen Zaehler.');
}
$source_count = (int)$value;
$checks[] = array('name'=>'Source-View', 'ok'=>true, 'detail'=>$source_count.' Quelle(n) lesbar');
}
catch (Throwable $e)
{
$checks[] = array('name'=>'Source-View', 'ok'=>false, 'detail'=>$e->getMessage());
$ok = false;
}
try
{
$activity_view = bratonien_tools_nc_connector_view_name($config['activity_view']);
bratonien_tools_nc_connector_psql($config, $credentials['db_password'], 'SELECT 1 FROM '.$activity_view.' LIMIT 1');
$checks[] = array('name'=>'Activity-View', 'ok'=>true, 'detail'=>'View lesbar');
}
catch (Throwable $e)
{
$checks[] = array('name'=>'Activity-View', 'ok'=>false, 'detail'=>$e->getMessage());
$ok = false;
}
}
$storages = isset($config['storages']) && is_array($config['storages']) ? $config['storages'] : array();
$mount_points = bratonien_tools_nc_connector_mount_points();
if (!$storages)
{
$checks[] = array('name'=>'Storage-Mounts', 'ok'=>false, 'detail'=>'Keine Storage-Zuordnung gespeichert');
$ok = false;
}
else
{
foreach ($storages as $index => $storage)
{
$path = rtrim((string)($storage['local_mount'] ?? ''), '/');
$exists = $path !== '' && is_dir($path);
$readable = $exists && is_readable($path);
$mounted = $path !== '' && isset($mount_points[$path]);
$storage_ok = $exists && $readable && $mounted;
$storage_id = (string)($storage['storage_id'] ?? ('#'.($index + 1)));
$detail = $storage_id.' -> '.($path !== '' ? $path : '(kein Pfad)');
if (!$exists) $detail .= ' (Pfad fehlt)';
elseif (!$readable) $detail .= ' (nicht lesbar)';
elseif (!$mounted) $detail .= ' (kein aktiver Mount)';
else $detail .= ' (bereit)';
$checks[] = array('name'=>'Storage '.($index + 1), 'ok'=>$storage_ok, 'detail'=>$detail);
if (!$storage_ok) $ok = false;
}
}
$config['verification'] = array(
'checked_at' => date('Y-m-d H:i:s'),
'ok' => $ok,
'source_count' => $source_count,
'checks' => $checks,
);
$table = bratonien_tools_nc_connector_table();
$config_json = json_encode($config, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
if (!is_string($config_json))
{
throw new RuntimeException('Verifikationsergebnis konnte nicht gespeichert werden.');
}
$state = $ok ? 'verified' : ((string)$connection['takeover_state'] === 'disabled' ? 'disabled' : 'imported');
$now = date('Y-m-d H:i:s');
pwg_query("UPDATE `$table` SET takeover_state='".pwg_db_real_escape_string($state)."', enabled=0, config_json='".pwg_db_real_escape_string($config_json)."', updated='".pwg_db_real_escape_string($now)."' WHERE id=".$id);
if (!$ok)
{
throw new RuntimeException('Connector-Verifikation ist fehlgeschlagen. Die Verbindung bleibt deaktiviert; Details stehen im NC Connector.');
}
return array('message'=>'Connector-Verbindung wurde erfolgreich verifiziert. PostgreSQL, Views und Storage-Mounts sind erreichbar.');
}
function bratonien_tools_nc_connector_delete()
{
$id = (int)($_POST['connection_id'] ?? 0);
$connection = bratonien_tools_nc_connector_connection($id, false);
if (!$connection)
{
throw new RuntimeException('Connector-Verbindung wurde nicht gefunden.');
}
if (!empty($connection['enabled']) || (string)$connection['takeover_state'] === 'active')
{
throw new RuntimeException('Eine aktive Verbindung kann nicht geloescht werden. Sie muss zuerst deaktiviert werden.');
}
$table = bratonien_tools_nc_connector_table();
pwg_query("DELETE FROM `$table` WHERE id=".$id." LIMIT 1");
return array('message'=>'Connector-Verbindung wurde geloescht.');
}

View File

@@ -7,10 +7,7 @@ if (!defined('PHPWG_ROOT_PATH'))
function bratonien_tools_nc_connector_xml_value(SimpleXMLElement $node)
{
$children = $node->children();
if (count($children) === 0)
{
return (string)$node;
}
if (count($children) === 0) return (string)$node;
$result = array();
foreach ($children as $name => $child)
@@ -18,16 +15,10 @@ function bratonien_tools_nc_connector_xml_value(SimpleXMLElement $node)
$value = bratonien_tools_nc_connector_xml_value($child);
if (array_key_exists($name, $result))
{
if (!is_array($result[$name]) || !array_is_list($result[$name]))
{
$result[$name] = array($result[$name]);
}
if (!is_array($result[$name]) || !array_is_list($result[$name])) $result[$name] = array($result[$name]);
$result[$name][] = $value;
}
else
{
$result[$name] = $value;
}
else $result[$name] = $value;
}
return $result;
}
@@ -35,15 +26,9 @@ function bratonien_tools_nc_connector_xml_value(SimpleXMLElement $node)
function bratonien_tools_nc_connector_decode_api_response($body, $content_type = '')
{
$decoded = json_decode((string)$body, true);
if (is_array($decoded))
{
return $decoded;
}
if (is_array($decoded)) return $decoded;
if (!function_exists('simplexml_load_string'))
{
throw new RuntimeException('Piwigo-API lieferte XML, aber SimpleXML ist in PHP nicht verfuegbar.');
}
if (!function_exists('simplexml_load_string')) throw new RuntimeException('Piwigo-API lieferte XML, aber SimpleXML ist in PHP nicht verfügbar.');
$previous = libxml_use_internal_errors(true);
$xml = simplexml_load_string((string)$body);
@@ -52,7 +37,7 @@ function bratonien_tools_nc_connector_decode_api_response($body, $content_type =
if ($xml === false || $xml->getName() !== 'rsp')
{
$detail = $content_type !== '' ? ' Antworttyp: '.$content_type.'.' : '';
throw new RuntimeException('Piwigo-API lieferte weder gueltiges JSON noch eine gueltige XML-Webservice-Antwort.'.$detail);
throw new RuntimeException('Piwigo-API lieferte weder gültiges JSON noch eine gültige XML-Webservice-Antwort.'.$detail);
}
$response = array('stat'=>(string)$xml['stat']);
@@ -61,27 +46,17 @@ function bratonien_tools_nc_connector_decode_api_response($body, $content_type =
$value = bratonien_tools_nc_connector_xml_value($child);
if (array_key_exists($name, $response))
{
if (!is_array($response[$name]) || !array_is_list($response[$name]))
{
$response[$name] = array($response[$name]);
}
if (!is_array($response[$name]) || !array_is_list($response[$name])) $response[$name] = array($response[$name]);
$response[$name][] = $value;
}
else
{
$response[$name] = $value;
}
else $response[$name] = $value;
}
return $response;
}
function bratonien_tools_nc_connector_api_payload(array $decoded)
{
if (array_key_exists('result', $decoded))
{
return $decoded['result'];
}
if (array_key_exists('result', $decoded)) return $decoded['result'];
unset($decoded['stat']);
return $decoded;
}
@@ -91,66 +66,42 @@ function bratonien_tools_nc_connector_collect_method_names($value, array &$metho
if (is_string($value))
{
$value = trim($value);
if ($value !== '' && preg_match('/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)+$/', $value))
{
$methods[$value] = true;
}
return;
}
if (!is_array($value))
{
if ($value !== '' && preg_match('/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)+$/', $value)) $methods[$value] = true;
return;
}
if (!is_array($value)) return;
if (isset($value['name']) && is_string($value['name']))
{
$name = trim($value['name']);
if ($name !== '')
{
$methods[$name] = true;
}
}
foreach ($value as $entry)
{
bratonien_tools_nc_connector_collect_method_names($entry, $methods);
if ($name !== '') $methods[$name] = true;
}
foreach ($value as $entry) bratonien_tools_nc_connector_collect_method_names($entry, $methods);
}
function bratonien_tools_nc_connector_piwigo_api_request($api_key_id, $api_key_secret, $method)
{
if (!function_exists('curl_init'))
{
throw new RuntimeException('cURL ist in PHP nicht verfuegbar. Der API-Key-Test kann nicht ausgefuehrt werden.');
}
if (!function_exists('curl_init')) throw new RuntimeException('cURL ist in PHP nicht verfügbar. Der API-Key-Test kann nicht ausgeführt werden.');
$api_key_id = trim((string)$api_key_id);
$api_key_secret = trim((string)$api_key_secret);
if ($api_key_id === '' || $api_key_secret === '')
{
throw new RuntimeException('API-Schluessel-ID und Geheimnis muessen angegeben werden.');
}
if ($api_key_id === '' || $api_key_secret === '') throw new RuntimeException('API-Schlüssel-ID und Geheimnis müssen angegeben werden.');
$api_key = $api_key_id.':'.$api_key_secret;
$url = rtrim(get_absolute_root_url(true), '/').'/ws.php';
$ch = curl_init($url);
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query(array(
'method' => (string)$method,
'format' => 'json',
)),
CURLOPT_HTTPHEADER => array(
'X-PIWIGO-API: '.$api_key,
CURLOPT_RETURNTRANSFER=>true,
CURLOPT_POST=>true,
CURLOPT_POSTFIELDS=>http_build_query(array('method'=>(string)$method,'format'=>'json')),
CURLOPT_HTTPHEADER=>array(
'X-PIWIGO-API: '.$api_key_id.':'.$api_key_secret,
'Accept: application/json, text/xml;q=0.9',
'Content-Type: application/x-www-form-urlencoded',
),
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'),
CURLOPT_CONNECTTIMEOUT=>10,
CURLOPT_TIMEOUT=>20,
CURLOPT_FOLLOWLOCATION=>false,
CURLOPT_USERAGENT=>'Bratonien-Tools-NC-WebDAV/'.(function_exists('bratonien_tools_current_version') ? bratonien_tools_current_version() : 'dev'),
));
$body = curl_exec($ch);
@@ -160,14 +111,8 @@ function bratonien_tools_nc_connector_piwigo_api_request($api_key_id, $api_key_s
$content_type = (string)curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
curl_close($ch);
if ($body === false || $errno !== 0)
{
throw new RuntimeException('Piwigo-API konnte nicht erreicht werden: '.$error);
}
if ($http_code < 200 || $http_code >= 300)
{
throw new RuntimeException('Piwigo-API antwortete mit HTTP '.$http_code.'.');
}
if ($body === false || $errno !== 0) throw new RuntimeException('Piwigo-API konnte nicht erreicht werden: '.$error);
if ($http_code < 200 || $http_code >= 300) throw new RuntimeException('Piwigo-API antwortete mit HTTP '.$http_code.'.');
$decoded = bratonien_tools_nc_connector_decode_api_response((string)$body, $content_type);
if (($decoded['stat'] ?? '') !== 'ok')
@@ -175,71 +120,63 @@ function bratonien_tools_nc_connector_piwigo_api_request($api_key_id, $api_key_s
$message = (string)($decoded['message'] ?? $decoded['err'] ?? 'API-Aufruf wurde abgelehnt.');
throw new RuntimeException($message);
}
return bratonien_tools_nc_connector_api_payload($decoded);
}
function bratonien_tools_nc_connector_piwigo_api_test()
function bratonien_tools_nc_connector_validate_fallback_credentials($username, $password)
{
$api_key_id = trim((string)($_POST['nc_piwigo_api_key_id'] ?? ''));
$api_key_secret = trim((string)($_POST['nc_piwigo_api_key_secret'] ?? ''));
if ($api_key_id === '')
if (!function_exists('curl_init')) throw new RuntimeException('cURL ist in PHP nicht verfügbar. Der Piwigo-Fallback kann nicht geprüft werden.');
$username = trim((string)$username);
$password = (string)$password;
if ($username === '' || $password === '') throw new RuntimeException('Piwigo-Benutzername und Passwort müssen angegeben werden.');
$cookie_file = tempnam(sys_get_temp_dir(), 'br-pwg-auth-');
if ($cookie_file === false) throw new RuntimeException('Temporäre Piwigo-Sitzung konnte nicht angelegt werden.');
try
{
throw new RuntimeException('Piwigo-API-Schluessel-ID fehlt.');
$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-WebDAV/'.(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 geprüft werden: '.$error);
if ($http < 200 || $http >= 300) throw new RuntimeException('Piwigo-Fallback-Prüfung 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, gehört aber keinem Administrator/Webmaster.');
return array('username'=>(string)($status['username'] ?? $username),'status'=>$role);
}
if ($api_key_secret === '')
finally
{
throw new RuntimeException('Piwigo-API-Geheimnis fehlt.');
@unlink($cookie_file);
}
$status = bratonien_tools_nc_connector_piwigo_api_request($api_key_id, $api_key_secret, 'pwg.session.getStatus');
if (!is_array($status))
{
throw new RuntimeException('Piwigo hat keinen auswertbaren Benutzerstatus geliefert.');
}
$username = (string)($status['username'] ?? $status['user'] ?? '');
$user_status = strtolower((string)($status['status'] ?? ''));
$is_admin = in_array($user_status, array('admin', 'webmaster'), true);
if (!$is_admin)
{
throw new RuntimeException('Der API-Key funktioniert, gehoert aber keinem Piwigo-Administrator/Webmaster. Er wurde nicht gespeichert.');
}
$method_result = bratonien_tools_nc_connector_piwigo_api_request($api_key_id, $api_key_secret, 'reflection.getMethodList');
$method_map = array();
bratonien_tools_nc_connector_collect_method_names($method_result, $method_map);
$methods = array_keys($method_map);
sort($methods, SORT_STRING);
$required_methods = array('bratonien.nc.syncProductive', 'bratonien.nc.syncOrphans');
$missing = array_values(array_diff($required_methods, $methods));
if ($missing)
{
throw new RuntimeException('Der API-Key ist gueltig, aber die benoetigten Bratonien-Sync-Methoden fehlen: '.implode(', ', $missing).'.');
}
bratonien_tools_nc_api_credentials_store($api_key_id, $api_key_secret);
$sync_candidates = array_values(array_filter($methods, function($method)
{
return preg_match('/sync|synchron|site/i', (string)$method) === 1;
}));
$result = array(
'ok' => true,
'username' => $username !== '' ? $username : 'nicht gemeldet',
'status' => $user_status !== '' ? $user_status : 'nicht gemeldet',
'admin' => true,
'method_count' => count($methods),
'sync_candidates' => $sync_candidates,
'sync_api_detected' => true,
'stored' => true,
'conclusion' => 'Der API-Key ist als bevorzugter Connector-Zugang gespeichert. Produktive API-Synchronisierung bleibt auf die im Plugin freigegebene Piwigo-Version begrenzt; bei einer nicht freigegebenen Version greift nur der konfigurierte Benutzername/Passwort-Fallback.',
);
return array(
'message' => 'Piwigo-API-Key wurde geprueft und verschluesselt als bevorzugter Connector-Zugang gespeichert.',
'nc_piwigo_api_test' => $result,
);
}

View File

@@ -4,40 +4,100 @@ if (!defined('PHPWG_ROOT_PATH'))
die('Hacking attempt!');
}
function bratonien_tools_nc_connector_systemctl_value(array $args)
function bratonien_tools_nc_connector_command_run(array $command)
{
$result = array('exit'=>-1, 'stdout'=>'', 'stderr'=>'');
if (!function_exists('proc_open'))
{
return '';
$result['stderr'] = 'proc_open ist in PHP nicht verfügbar.';
return $result;
}
$command = array_merge(array('/usr/bin/systemctl'), $args);
$spec = array(
0 => array('file', '/dev/null', 'r'),
1 => array('pipe', 'w'),
2 => array('pipe', 'w'),
0=>array('file','/dev/null','r'),
1=>array('pipe','w'),
2=>array('pipe','w'),
);
$environment = array_merge($_ENV, array('LC_ALL'=>'C', 'LANG'=>'C'));
$environment = array_merge($_ENV, array('LC_ALL'=>'C','LANG'=>'C'));
$process = @proc_open($command, $spec, $pipes, null, $environment);
if (!is_resource($process))
{
return '';
$result['stderr'] = 'Prozess konnte nicht gestartet werden.';
return $result;
}
$stdout = stream_get_contents($pipes[1]);
stream_get_contents($pipes[2]);
$result['stdout'] = trim((string)stream_get_contents($pipes[1]));
$result['stderr'] = trim((string)stream_get_contents($pipes[2]));
fclose($pipes[1]);
fclose($pipes[2]);
$exit = proc_close($process);
return $exit === 0 ? trim((string)$stdout) : '';
$result['exit'] = (int)proc_close($process);
return $result;
}
function bratonien_tools_nc_connector_systemctl_run(array $args)
{
return bratonien_tools_nc_connector_command_run(array_merge(array('/usr/bin/systemctl'), $args));
}
function bratonien_tools_nc_connector_systemctl_value(array $args)
{
$result = bratonien_tools_nc_connector_systemctl_run($args);
return $result['exit'] === 0 ? $result['stdout'] : '';
}
function bratonien_tools_nc_connector_run_now()
{
$service = 'bratonien-nc-connector.service';
$load_state = bratonien_tools_nc_connector_systemctl_value(array('show',$service,'--property=LoadState','--value'));
if ($load_state !== 'loaded')
{
throw new RuntimeException('WebDAV-Abgleich konnte nicht gestartet werden: der privilegierte Connector-Dienst '.$service.' ist nicht geladen.');
}
// Der Connector verwaltet bewusst geschützte Runtime-Daten unter /etc und
// /var/lib. Er darf deshalb niemals direkt als Webserver-Benutzer laufen.
// Der manuelle Admin-Button startet denselben privilegierten systemd-Dienst,
// den auch der Timer verwendet.
$result = bratonien_tools_nc_connector_systemctl_run(array('start',$service));
// Auf Installationen ohne passende polkit-Regel darf ausschließlich die
// eng begrenzte, vom Betreiber eingerichtete sudo-Freigabe für genau diesen
// systemd-Dienst verwendet werden. Es gibt absichtlich keinen Fallback auf
// runtime/run-all.sh als www-data.
if ($result['exit'] !== 0 && is_file('/usr/bin/sudo') && is_executable('/usr/bin/sudo'))
{
$result = bratonien_tools_nc_connector_command_run(array(
'/usr/bin/sudo',
'-n',
'/usr/bin/systemctl',
'start',
$service,
));
}
if ($result['exit'] !== 0)
{
$detail = $result['stderr'] !== '' ? $result['stderr'] : $result['stdout'];
if ($detail === '') $detail = 'Exit-Code '.$result['exit'];
throw new RuntimeException(
'WebDAV-Abgleich konnte den privilegierten Connector-Dienst nicht starten. '
.'Der Connector wird aus Sicherheitsgründen nicht als Webserver-Benutzer direkt ausgeführt. '.$detail
);
}
$service_result = bratonien_tools_nc_connector_systemctl_value(array('show',$service,'--property=Result','--value'));
if ($service_result !== '' && $service_result !== 'success')
{
throw new RuntimeException('WebDAV-Abgleich wurde gestartet, der Connector-Dienst endete aber mit Ergebnis '.$service_result.'.');
}
return array('message'=>'WebDAV-Abgleich wurde über den privilegierten Connector-Dienst ausgeführt.');
}
function bratonien_tools_nc_connector_parse_systemd_time($value)
{
$value = trim((string)$value);
if ($value === '' || strtolower($value) === 'n/a')
{
return 0;
}
if ($value === '' || strtolower($value) === 'n/a') return 0;
$parsed = strtotime($value);
return $parsed === false ? 0 : (int)$parsed;
}
@@ -45,106 +105,52 @@ function bratonien_tools_nc_connector_parse_systemd_time($value)
function bratonien_tools_nc_connector_monotonic_to_timestamp($value)
{
$value = trim((string)$value);
if ($value === '' || $value === '0' || strtolower($value) === 'n/a')
{
return 0;
}
if (preg_match('/^([0-9]+)(?:us)?$/', $value, $matches))
{
$next_boot_seconds = ((float)$matches[1]) / 1000000;
}
else
{
return 0;
}
if ($value === '' || $value === '0' || strtolower($value) === 'n/a') return 0;
if (!preg_match('/^([0-9]+)(?:us)?$/', $value, $matches)) return 0;
$next_boot_seconds = ((float)$matches[1]) / 1000000;
$uptime_raw = @file_get_contents('/proc/uptime');
if (!is_string($uptime_raw) || !preg_match('/^([0-9]+(?:\.[0-9]+)?)/', trim($uptime_raw), $uptime_match))
{
return 0;
}
if (!is_string($uptime_raw) || !preg_match('/^([0-9]+(?:\.[0-9]+)?)/', trim($uptime_raw), $uptime_match)) return 0;
$remaining = $next_boot_seconds - (float)$uptime_match[1];
if ($remaining < -1)
{
return 0;
}
if ($remaining < -1) return 0;
return (int)round(time() + max(0, $remaining));
}
function bratonien_tools_nc_connector_next_from_timer_list($timer)
{
$line = bratonien_tools_nc_connector_systemctl_value(array(
'list-timers', '--all', '--no-pager', '--no-legend', $timer,
));
if ($line === '')
{
return 0;
}
$line = bratonien_tools_nc_connector_systemctl_value(array('list-timers','--all','--no-pager','--no-legend',$timer));
if ($line === '') return 0;
$first_line = trim((string)strtok($line, "\n"));
if (preg_match('/^(\S+\s+\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2}\s+\S+)/', $first_line, $matches))
{
$parsed = strtotime($matches[1]);
return $parsed === false ? 0 : (int)$parsed;
}
return 0;
if (!preg_match('/^(\S+\s+\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2}\s+\S+)/', $first_line, $matches)) return 0;
$parsed = strtotime($matches[1]);
return $parsed === false ? 0 : (int)$parsed;
}
function bratonien_tools_nc_connector_connection_last_status(array $connection)
{
$empty = array(
'timestamp'=>0,
'label'=>'Nicht verfügbar',
'state'=>'',
'message'=>'',
'auth_mode'=>'',
'api_state'=>'',
'api_message'=>'',
'fallback_state'=>'',
'fallback_message'=>'',
'error_detail'=>'',
'timestamp'=>0,'label'=>'Nicht verfügbar','state'=>'','message'=>'','auth_mode'=>'',
'api_state'=>'','api_message'=>'','fallback_state'=>'','fallback_message'=>'','error_detail'=>'',
);
$connection_id = (int)($connection['id'] ?? 0);
$candidates = array();
if ($connection_id > 0)
{
$candidates[] = rtrim(PHPWG_ROOT_PATH, '/').'/_data/bratonien-tools/nc-connector-status/connection-'.$connection_id.'.json';
}
if ($connection_id > 0) $candidates[] = rtrim(PHPWG_ROOT_PATH, '/').'/_data/bratonien-tools/nc-connector-status/connection-'.$connection_id.'.json';
$config = isset($connection['config']) && is_array($connection['config']) ? $connection['config'] : array();
$state_dir = rtrim((string)($config['state_dir'] ?? ''), '/');
if ($state_dir === '' && $connection_id > 0)
{
$state_dir = '/var/lib/bratonien-tools/nc-connector/connection-'.$connection_id;
}
if ($state_dir !== '')
{
$candidates[] = $state_dir.'/connector-status.json';
}
if ($state_dir === '' && $connection_id > 0) $state_dir = '/var/lib/bratonien-tools/nc-connector/connection-'.$connection_id;
if ($state_dir !== '') $candidates[] = $state_dir.'/connector-status.json';
$decoded = null;
foreach ($candidates as $candidate)
{
if (!is_readable($candidate))
{
continue;
}
if (!is_readable($candidate)) continue;
$value = json_decode((string)@file_get_contents($candidate), true);
if (is_array($value))
{
$decoded = $value;
break;
}
}
if (!is_array($decoded))
{
return $empty;
if (is_array($value)) { $decoded = $value; break; }
}
if (!is_array($decoded)) return $empty;
$timestamp = (int)($decoded['timestamp'] ?? 0);
$api = isset($decoded['api']) && is_array($decoded['api']) ? $decoded['api'] : array();
@@ -166,73 +172,63 @@ function bratonien_tools_nc_connector_connection_last_status(array $connection)
function bratonien_tools_nc_connector_last_status(array $connections)
{
$latest = array('timestamp'=>0, 'state'=>'', 'message'=>'', 'auth_mode'=>'', 'api_state'=>'', 'api_message'=>'', 'fallback_state'=>'', 'fallback_message'=>'', 'error_detail'=>'');
$latest = array('timestamp'=>0,'state'=>'','message'=>'','auth_mode'=>'','api_state'=>'','api_message'=>'','fallback_state'=>'','fallback_message'=>'','error_detail'=>'');
foreach ($connections as $connection)
{
if (empty($connection['enabled']) || (string)($connection['takeover_state'] ?? '') !== 'active')
{
continue;
}
$status = bratonien_tools_nc_connector_connection_last_status($connection);
if ((int)$status['timestamp'] >= (int)$latest['timestamp'])
{
$latest = $status;
}
if ((int)$status['timestamp'] >= (int)$latest['timestamp']) $latest = $status;
}
return $latest;
}
function bratonien_tools_nc_connector_status_message(array $last)
{
if ((string)($last['state'] ?? '') === 'ok')
{
return 'WebDAV eingelesen und Piwigo synchronisiert';
}
return (string)($last['message'] ?? '');
}
function bratonien_tools_nc_connector_system_status(array $connections = array())
{
$timer = 'bratonien-nc-connector.timer';
$service = 'bratonien-nc-connector.service';
$next_realtime_raw = bratonien_tools_nc_connector_systemctl_value(array('show', $timer, '--property=NextElapseUSecRealtime', '--value'));
$next_realtime_raw = bratonien_tools_nc_connector_systemctl_value(array('show',$timer,'--property=NextElapseUSecRealtime','--value'));
$next_timestamp = bratonien_tools_nc_connector_parse_systemd_time($next_realtime_raw);
if ($next_timestamp <= 0)
{
$next_monotonic_raw = bratonien_tools_nc_connector_systemctl_value(array('show', $timer, '--property=NextElapseUSecMonotonic', '--value'));
$next_monotonic_raw = bratonien_tools_nc_connector_systemctl_value(array('show',$timer,'--property=NextElapseUSecMonotonic','--value'));
$next_timestamp = bratonien_tools_nc_connector_monotonic_to_timestamp($next_monotonic_raw);
}
if ($next_timestamp <= 0) $next_timestamp = bratonien_tools_nc_connector_next_from_timer_list($timer);
if ($next_timestamp <= 0)
{
$next_timestamp = bratonien_tools_nc_connector_next_from_timer_list($timer);
}
$active = bratonien_tools_nc_connector_systemctl_value(array('is-active', $timer));
$enabled = bratonien_tools_nc_connector_systemctl_value(array('is-enabled', $timer));
$active = bratonien_tools_nc_connector_systemctl_value(array('is-active',$timer));
$enabled = bratonien_tools_nc_connector_systemctl_value(array('is-enabled',$timer));
$last = bratonien_tools_nc_connector_last_status($connections);
if ($last['timestamp'] <= 0)
{
$last_raw = bratonien_tools_nc_connector_systemctl_value(array('show', $service, '--property=ExecMainExitTimestamp', '--value'));
$last_raw = bratonien_tools_nc_connector_systemctl_value(array('show',$service,'--property=ExecMainExitTimestamp','--value'));
$last['timestamp'] = bratonien_tools_nc_connector_parse_systemd_time($last_raw);
}
return array(
'timer_name' => $timer,
'timer_active' => $active === 'active',
'timer_enabled' => $enabled === 'enabled',
'last_run_timestamp' => (int)$last['timestamp'],
'last_run_label' => $last['timestamp'] > 0 ? date('d.m.Y H:i:s', (int)$last['timestamp']) : 'Nicht verfügbar',
'last_run_state' => (string)$last['state'],
'last_run_message' => (string)$last['message'],
'last_run_auth_mode' => (string)$last['auth_mode'],
'last_run_api_state' => (string)$last['api_state'],
'last_run_api_message' => (string)$last['api_message'],
'last_run_fallback_state' => (string)$last['fallback_state'],
'last_run_fallback_message' => (string)$last['fallback_message'],
'last_run_error_detail' => (string)$last['error_detail'],
'next_run_timestamp' => $next_timestamp,
'next_run_label' => $next_timestamp > 0 ? date('d.m.Y H:i:s', $next_timestamp) : 'Nicht verfügbar',
'legacy_runtime_exists' => is_dir('/opt/piwigo-sync'),
'legacy_config_exists' => is_dir('/etc/piwigo-sync'),
'legacy_service_exists' => is_file('/etc/systemd/system/piwigo-sync.service'),
'legacy_timer_exists' => is_file('/etc/systemd/system/piwigo-sync.timer'),
'timer_name'=>$timer,
'timer_active'=>$active === 'active',
'timer_enabled'=>$enabled === 'enabled',
'last_run_timestamp'=>(int)$last['timestamp'],
'last_run_label'=>$last['timestamp'] > 0 ? date('d.m.Y H:i:s', (int)$last['timestamp']) : 'Nicht verfügbar',
'last_run_state'=>(string)$last['state'],
'last_run_message'=>bratonien_tools_nc_connector_status_message($last),
'last_run_auth_mode'=>(string)$last['auth_mode'],
'last_run_api_state'=>(string)$last['api_state'],
'last_run_api_message'=>(string)$last['api_message'],
'last_run_fallback_state'=>(string)$last['fallback_state'],
'last_run_fallback_message'=>(string)$last['fallback_message'],
'last_run_error_detail'=>(string)$last['error_detail'],
'next_run_timestamp'=>$next_timestamp,
'next_run_label'=>$next_timestamp > 0 ? date('d.m.Y H:i:s', $next_timestamp) : 'Nicht verfügbar',
);
}

View File

@@ -1,135 +0,0 @@
<?php
if (!defined('PHPWG_ROOT_PATH'))
{
die('Hacking attempt!');
}
/**
* Controlled handover preparation for verified NC Connector connections.
*
* This phase intentionally does not stop, disable or modify the legacy
* piwigo-sync service. It only marks a verified Connector connection as ready
* for a later controlled takeover. The marker can be rolled back at any time.
*/
function bratonien_tools_nc_connector_ensure_takeover_state()
{
bratonien_tools_nc_connector_ensure_table();
$table = bratonien_tools_nc_connector_table();
pwg_query("ALTER TABLE `$table` MODIFY takeover_state enum('imported','verified','ready','active','disabled') NOT NULL DEFAULT 'imported'");
}
function bratonien_tools_nc_connector_prepare_takeover()
{
$id = isset($_POST['connection_id']) ? (int)$_POST['connection_id'] : 0;
$connection = bratonien_tools_nc_connector_connection($id, false);
if (!$connection)
{
throw new RuntimeException('Connector-Verbindung wurde nicht gefunden.');
}
if ($connection['takeover_state'] !== 'verified')
{
throw new RuntimeException('Nur eine erfolgreich verifizierte Verbindung kann fuer die Uebergabe vorbereitet werden.');
}
$config = $connection['config'];
$verification = isset($config['verification']) && is_array($config['verification'])
? $config['verification']
: array();
if (empty($verification['ok']))
{
throw new RuntimeException('Die gespeicherte Verifikation ist nicht erfolgreich. Bitte die Verbindung erneut pruefen.');
}
$config['takeover'] = array(
'prepared_at' => date('Y-m-d H:i:s'),
'legacy_sync_untouched' => true,
'connector_enabled' => false,
'first_run' => array(
'status' => 'pending',
'finished_at' => null,
'detail' => '',
),
);
$config_json = json_encode($config, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
if (!is_string($config_json))
{
throw new RuntimeException('Uebergabestatus konnte nicht gespeichert werden.');
}
bratonien_tools_nc_connector_ensure_takeover_state();
$table = bratonien_tools_nc_connector_table();
$now = date('Y-m-d H:i:s');
pwg_query("UPDATE `$table` SET
takeover_state = 'ready',
enabled = 0,
config_json = '".pwg_db_real_escape_string($config_json)."',
updated = '".pwg_db_real_escape_string($now)."'
WHERE id = ".(int)$connection['id']);
return array(
'message' => 'Die verifizierte Nextcloud-Verbindung ist jetzt fuer die kontrollierte Uebergabe vorbereitet. Der Connector wurde noch nicht aktiviert und der Legacy-Sync bleibt unveraendert Produktionsverbindung.',
);
}
function bratonien_tools_nc_connector_cancel_takeover()
{
$id = isset($_POST['connection_id']) ? (int)$_POST['connection_id'] : 0;
$connection = bratonien_tools_nc_connector_connection($id, false);
if (!$connection)
{
throw new RuntimeException('Connector-Verbindung wurde nicht gefunden.');
}
if ($connection['takeover_state'] !== 'ready')
{
throw new RuntimeException('Diese Verbindung befindet sich nicht in der Uebergabevorbereitung.');
}
$config = $connection['config'];
if (isset($config['takeover']))
{
unset($config['takeover']);
}
$config_json = json_encode($config, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
if (!is_string($config_json))
{
throw new RuntimeException('Uebergabestatus konnte nicht zurueckgesetzt werden.');
}
bratonien_tools_nc_connector_ensure_takeover_state();
$table = bratonien_tools_nc_connector_table();
$now = date('Y-m-d H:i:s');
pwg_query("UPDATE `$table` SET
takeover_state = 'verified',
enabled = 0,
config_json = '".pwg_db_real_escape_string($config_json)."',
updated = '".pwg_db_real_escape_string($now)."'
WHERE id = ".(int)$connection['id']);
return array(
'message' => 'Die Uebergabevorbereitung wurde zurueckgenommen. Die Verbindung bleibt verifiziert und deaktiviert; der Legacy-Sync bleibt unveraendert aktiv.',
);
}
/**
* Normalize the outcome of a Connector sync run during takeover.
*
* Both "changed" and "no_changes" are successful results. Only "error"
* represents a failed run and may trigger rollback of a controlled handover.
*/
function bratonien_tools_nc_connector_takeover_result($status, $detail = '')
{
$status = trim((string)$status);
if (!in_array($status, array('changed', 'no_changes', 'error'), true))
{
throw new RuntimeException('Unbekannter Connector-Laufstatus: '.$status);
}
return array(
'status' => $status,
'success' => $status !== 'error',
'changed' => $status === 'changed',
'finished_at' => date('Y-m-d H:i:s'),
'detail' => (string)$detail,
);
}

View File

@@ -0,0 +1,121 @@
<?php
if (!defined('PHPWG_ROOT_PATH'))
{
die('Hacking attempt!');
}
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 die WebDAV-Verbindung 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 !== '';
$config = array(
'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'=>'',
'piwigo_auth'=>'connection-scoped',
'api_enabled'=>$api_enabled,
);
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,
'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.');
$config_json = json_encode($config, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
if (!is_string($config_json)) throw new RuntimeException('WebDAV-Konfiguration konnte nicht serialisiert werden.');
bratonien_tools_nc_connector_ensure_table();
$table = bratonien_tools_nc_connector_table();
$now = date('Y-m-d H:i:s');
$connection_key = 'webdav-'.bin2hex(random_bytes(12));
$secret_blob = bratonien_tools_nc_connector_encrypt_secret($secret_payload);
pwg_query("INSERT INTO `$table` (connection_key,name,adapter,enabled,config_json,secret_blob,created,updated) VALUES ('"
.pwg_db_real_escape_string($connection_key)."','"
.pwg_db_real_escape_string($name)."','remote',1,'"
.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.');
$config['state_dir'] = '/var/lib/bratonien-tools/nc-connector/connection-'.$id;
$config['status_file'] = $config['state_dir'].'/connector-status.json';
$config_json = json_encode($config, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
if (!is_string($config_json))
{
pwg_query("DELETE FROM `$table` WHERE id=".$id." LIMIT 1");
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");
return array(
'connection_id'=>$id,
'message'=>'WebDAV-Verbindung wurde angelegt.',
);
}

View File

@@ -0,0 +1,219 @@
<?php
if (!defined('PHPWG_ROOT_PATH'))
{
die('Hacking attempt!');
}
function bratonien_tools_nc_wizard_state()
{
$state = isset($_SESSION['bratonien_nc_wizard']) && is_array($_SESSION['bratonien_nc_wizard']) ? $_SESSION['bratonien_nc_wizard'] : array();
return array_merge(array(
'step'=>1,
'scan_ok'=>false,
'base_url'=>'',
'host_input'=>'',
'username'=>'',
'display_name'=>'',
'version'=>'',
'product'=>'Nextcloud',
'connection_name'=>'',
'scan_message'=>'',
'source_mode'=>'webdav-placeholder',
'transport'=>'webdav',
'gallery_root'=>'',
'roots'=>array(),
'technical_stage'=>'mounts',
'technical_source'=>'WebDAV',
'technical_error'=>'',
'technical_complete'=>false,
'directory_selection_ready'=>false,
'directory_path'=>'',
'directory_parent'=>'',
'directory_children'=>array(),
'directory_current_fileid'=>0,
'directory_fileids'=>array(),
'directory_selected'=>array(),
'directory_selected_fileids'=>array(),
'api_status'=>'pending',
'api_username'=>'',
'api_error'=>'',
'_password'=>'',
'_api_key_id'=>'',
'_api_key_secret'=>'',
'_fallback_user'=>'',
'_fallback_password'=>'',
), $state);
}
function bratonien_tools_nc_wizard_store(array $state)
{
$_SESSION['bratonien_nc_wizard'] = $state;
}
function bratonien_tools_nc_wizard_reset()
{
unset($_SESSION['bratonien_nc_wizard']);
return array('message'=>'Verbindungsassistent wurde zurückgesetzt.');
}
function bratonien_tools_nc_wizard_normalize_url($host)
{
$host = trim((string)$host);
if ($host === '') throw new RuntimeException('Nextcloud-Adresse fehlt.');
if (!preg_match('#^https?://#i', $host)) $host = 'https://'.$host;
$parts = parse_url($host);
if (!is_array($parts) || empty($parts['host'])) throw new RuntimeException('Die Nextcloud-Adresse ist ungültig.');
$scheme = strtolower((string)($parts['scheme'] ?? 'https'));
if (!in_array($scheme, array('http','https'), true)) throw new RuntimeException('Nextcloud muss per HTTP oder HTTPS erreichbar sein.');
$url = $scheme.'://'.$parts['host'];
if (!empty($parts['port'])) $url .= ':'.(int)$parts['port'];
if (!empty($parts['path']) && $parts['path'] !== '/') $url .= '/'.trim($parts['path'], '/');
return rtrim($url, '/');
}
function bratonien_tools_nc_wizard_candidate_urls($host)
{
$host = trim((string)$host);
if ($host === '') throw new RuntimeException('Bitte die Adresse der Nextcloud angeben.');
if (preg_match('#^https?://#i', $host)) return array(bratonien_tools_nc_wizard_normalize_url($host));
return array(
bratonien_tools_nc_wizard_normalize_url('https://'.$host),
bratonien_tools_nc_wizard_normalize_url('http://'.$host),
);
}
function bratonien_tools_nc_wizard_http($url, $username = '', $password = '', array $headers = array())
{
if (!function_exists('curl_init')) throw new RuntimeException('Der Server kann Nextcloud derzeit nicht per HTTP prüfen.');
$ch = curl_init($url);
$options = array(
CURLOPT_RETURNTRANSFER=>true,
CURLOPT_FOLLOWLOCATION=>true,
CURLOPT_MAXREDIRS=>3,
CURLOPT_CONNECTTIMEOUT=>8,
CURLOPT_TIMEOUT=>15,
CURLOPT_HTTPHEADER=>array_merge(array('Accept: application/json'), $headers),
CURLOPT_USERAGENT=>'Bratonien-Tools-NC-WebDAV/'.(function_exists('bratonien_tools_current_version') ? bratonien_tools_current_version() : 'dev'),
);
if ($username !== '')
{
$options[CURLOPT_HTTPAUTH] = CURLAUTH_BASIC;
$options[CURLOPT_USERPWD] = $username.':'.$password;
}
curl_setopt_array($ch, $options);
$body = curl_exec($ch);
$errno = curl_errno($ch);
$status = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($body === false || $errno !== 0) throw new RuntimeException('Verbindung fehlgeschlagen.');
return array('status'=>$status, 'body'=>(string)$body);
}
function bratonien_tools_nc_wizard_ocs_data($body)
{
$decoded = json_decode((string)$body, true);
if (!is_array($decoded) || !isset($decoded['ocs']) || !is_array($decoded['ocs'])) throw new RuntimeException('Nextcloud hat keine gültige Antwort geliefert.');
$meta = isset($decoded['ocs']['meta']) && is_array($decoded['ocs']['meta']) ? $decoded['ocs']['meta'] : array();
$status = strtolower(trim((string)($meta['status'] ?? '')));
$status_code = isset($meta['statuscode']) ? (int)$meta['statuscode'] : 0;
if ($status !== 'ok' && !in_array($status_code, array(100,200), true))
{
$message = trim((string)($meta['message'] ?? ''));
if ($message === '' || strtolower($message) === 'ok') $message = 'Nextcloud hat die Anfrage abgelehnt.';
throw new RuntimeException($message);
}
return isset($decoded['ocs']['data']) && is_array($decoded['ocs']['data']) ? $decoded['ocs']['data'] : array();
}
function bratonien_tools_nc_wizard_api_test()
{
$state = bratonien_tools_nc_wizard_state();
if ((int)$state['step'] !== 3) throw new RuntimeException('Der API-Test ist in diesem Assistentenschritt nicht verfügbar.');
$posted_id = trim((string)($_POST['nc_wizard_api_key_id'] ?? ''));
$posted_secret = trim((string)($_POST['nc_wizard_api_key_secret'] ?? ''));
if ($posted_id !== '') $state['_api_key_id'] = $posted_id;
if ($posted_secret !== '') $state['_api_key_secret'] = $posted_secret;
bratonien_tools_nc_wizard_store($state);
$key_id = trim((string)$state['_api_key_id']);
$secret = trim((string)$state['_api_key_secret']);
if ($key_id === '' || $secret === '') throw new RuntimeException('API-Schlüssel-ID und API-Geheimnis fehlen.');
try
{
$status = bratonien_tools_nc_connector_piwigo_api_request($key_id, $secret, 'pwg.session.getStatus');
$user_status = strtolower((string)($status['status'] ?? ''));
if (!in_array($user_status, array('admin','webmaster'), true)) throw new RuntimeException('Der API-Key gehört keinem Piwigo-Administrator/Webmaster.');
$method_result = bratonien_tools_nc_connector_piwigo_api_request($key_id, $secret, 'reflection.getMethodList');
$method_map = array();
bratonien_tools_nc_connector_collect_method_names($method_result, $method_map);
$missing = array_values(array_diff(array('bratonien.nc.syncProductive','bratonien.nc.syncOrphans'), array_keys($method_map)));
if ($missing) throw new RuntimeException('Benötigte Bratonien-Sync-Methoden fehlen: '.implode(', ', $missing).'.');
$state['_api_key_id'] = $key_id;
$state['_api_key_secret'] = $secret;
$state['api_status'] = 'ok';
$state['api_username'] = (string)($status['username'] ?? $status['user'] ?? '');
$state['api_error'] = '';
$state['step'] = 4;
bratonien_tools_nc_wizard_store($state);
return array('message'=>'Piwigo-API erfolgreich geprüft. Gespeichert wird sie erst beim Abschluss des Assistenten.');
}
catch (Throwable $e)
{
$state['api_status'] = 'error';
$state['api_error'] = $e->getMessage();
bratonien_tools_nc_wizard_store($state);
throw $e;
}
}
function bratonien_tools_nc_wizard_api_skip()
{
$state = bratonien_tools_nc_wizard_state();
if ((int)$state['step'] !== 3) throw new RuntimeException('Die API kann in diesem Assistentenschritt nicht übersprungen werden.');
$state['api_status'] = 'skipped';
$state['api_error'] = '';
$state['step'] = 4;
bratonien_tools_nc_wizard_store($state);
return array('message'=>'Piwigo-API wurde übersprungen. Für diese Verbindung ist deshalb ein Fallback-Zugang erforderlich.');
}
function bratonien_tools_nc_connector_update_name()
{
$id = (int)($_POST['connection_id'] ?? 0);
$name = trim((string)($_POST['connection_name'] ?? ''));
if ($id < 1 || $name === '') throw new RuntimeException('Verbindung oder Name fehlt.');
$connection = bratonien_tools_nc_connector_connection($id, false);
if (!$connection) throw new RuntimeException('Connector-Verbindung wurde nicht gefunden.');
if ((string)($connection['adapter'] ?? '') !== 'remote' || (string)($connection['config']['source_mode'] ?? '') !== 'webdav-placeholder')
{
throw new RuntimeException('Es können nur WebDAV-Verbindungen bearbeitet werden.');
}
$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)."', updated='".pwg_db_real_escape_string($now)."' WHERE id=".$id." LIMIT 1");
return array('message'=>'Verbindungsname wurde aktualisiert.');
}

View File

@@ -0,0 +1,199 @@
<?php
if (!defined('PHPWG_ROOT_PATH'))
{
die('Hacking attempt!');
}
function bratonien_tools_nc_wizard_webdav_list(array $state, $path = '')
{
if (empty($state['scan_ok']) || trim((string)$state['base_url']) === '' || trim((string)$state['username']) === '' || (string)$state['_password'] === '')
{
throw new RuntimeException('Die Nextcloud-Sitzung des Assistenten ist nicht vollständig.');
}
if (!function_exists('curl_init')) throw new RuntimeException('cURL ist für die Verzeichnisauswahl nicht verfügbar.');
$path = trim((string)$path, '/');
if ($path !== '' && preg_match('#(^|/)\.\.(/|$)#', $path)) throw new RuntimeException('Ungültiger Verzeichnispfad.');
$segments = $path === '' ? array() : array_map('rawurlencode', explode('/', $path));
$user = rawurlencode((string)$state['username']);
$url = rtrim((string)$state['base_url'], '/').'/remote.php/dav/files/'.$user.'/'.implode('/', $segments);
if (substr($url, -1) !== '/') $url .= '/';
$body = '<?xml version="1.0"?><d:propfind xmlns:d="DAV:" xmlns:oc="http://owncloud.org/ns"><d:prop><d:resourcetype/><d:displayname/><oc:fileid/></d:prop></d:propfind>';
$ch = curl_init($url);
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER=>true,
CURLOPT_CUSTOMREQUEST=>'PROPFIND',
CURLOPT_POSTFIELDS=>$body,
CURLOPT_HTTPHEADER=>array('Depth: 1','Content-Type: application/xml; charset=utf-8'),
CURLOPT_HTTPAUTH=>CURLAUTH_BASIC,
CURLOPT_USERPWD=>(string)$state['username'].':'.(string)$state['_password'],
CURLOPT_CONNECTTIMEOUT=>8,
CURLOPT_TIMEOUT=>20,
));
$response = curl_exec($ch);
$errno = curl_errno($ch);
$status = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($response === false || $errno !== 0) throw new RuntimeException('Nextcloud-Verzeichnisse konnten nicht geladen werden.');
if ($status === 401 || $status === 403) throw new RuntimeException('Nextcloud hat den Zugriff auf dieses Verzeichnis abgelehnt.');
if ($status !== 207) throw new RuntimeException('Nextcloud-Verzeichnisabfrage antwortete mit HTTP '.$status.'.');
libxml_use_internal_errors(true);
$xml = simplexml_load_string((string)$response);
if ($xml === false) throw new RuntimeException('Nextcloud hat eine ungültige WebDAV-Antwort geliefert.');
$xml->registerXPathNamespace('d', 'DAV:');
$xml->registerXPathNamespace('oc', 'http://owncloud.org/ns');
$children = array();
$fileids = array();
$current_fileid = 0;
$base_path = (string)parse_url($url, PHP_URL_PATH);
foreach ($xml->xpath('//d:response') as $item)
{
$item->registerXPathNamespace('d', 'DAV:');
$item->registerXPathNamespace('oc', 'http://owncloud.org/ns');
$hrefs = $item->xpath('d:href');
$collections = $item->xpath('d:propstat/d:prop/d:resourcetype/d:collection');
$ids = $item->xpath('d:propstat/d:prop/oc:fileid');
if (!$hrefs || !$collections || !$ids) continue;
$fileid = (int)trim((string)$ids[0]);
if ($fileid < 1) continue;
$href = rawurldecode((string)$hrefs[0]);
$href_path = (string)parse_url($href, PHP_URL_PATH);
if (rtrim($href_path, '/') === rtrim($base_path, '/'))
{
$current_fileid = $fileid;
continue;
}
$name = basename(rtrim($href_path, '/'));
if ($name === '') continue;
$child_path = $path === '' ? $name : $path.'/'.$name;
$children[$child_path] = $name;
$fileids[$child_path] = $fileid;
}
natcasesort($children);
if ($current_fileid < 1) throw new RuntimeException('Nextcloud hat für das aktuelle Verzeichnis keine eindeutige Datei-ID geliefert.');
$parent = '';
if ($path !== '')
{
$parts = explode('/', $path);
array_pop($parts);
$parent = implode('/', $parts);
}
return array(
'current'=>$path,
'parent'=>$parent,
'children'=>$children,
'current_fileid'=>$current_fileid,
'fileids'=>$fileids,
);
}
function bratonien_tools_nc_wizard_refresh_directory_state(array &$state, $path = null)
{
if ($path === null) $path = (string)($state['directory_path'] ?? '');
$listing = bratonien_tools_nc_wizard_webdav_list($state, $path);
$state['directory_path'] = (string)$listing['current'];
$state['directory_parent'] = (string)$listing['parent'];
$state['directory_children'] = (array)$listing['children'];
$state['directory_current_fileid'] = (int)$listing['current_fileid'];
$state['directory_fileids'] = (array)$listing['fileids'];
if (!isset($state['directory_selected']) || !is_array($state['directory_selected'])) $state['directory_selected'] = array();
if (!isset($state['directory_selected_fileids']) || !is_array($state['directory_selected_fileids'])) $state['directory_selected_fileids'] = array();
}
function bratonien_tools_nc_wizard_directory_browse()
{
$state = bratonien_tools_nc_wizard_state();
if ((int)$state['step'] !== 2 || (string)$state['technical_stage'] !== 'mounts' || empty($state['directory_selection_ready'])) throw new RuntimeException('Die Verzeichnisauswahl ist in diesem Fenster nicht verfügbar.');
$path = trim((string)($_POST['nc_wizard_directory_path'] ?? ''), '/');
bratonien_tools_nc_wizard_refresh_directory_state($state, $path);
bratonien_tools_nc_wizard_store($state);
return array('message'=>'Verzeichnis geöffnet.');
}
function bratonien_tools_nc_wizard_directory_add()
{
$state = bratonien_tools_nc_wizard_state();
if ((int)$state['step'] !== 2 || (string)$state['technical_stage'] !== 'mounts' || empty($state['directory_selection_ready'])) throw new RuntimeException('Die Verzeichnisauswahl ist in diesem Fenster nicht verfügbar.');
$path = trim((string)($state['directory_path'] ?? ''), '/');
$fileid = (int)($state['directory_current_fileid'] ?? 0);
if ($fileid < 1) throw new RuntimeException('Für dieses Verzeichnis fehlt die eindeutige Nextcloud-Datei-ID.');
$selected = isset($state['directory_selected']) && is_array($state['directory_selected']) ? $state['directory_selected'] : array();
if (!in_array($path, $selected, true)) $selected[] = $path;
$state['directory_selected'] = array_values($selected);
if (!isset($state['directory_selected_fileids']) || !is_array($state['directory_selected_fileids'])) $state['directory_selected_fileids'] = array();
$state['directory_selected_fileids'][$path] = $fileid;
bratonien_tools_nc_wizard_store($state);
return array('message'=>$path === '' ? 'Stammverzeichnis ausgewählt.' : 'Verzeichnis hinzugefügt.');
}
function bratonien_tools_nc_wizard_directory_remove()
{
$state = bratonien_tools_nc_wizard_state();
if ((int)$state['step'] !== 2 || empty($state['directory_selection_ready'])) throw new RuntimeException('Die Verzeichnisauswahl ist in diesem Fenster nicht verfügbar.');
$path = trim((string)($_POST['nc_wizard_directory_remove'] ?? ''), '/');
$selected = isset($state['directory_selected']) && is_array($state['directory_selected']) ? $state['directory_selected'] : array();
$state['directory_selected'] = array_values(array_filter($selected, function($value) use ($path) { return (string)$value !== $path; }));
if (isset($state['directory_selected_fileids'][$path])) unset($state['directory_selected_fileids'][$path]);
bratonien_tools_nc_wizard_store($state);
return array('message'=>'Verzeichnis entfernt.');
}
function bratonien_tools_nc_wizard_select_current_user()
{
$state = bratonien_tools_nc_wizard_state();
if (empty($state['scan_ok'])) throw new RuntimeException('Bitte zuerst Nextcloud erfolgreich scannen.');
if (empty($state['technical_complete'])) throw new RuntimeException('Die Verbindung ist noch nicht vollständig geprüft.');
$connection_name = trim((string)($_POST['nc_wizard_connection_name'] ?? $state['connection_name']));
if ($connection_name === '') throw new RuntimeException('Bitte einen Namen für die Verbindung angeben.');
$state['connection_name'] = $connection_name;
$state['step'] = 3;
$state['api_error'] = '';
bratonien_tools_nc_wizard_store($state);
return array('message'=>'Nextcloud-Benutzer übernommen. Jetzt folgt der Piwigo-API-Zugang.');
}
function bratonien_tools_nc_wizard_back()
{
$state = bratonien_tools_nc_wizard_state();
$step = (int)($state['step'] ?? 1);
if ($step <= 1) return array('message'=>'Bereits am Anfang des Assistenten.');
if ($step === 4)
{
$state['step'] = 3;
}
elseif ($step === 3)
{
$state['step'] = 2;
$state['technical_complete'] = true;
$state['technical_stage'] = 'ready';
$state['directory_selection_ready'] = false;
}
elseif (!empty($state['technical_complete']))
{
$state['technical_complete'] = false;
$state['technical_stage'] = 'mounts';
$state['directory_selection_ready'] = true;
bratonien_tools_nc_wizard_refresh_directory_state($state);
}
else
{
$state['step'] = 1;
$state['directory_selection_ready'] = false;
}
bratonien_tools_nc_wizard_store($state);
return array('message'=>'Ein Fenster zurück.');
}

View File

@@ -0,0 +1,200 @@
<?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'),
'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',
'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(),
'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')
{
throw new RuntimeException('Der Assistent unterstützt ausschließlich WebDAV-Verbindungen.');
}
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.');
}
function bratonien_tools_nc_wizard_finish_dispatch()
{
$state = bratonien_tools_nc_wizard_state();
if ((string)($state['source_mode'] ?? '') !== 'webdav-placeholder')
{
throw new RuntimeException('Der Assistent unterstützt ausschließlich WebDAV-Verbindungen.');
}
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;
}

View File

@@ -1,282 +0,0 @@
<?php
if (!defined('PHPWG_ROOT_PATH'))
{
die('Hacking attempt!');
}
/**
* Registers the connector-owned filesystem synchronization endpoint.
*
* Authentication and authorization are delegated to Piwigo's Web API.
* The method is administrator-only and POST-only so an API key inherits the
* permissions of its Piwigo user without storing that user's password.
*/
function bratonien_tools_register_ws_methods($arr)
{
$service = &$arr[0];
$service->addMethod(
'bratonien.nc.sync',
'bratonien_tools_ws_nc_sync',
array(
'site_id' => array(
'default' => 1,
'type' => WS_TYPE_ID,
'info' => 'Piwigo storage site to synchronize. Default: 1.',
),
'simulate' => array(
'default' => true,
'type' => WS_TYPE_BOOL,
'info' => 'Simulation only. Productive API synchronization is disabled until parity has been verified.',
),
),
'Simulates the local Piwigo filesystem synchronization used by the Bratonien NC Connector.',
null,
array(
'admin_only' => true,
'post_only' => true,
)
);
}
function bratonien_tools_ws_nc_sync_error(&$errors, $path, $type)
{
$errors[] = array(
'path' => (string)$path,
'type' => (string)$type,
);
}
/**
* Read-only parity test for Piwigo 16.4.0 admin/site_update.php with the
* connector's fixed settings:
* sync=files, privacy_level=0, sync_meta=1, subcats-included=1,
* no cat, no caddie, no meta_all, no meta_empty_overrides.
*
* The simulation deliberately performs no INSERT/UPDATE/DELETE and triggers
* no Piwigo activity/events. It only calculates what the matching core admin
* synchronization would attempt to change.
*/
function bratonien_tools_ws_nc_sync($params, &$service)
{
global $conf, $user, $logger;
if (empty($conf['enable_synchronization']))
{
return new PwgError(403, 'Piwigo filesystem synchronization is disabled.');
}
$piwigo_version = defined('PHPWG_VERSION') ? (string)PHPWG_VERSION : '';
if ($piwigo_version !== '16.4.0')
{
return new PwgError(
409,
'Bratonien API synchronization is not approved for Piwigo '.$piwigo_version.'. Use the administrator fallback until this Piwigo version has been verified.'
);
}
$simulate = !isset($params['simulate']) || (bool)$params['simulate'];
if (!$simulate)
{
return new PwgError(
409,
'Productive Bratonien API synchronization is not enabled yet. Run the simulation and verify parity with Piwigo admin synchronization first.'
);
}
$site_id = isset($params['site_id']) ? (int)$params['site_id'] : 1;
if ($site_id < 1)
{
return new PwgError(400, 'Invalid site_id.');
}
include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
include_once(PHPWG_ROOT_PATH.'admin/site_reader_local.php');
$query = '
SELECT galleries_url
FROM '.SITES_TABLE.'
WHERE id = '.$site_id.'
LIMIT 1';
$result = pwg_query($query);
if (!pwg_db_num_rows($result))
{
return new PwgError(404, 'Piwigo site does not exist.');
}
list($site_url) = pwg_db_fetch_row($result);
if (url_is_remote($site_url))
{
return new PwgError(400, 'Remote Piwigo sites are not supported by this synchronization method.');
}
$errors = array();
$site_reader = new LocalSiteReader($site_url);
if (!$site_reader->open())
{
return new PwgError(500, 'Piwigo could not open the configured local site.');
}
$counts = array(
'new_categories' => 0,
'del_categories' => 0,
'new_elements' => 0,
'del_elements' => 0,
'upd_elements' => 0,
'new_formats' => 0,
'del_formats' => 0,
'metadata_candidates' => 0,
);
// -------------------------------------------------------------------
// Directories / physical categories
// -------------------------------------------------------------------
$query = '
SELECT id, uppercats, global_rank, status, visible
FROM '.CATEGORIES_TABLE.'
WHERE dir IS NOT NULL
AND site_id = '.$site_id;
$db_categories = hash_from_query($query, 'id');
$db_fulldirs = get_fulldirs(array_keys($db_categories));
$basedir = preg_replace('#/*$#', '', $site_url);
$db_fulldirs = array_flip($db_fulldirs);
$fs_fulldirs = $site_reader->get_full_directories($basedir);
$next_id = pwg_db_nextval('id', CATEGORIES_TABLE);
foreach (array_diff($fs_fulldirs, array_keys($db_fulldirs)) as $fulldir)
{
$dir = basename($fulldir);
if (!preg_match($conf['sync_chars_regex'], $dir))
{
bratonien_tools_ws_nc_sync_error($errors, $fulldir, 'PWG-UPDATE-1');
continue;
}
$virtual_id = $next_id++;
$db_fulldirs[$fulldir] = $virtual_id;
$db_categories[$virtual_id] = array('id'=>$virtual_id);
$counts['new_categories']++;
}
$to_delete = array();
foreach (array_diff(array_keys($db_fulldirs), $fs_fulldirs) as $fulldir)
{
$to_delete[] = $db_fulldirs[$fulldir];
}
$counts['del_categories'] = count($to_delete);
// -------------------------------------------------------------------
// Files / images / formats
// -------------------------------------------------------------------
$fs = $site_reader->get_elements($basedir);
$cat_ids = array_diff(array_keys($db_categories), $to_delete);
$db_elements = array();
if (count($cat_ids) > 0)
{
$query = '
SELECT id, path
FROM '.IMAGES_TABLE.'
WHERE storage_category_id IN ('.wordwrap(implode(', ', $cat_ids), 160, "\n").')';
$db_elements = simple_hash_from_query($query, 'id', 'path');
}
foreach (array_diff(array_keys($fs), $db_elements) as $path)
{
$dirname = dirname($path);
if (!isset($db_fulldirs[$dirname]))
{
continue;
}
$filename = basename($path);
if (!preg_match($conf['sync_chars_regex'], $filename))
{
bratonien_tools_ws_nc_sync_error($errors, $path, 'PWG-UPDATE-1');
continue;
}
$counts['new_elements']++;
if (!empty($conf['enable_formats']) && isset($fs[$path]['formats']) && is_array($fs[$path]['formats']))
{
$counts['new_formats'] += count($fs[$path]['formats']);
}
}
if (!empty($conf['enable_formats']) && count($db_elements) > 0)
{
$db_elements_flip = array_flip($db_elements);
$existing_ids = array();
foreach (array_intersect_key($fs, $db_elements_flip) as $path => $unused)
{
$existing_ids[] = $db_elements_flip[$path];
}
if (count($existing_ids) > 0)
{
$db_formats = array();
$query = '
SELECT *
FROM '.IMAGE_FORMAT_TABLE.'
WHERE image_id IN ('.implode(',', $existing_ids).')';
$result = pwg_query($query);
while ($row = pwg_db_fetch_assoc($result))
{
if (!isset($db_formats[$row['image_id']]))
{
$db_formats[$row['image_id']] = array();
}
$db_formats[$row['image_id']][$row['ext']] = $row['format_id'];
}
foreach ($db_formats as $image_id => $formats)
{
$path = $db_elements[$image_id];
$filesystem_formats = isset($fs[$path]['formats']) && is_array($fs[$path]['formats']) ? $fs[$path]['formats'] : array();
$counts['del_formats'] += count(array_diff_key($formats, $filesystem_formats));
}
foreach ($existing_ids as $image_id)
{
$path = $db_elements[$image_id];
$known_formats = isset($db_formats[$image_id]) ? $db_formats[$image_id] : array();
$filesystem_formats = isset($fs[$path]['formats']) && is_array($fs[$path]['formats']) ? $fs[$path]['formats'] : array();
$counts['new_formats'] += count(array_diff_key($filesystem_formats, $known_formats));
}
}
}
$counts['del_elements'] = count(array_diff($db_elements, array_keys($fs)));
$files = get_filelist('', $site_id, true, false);
$update_count = 0;
foreach ($files as $id => $file)
{
$data = $site_reader->get_element_update_attributes($file['path']);
if (is_array($data))
{
$update_count++;
}
}
$counts['upd_elements'] = $update_count;
$metadata_files = get_filelist('', $site_id, true, true);
$counts['metadata_candidates'] = count($metadata_files);
return array(
'mode' => 'simulation',
'approved_piwigo_version' => '16.4.0',
'piwigo_version' => $piwigo_version,
'site_id' => $site_id,
'site_url' => $site_url,
'counts' => $counts,
'errors' => $errors,
'error_count' => count($errors),
'database_writes' => false,
'fallback' => 'administrator',
'connected_with' => isset($_SESSION['connected_with']) ? (string)$_SESSION['connected_with'] : '',
'username' => isset($user['username']) ? (string)$user['username'] : '',
'status' => isset($user['status']) ? (string)$user['status'] : '',
);
}

View File

@@ -0,0 +1,161 @@
<?php
if (!defined('PHPWG_ROOT_PATH'))
{
die('Hacking attempt!');
}
function bratonien_tools_presentation_refresh_queue_dir()
{
return PHPWG_ROOT_PATH.PWG_LOCAL_DIR.'bratonien-presentation-refresh';
}
function bratonien_tools_presentation_refresh_normalize_categories(array $category_ids)
{
$result = array();
foreach ($category_ids as $category_id)
{
$category_id = (int)$category_id;
if ($category_id > 0) $result[$category_id] = $category_id;
}
ksort($result, SORT_NUMERIC);
return array_values($result);
}
function bratonien_tools_presentation_refresh_start()
{
if (!function_exists('exec'))
{
error_log('Bratonien presentation refresh: PHP exec() ist deaktiviert; Auftrag bleibt in der Queue.');
return false;
}
$php = function_exists('bratonien_tools_webdav_warmup_php_cli')
? bratonien_tools_webdav_warmup_php_cli()
: null;
if (!$php)
{
foreach (array('/usr/bin/php', '/usr/bin/php8.4', '/usr/bin/php8.3', '/usr/local/bin/php') as $candidate)
{
if (is_file($candidate) && is_executable($candidate))
{
$php = $candidate;
break;
}
}
}
if (!$php)
{
error_log('Bratonien presentation refresh: PHP-CLI wurde nicht gefunden; Auftrag bleibt in der Queue.');
return false;
}
$worker = realpath(BRATONIEN_TOOLS_PATH.'runtime/piwigo-presentation-refresh.php');
if (!$worker || !is_file($worker))
{
error_log('Bratonien presentation refresh: Worker fehlt; Auftrag bleibt in der Queue.');
return false;
}
$log = PHPWG_ROOT_PATH.PWG_LOCAL_DIR.'bratonien-presentation-refresh.log';
$command = 'nohup '.escapeshellarg($php).' '.escapeshellarg($worker)
.' >> '.escapeshellarg($log).' 2>&1 < /dev/null & echo $!';
$output = array();
$exit = 1;
@exec($command, $output, $exit);
return $exit === 0 && !empty($output[0]) && (int)$output[0] > 0;
}
function bratonien_tools_presentation_refresh_enqueue(array $category_ids, $reason='presentation-changed', $all=false)
{
$category_ids = bratonien_tools_presentation_refresh_normalize_categories($category_ids);
$all = (bool)$all;
if (!$all && !$category_ids) return array('queued'=>false, 'started'=>false);
$dir = bratonien_tools_presentation_refresh_queue_dir();
if (!is_dir($dir) && !@mkdir($dir, 0775, true) && !is_dir($dir))
{
throw new RuntimeException('Queue für die Vorschau-Aktualisierung konnte nicht angelegt werden.');
}
$payload = array(
'all'=>$all,
'categories'=>$category_ids,
'reason'=>(string)$reason,
'requested_at'=>time(),
);
$json = json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
if ($json === false) throw new RuntimeException('Vorschau-Auftrag konnte nicht serialisiert werden.');
$name = sprintf('%010d-%s.json', time(), bin2hex(random_bytes(6)));
$target = $dir.'/'.$name;
$tmp = $target.'.tmp';
if (@file_put_contents($tmp, $json."\n", LOCK_EX) === false)
{
throw new RuntimeException('Vorschau-Auftrag konnte nicht geschrieben werden.');
}
@chmod($tmp, 0664);
if (!@rename($tmp, $target))
{
@unlink($tmp);
throw new RuntimeException('Vorschau-Auftrag konnte nicht atomar bereitgestellt werden.');
}
return array('queued'=>true, 'started'=>bratonien_tools_presentation_refresh_start());
}
function bratonien_tools_presentation_refresh_enqueue_all($reason='presentation-changed')
{
return bratonien_tools_presentation_refresh_enqueue(array(), $reason, true);
}
function bratonien_tools_presentation_refresh_category_snapshot()
{
$snapshot = array();
$result = pwg_query('SELECT id, status, visible FROM '.CATEGORIES_TABLE.' ORDER BY id');
while ($row = pwg_db_fetch_assoc($result))
{
$snapshot[(int)$row['id']] = array(
'status'=>(string)$row['status'],
'visible'=>(string)$row['visible'],
);
}
return $snapshot;
}
function bratonien_tools_presentation_refresh_watch_admin_categories()
{
if (!defined('IN_ADMIN') || ($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') return;
// Connector-Sync hat einen eigenen, priorisierten Bildcache-Pfad. Neue
// Kategorien werden dort bereits korrekt an den Worker übergeben.
if ((string)($_GET['page'] ?? '') === 'site_update' && (string)($_POST['bratonien_connector'] ?? '') === '1') return;
$before = bratonien_tools_presentation_refresh_category_snapshot();
register_shutdown_function(function () use ($before) {
try
{
$after = bratonien_tools_presentation_refresh_category_snapshot();
$changed = array();
foreach ($after as $category_id=>$state)
{
if (!isset($before[$category_id])) continue;
if (
(string)$before[$category_id]['status'] !== (string)$state['status']
|| (string)$before[$category_id]['visible'] !== (string)$state['visible']
)
{
$changed[] = (int)$category_id;
}
}
if ($changed)
{
bratonien_tools_presentation_refresh_enqueue($changed, 'album-status-or-visibility-changed');
}
}
catch (Throwable $e)
{
error_log('Bratonien presentation refresh watcher: '.$e->getMessage());
}
});
}

View File

@@ -14,6 +14,53 @@ function bratonien_tools_current_version()
return '0.0.0';
}
function bratonien_tools_self_update_fetch_text($url, &$body, &$details)
{
$body = '';
$details = '';
if (function_exists('curl_init'))
{
$ch = curl_init($url);
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 3,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_TIMEOUT => 20,
CURLOPT_USERAGENT => 'Bratonien-Tools-Updater/'.bratonien_tools_current_version(),
CURLOPT_HTTPHEADER => array('Accept: application/vnd.github+json, text/plain;q=0.9, */*;q=0.8'),
));
$response = curl_exec($ch);
$errno = curl_errno($ch);
$error = curl_error($ch);
$http = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($response === false || $errno !== 0)
{
$details = 'cURL-Fehler '.$errno.': '.$error;
return false;
}
if ($http < 200 || $http >= 300)
{
$details = 'HTTP '.$http;
return false;
}
$body = (string)$response;
return true;
}
if (function_exists('fetchRemote') && fetchRemote($url, $body))
{
return true;
}
$details = 'Remote-Inhalt konnte nicht geladen werden.';
return false;
}
function bratonien_tools_remote_update_info($force = false)
{
$cache_key = 'bratonien_self_update_status';
@@ -28,28 +75,68 @@ function bratonien_tools_remote_update_info($force = false)
}
$current = bratonien_tools_current_version();
$remote_main = '';
$ok = function_exists('fetchRemote') && fetchRemote('https://raw.githubusercontent.com/Terranom674/Piwigo_Bratonien_Tools/main/main.inc.php', $remote_main);
if (!$ok || !preg_match('/Version:\s*([\w.-]+)/i', (string)$remote_main, $m))
$commit_json = '';
$details = '';
$commit_url = 'https://api.github.com/repos/Terranom674/Piwigo_Bratonien_Tools/commits/main';
if (!bratonien_tools_self_update_fetch_text($commit_url, $commit_json, $details))
{
$data = array(
'checked_at' => time(),
'current' => $current,
'remote' => null,
'signature' => null,
'main_sha256' => null,
'update_available' => false,
'error' => 'GitHub konnte nicht erreicht oder die Versionsnummer nicht gelesen werden.',
'error' => 'GitHub konnte nicht erreicht oder der aktuelle Commit nicht ermittelt werden.'.($details !== '' ? ' Details: '.$details : ''),
);
}
else
{
$remote = trim($m[1]);
$data = array(
'checked_at' => time(),
'current' => $current,
'remote' => $remote,
'update_available' => version_compare($remote, $current, '>'),
'error' => null,
);
$commit = json_decode($commit_json, true);
$signature = is_array($commit) ? strtolower(trim((string)($commit['sha'] ?? ''))) : '';
if (!preg_match('/^[a-f0-9]{40}$/', $signature))
{
$data = array(
'checked_at' => time(),
'current' => $current,
'remote' => null,
'signature' => null,
'main_sha256' => null,
'update_available' => false,
'error' => 'GitHub lieferte keine gültige Commit-Signatur für main.',
);
}
else
{
$remote_main = '';
$raw_url = 'https://raw.githubusercontent.com/Terranom674/Piwigo_Bratonien_Tools/'.$signature.'/main.inc.php';
if (!bratonien_tools_self_update_fetch_text($raw_url, $remote_main, $details) || !preg_match('/Version:\s*([\w.-]+)/i', (string)$remote_main, $m))
{
$data = array(
'checked_at' => time(),
'current' => $current,
'remote' => null,
'signature' => $signature,
'main_sha256' => null,
'update_available' => false,
'error' => 'Die Plugin-Version des ermittelten GitHub-Commits konnte nicht gelesen werden.'.($details !== '' ? ' Details: '.$details : ''),
);
}
else
{
$remote = trim($m[1]);
$data = array(
'checked_at' => time(),
'current' => $current,
'remote' => $remote,
'signature' => $signature,
'main_sha256' => hash('sha256', (string)$remote_main),
'update_available' => version_compare($remote, $current, '>'),
'error' => null,
);
}
}
}
if (function_exists('conf_update_param'))
@@ -72,16 +159,17 @@ function bratonien_tools_self_update_check()
throw new RuntimeException($info['error']);
}
$signature_label = !empty($info['signature']) ? substr($info['signature'], 0, 12) : 'unbekannt';
if (!empty($info['update_available']))
{
return array(
'message' => 'Update verfügbar: '.$info['current'].' → '.$info['remote'].'.',
'message' => 'Update verfügbar: '.$info['current'].' → '.$info['remote'].' · Signatur '.$signature_label.'.',
'self_update' => $info,
);
}
return array(
'message' => 'Bratonien Tools ist aktuell (Version '.$info['current'].').',
'message' => 'Bratonien Tools ist aktuell (Version '.$info['current'].', Signatur '.$signature_label.').',
'self_update' => $info,
);
}
@@ -172,6 +260,23 @@ function bratonien_tools_download_update_archive($url, &$data, &$details)
return true;
}
function bratonien_tools_self_update_find_source($extract_dir, $signature)
{
$expected = rtrim($extract_dir, '/').'/Piwigo_Bratonien_Tools-'.$signature;
if (is_dir($expected))
{
return $expected;
}
$candidates = glob(rtrim($extract_dir, '/').'/Piwigo_Bratonien_Tools-*', GLOB_ONLYDIR);
if (is_array($candidates) && count($candidates) === 1)
{
return $candidates[0];
}
return '';
}
function bratonien_tools_self_update_run()
{
global $template;
@@ -202,6 +307,13 @@ function bratonien_tools_self_update_run()
);
}
$signature = strtolower(trim((string)($info['signature'] ?? '')));
$expected_main_sha256 = strtolower(trim((string)($info['main_sha256'] ?? '')));
if (!preg_match('/^[a-f0-9]{40}$/', $signature) || !preg_match('/^[a-f0-9]{64}$/', $expected_main_sha256))
{
throw new RuntimeException('Update abgebrochen: Version oder Signatur des Zielstands ist unvollständig.');
}
$work_root = rtrim(PHPWG_ROOT_PATH, '/').'/_data/bratonien-updater';
if (!is_dir($work_root) && !@mkdir($work_root, 0755, true))
{
@@ -216,7 +328,7 @@ function bratonien_tools_self_update_run()
$zip_data = '';
$download_details = '';
$archive_url = 'https://codeload.github.com/Terranom674/Piwigo_Bratonien_Tools/zip/refs/heads/main';
$archive_url = 'https://codeload.github.com/Terranom674/Piwigo_Bratonien_Tools/zip/'.$signature;
if (!bratonien_tools_download_update_archive($archive_url, $zip_data, $download_details))
{
bratonien_tools_self_update_rrmdir($run_dir);
@@ -245,12 +357,12 @@ function bratonien_tools_self_update_run()
}
$zip->close();
$source = $extract_dir.'/Piwigo_Bratonien_Tools-main';
$source_main = $source.'/main.inc.php';
if (!is_file($source_main))
$source = bratonien_tools_self_update_find_source($extract_dir, $signature);
$source_main = $source !== '' ? $source.'/main.inc.php' : '';
if ($source === '' || !is_file($source_main))
{
bratonien_tools_self_update_rrmdir($run_dir);
throw new RuntimeException('Das geladene Archiv enthält kein gültiges Bratonien-Tools-Plugin. Erwartet wurde: '.$source_main);
throw new RuntimeException('Das geladene Archiv enthält kein gültiges Bratonien-Tools-Plugin für die erwartete Signatur '.substr($signature, 0, 12).'.');
}
$remote_main = @file_get_contents($source_main);
@@ -259,11 +371,18 @@ function bratonien_tools_self_update_run()
bratonien_tools_self_update_rrmdir($run_dir);
throw new RuntimeException('Die geladene Plugin-Version konnte nicht verifiziert werden. main.inc.php fehlt oder enthält keine lesbare Plugin-/Versionsangabe.');
}
$package_version = trim($vm[1]);
$package_main_sha256 = hash('sha256', (string)$remote_main);
if (!hash_equals($expected_main_sha256, $package_main_sha256))
{
bratonien_tools_self_update_rrmdir($run_dir);
throw new RuntimeException('Signaturprüfung fehlgeschlagen: Das geladene Paket gehört nicht exakt zum zuvor geprüften GitHub-Stand '.substr($signature, 0, 12).'.');
}
if ($package_version !== $info['remote'])
{
bratonien_tools_self_update_rrmdir($run_dir);
throw new RuntimeException('Versionsprüfung fehlgeschlagen: Erwartet '.$info['remote'].', erhalten '.$package_version.'.');
throw new RuntimeException('Versionsprüfung fehlgeschlagen: Erwartet '.$info['remote'].', erhalten '.$package_version.'; Signatur '.substr($signature, 0, 12).'.');
}
$plugin_dir = rtrim(BRATONIEN_TOOLS_PATH, '/');
@@ -320,11 +439,13 @@ function bratonien_tools_self_update_run()
'checked_at' => time(),
'current' => $package_version,
'remote' => $package_version,
'signature' => $signature,
'main_sha256' => $package_main_sha256,
'update_available' => false,
'error' => null,
);
return array(
'message' => 'Bratonien Tools wurde auf Version '.$package_version.' aktualisiert. Backup: '.$backup_dir,
'message' => 'Bratonien Tools wurde auf Version '.$package_version.' aktualisiert. Signatur '.substr($signature, 0, 12).'. Backup: '.$backup_dir,
'self_update' => $updated_info,
);
}

View File

@@ -5,125 +5,80 @@ if (!defined('PHPWG_ROOT_PATH'))
}
require_once(BRATONIEN_TOOLS_PATH . 'tools/image_cache.inc.php');
require_once(BRATONIEN_TOOLS_PATH . 'include/cache_clear_atomic.inc.php');
require_once(BRATONIEN_TOOLS_PATH . 'tools/watermark.inc.php');
require_once(BRATONIEN_TOOLS_PATH . 'tools/watermark_profiles.inc.php');
require_once(BRATONIEN_TOOLS_PATH . 'tools/watermark_settings.inc.php');
require_once(BRATONIEN_TOOLS_PATH . 'tools/album_rules.inc.php');
require_once(BRATONIEN_TOOLS_PATH . 'tools/asset_manager.inc.php');
require_once(BRATONIEN_TOOLS_PATH . 'include/watermark_engine.inc.php');
require_once(BRATONIEN_TOOLS_PATH . 'include/presentation_refresh.inc.php');
require_once(BRATONIEN_TOOLS_PATH . 'include/public_selection.inc.php');
require_once(BRATONIEN_TOOLS_PATH . 'include/self_update.inc.php');
require_once(BRATONIEN_TOOLS_PATH . 'include/album_shares.inc.php');
require_once(BRATONIEN_TOOLS_PATH . 'include/album_lock.inc.php');
require_once(BRATONIEN_TOOLS_PATH . 'include/customer_qr_upload.inc.php');
require_once(BRATONIEN_TOOLS_PATH . 'include/friendship_code_upload.inc.php');
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_takeover.inc.php');
require_once(BRATONIEN_TOOLS_PATH . 'include/nc_connector_auth.inc.php');
require_once(BRATONIEN_TOOLS_PATH . 'include/nc_connector_create_api.inc.php');
require_once(BRATONIEN_TOOLS_PATH . 'include/nc_connector_piwigo_api.inc.php');
require_once(BRATONIEN_TOOLS_PATH . 'include/nc_connector_wizard.inc.php');
require_once(BRATONIEN_TOOLS_PATH . 'include/nc_connector_wizard_user_scope.inc.php');
require_once(BRATONIEN_TOOLS_PATH . 'include/nc_connector_connection_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/webdav_warmup_settings.inc.php');
require_once(BRATONIEN_TOOLS_PATH . 'include/webdav_scan_diagnostic.inc.php');
function bratonien_tools_get_tools()
{
return array(
'image_cache_clear' => array(
'handler' => 'bratonien_tools_clear_image_cache',
),
'image_cache_build' => array(
'handler' => 'bratonien_tools_start_main_cache_build',
),
'image_cache_cancel' => array(
'handler' => 'bratonien_tools_cancel_main_cache_build',
),
'image_cache_worker_settings' => array(
'handler' => 'bratonien_tools_save_cache_worker_settings',
),
'watermark_save' => array(
'handler' => 'bratonien_tools_save_watermark',
),
'watermark_file_delete' => array(
'handler' => 'bratonien_tools_delete_watermark_file',
),
'watermark_engine' => array(
'handler' => 'bratonien_tools_handle_watermark_engine',
),
'watermark_profile_save' => array(
'handler' => 'bratonien_tools_save_watermark_profile',
),
'watermark_profile_delete' => array(
'handler' => 'bratonien_tools_delete_watermark_profile',
),
'watermark_profile_duplicate' => array(
'handler' => 'bratonien_tools_duplicate_watermark_profile',
),
'watermark_defaults' => array(
'handler' => 'bratonien_tools_save_watermark_defaults',
),
'watermark_rule' => array(
'handler' => 'bratonien_tools_save_album_rule',
),
'public_selection_settings' => array(
'handler' => 'bratonien_tools_save_public_selection_settings',
),
'asset_upload' => array(
'handler' => 'bratonien_tools_upload_asset',
),
'asset_delete' => array(
'handler' => 'bratonien_tools_delete_asset',
),
'asset_upload_limits' => array(
'handler' => 'bratonien_tools_save_upload_limits',
),
'album_lock_toggle' => array(
'handler' => 'bratonien_tools_toggle_album_lock',
),
'album_share_create' => array(
'handler' => 'bratonien_tools_create_album_share',
),
'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',
),
'nc_connector_import_legacy' => array(
'handler' => 'bratonien_tools_nc_connector_import_legacy',
),
'nc_connector_verify' => array(
'handler' => 'bratonien_tools_nc_connector_verify_managed',
),
'nc_connector_prepare_takeover' => array(
'handler' => 'bratonien_tools_nc_connector_prepare_takeover',
),
'nc_connector_cancel_takeover' => array(
'handler' => 'bratonien_tools_nc_connector_cancel_takeover',
),
'nc_connector_piwigo_api_test' => array(
'handler' => 'bratonien_tools_nc_connector_piwigo_api_test',
),
'nc_connector_piwigo_api_delete' => array(
'handler' => 'bratonien_tools_nc_connector_api_delete',
),
'nc_connector_fallback_save' => array(
'handler' => 'bratonien_tools_nc_connector_fallback_save',
),
'nc_connector_fallback_delete' => array(
'handler' => 'bratonien_tools_nc_connector_fallback_delete',
),
'nc_connector_fallback_once' => array(
'handler' => 'bratonien_tools_nc_connector_fallback_once',
),
'self_update_check' => array(
'handler' => 'bratonien_tools_self_update_check',
),
'self_update_run' => array(
'handler' => 'bratonien_tools_self_update_run',
),
'image_cache_clear' => array('handler' => 'bratonien_tools_clear_image_cache_atomic'),
'image_cache_build' => array('handler' => 'bratonien_tools_start_combined_image_cache_build'),
'image_cache_cancel' => array('handler' => 'bratonien_tools_cancel_combined_image_cache_build'),
'image_cache_worker_settings' => array('handler' => 'bratonien_tools_save_cache_worker_settings'),
'image_cache_webdav_warmup_settings' => array('handler' => 'bratonien_tools_save_webdav_warmup_settings'),
'image_cache_webdav_warmup_manual' => array('handler' => 'bratonien_tools_start_webdav_warmup_manual'),
'image_cache_webdav_warmup_audit' => array('handler' => 'bratonien_tools_run_webdav_warmup_audit'),
'image_cache_webdav_scan_diagnostic' => array('handler' => 'bratonien_tools_run_webdav_scan_diagnostic'),
'watermark_save' => array('handler' => 'bratonien_tools_save_watermark'),
'watermark_file_delete' => array('handler' => 'bratonien_tools_delete_watermark_file'),
'watermark_engine' => array('handler' => 'bratonien_tools_handle_watermark_engine'),
'watermark_profile_save' => array('handler' => 'bratonien_tools_save_watermark_profile'),
'watermark_profile_delete' => array('handler' => 'bratonien_tools_delete_watermark_profile'),
'watermark_profile_duplicate' => array('handler' => 'bratonien_tools_duplicate_watermark_profile'),
'watermark_defaults' => array('handler' => 'bratonien_tools_save_watermark_defaults'),
'watermark_rule' => array('handler' => 'bratonien_tools_save_album_rule'),
'public_selection_settings' => array('handler' => 'bratonien_tools_save_public_selection_settings'),
'customer_qr_settings' => array('handler' => 'bratonien_tools_customer_qr_save_settings'),
'customer_qr_delete' => array('handler' => 'bratonien_tools_customer_qr_delete_upload'),
'friendship_code_delete' => array('handler' => 'bratonien_tools_friendship_code_delete_upload'),
'asset_upload' => array('handler' => 'bratonien_tools_upload_asset'),
'asset_delete' => array('handler' => 'bratonien_tools_delete_asset'),
'asset_upload_limits' => array('handler' => 'bratonien_tools_save_upload_limits'),
'album_lock_toggle' => array('handler' => 'bratonien_tools_toggle_album_lock'),
'album_share_create' => array('handler' => 'bratonien_tools_create_album_share'),
'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_webdav_parallel' => array('handler' => 'bratonien_tools_nc_connector_create_webdav_placeholder_from_wizard'),
'nc_connector_delete' => array('handler' => 'bratonien_tools_nc_connector_delete_safe'),
'nc_connector_update_name' => array('handler' => 'bratonien_tools_nc_connector_update_name'),
'nc_connector_run_now' => array('handler' => 'bratonien_tools_nc_connector_run_now'),
'nc_connector_wizard_scan' => array('handler' => 'bratonien_tools_nc_wizard_scan_webdav_first'),
'nc_connector_wizard_directory_browse' => array('handler' => 'bratonien_tools_nc_wizard_directory_browse'),
'nc_connector_wizard_directory_add' => array('handler' => 'bratonien_tools_nc_wizard_directory_add'),
'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_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_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_fallback_save' => array('handler' => 'bratonien_tools_nc_connector_fallback_save_scoped'),
'nc_connector_fallback_delete' => array('handler' => 'bratonien_tools_nc_connector_fallback_delete_scoped'),
'self_update_check' => array('handler' => 'bratonien_tools_self_update_check'),
'self_update_run' => array('handler' => 'bratonien_tools_self_update_run'),
);
}
@@ -132,9 +87,14 @@ function bratonien_tools_handle_watermark_engine()
$enabled = !empty($_POST['engine_enabled']);
bratonien_tools_set_watermark_engine($enabled);
if (function_exists('bratonien_tools_presentation_refresh_enqueue_all'))
{
bratonien_tools_presentation_refresh_enqueue_all('watermark-engine-changed');
}
return array(
'message' => $enabled
? 'Bratonien-Wasserzeichenverwaltung aktiviert. Piwigos bisherige Wasserzeichen-Nutzung wurde gesichert und unterdrueckt.'
: 'Bratonien-Wasserzeichenverwaltung deaktiviert. Die zuvor gesicherte Piwigo-Wasserzeichen-Nutzung wurde wiederhergestellt.',
? 'Bratonien-Wasserzeichenverwaltung aktiviert. Piwigos bisherige Wasserzeichen-Nutzung wurde gesichert und die Vorschauen werden aktualisiert.'
: 'Bratonien-Wasserzeichenverwaltung deaktiviert. Die zuvor gesicherte Piwigo-Wasserzeichen-Nutzung wurde wiederhergestellt und die Vorschauen werden aktualisiert.',
);
}

View File

@@ -82,16 +82,37 @@ function bratonien_tools_runtime_b64url_encode($value)
return rtrim(strtr(base64_encode($value), '+/', '-_'), '=');
}
function bratonien_tools_profile_watermark_relative(array $profile)
{
$relative = ltrim(trim((string)($profile['watermark_file'] ?? '')), '/');
if ($relative !== '')
{
return $relative;
}
// Ein Profil ohne eigene Datei bedeutet bewusst: Einstellungen dieses
// Profils verwenden, aber die zentrale Basis-Wasserzeichendatei erben.
// Dadurch kann das Standardprofil "Oeffentlich" ohne doppelte Dateipflege
// fuer jedes öffentliche Album als Schutzregel dienen.
if (function_exists('bratonien_tools_get_base_watermark_config'))
{
$base = bratonien_tools_get_base_watermark_config();
$relative = ltrim(trim((string)($base['file'] ?? '')), '/');
}
return $relative;
}
function bratonien_tools_profile_watermark_path(array $profile)
{
static $paths = array();
if (empty($profile['watermark_file']))
$relative = bratonien_tools_profile_watermark_relative($profile);
if ($relative === '')
{
return null;
}
$relative = ltrim((string)$profile['watermark_file'], '/');
if (array_key_exists($relative, $paths))
{
return $paths[$relative];
@@ -119,9 +140,10 @@ function bratonien_tools_profile_watermark_path(array $profile)
function bratonien_tools_runtime_profile_version(array $profile)
{
$watermark_path = bratonien_tools_profile_watermark_path($profile);
$effective_file = bratonien_tools_profile_watermark_relative($profile);
$parts = array(
$profile['id'] ?? 0,
$profile['watermark_file'] ?? '',
$effective_file,
$profile['scale_percent'] ?? 100,
$profile['xpos'] ?? 90,
$profile['ypos'] ?? 90,

View File

@@ -0,0 +1,66 @@
<?php
if (!defined('PHPWG_ROOT_PATH'))
{
die('Hacking attempt!');
}
function bratonien_tools_webdav_derivative_cache_valid($target_path, $derivative, $params=null, &$reason=null)
{
$reason = '';
$target_path = (string)$target_path;
if ($target_path === '' || !is_file($target_path) || !is_readable($target_path))
{
$reason = 'missing';
return false;
}
$cache_root = PHPWG_ROOT_PATH.PWG_DERIVATIVE_DIR;
if (strpos($target_path, $cache_root) !== 0)
{
$reason = 'outside-cache';
return false;
}
clearstatcache(true, $target_path);
$bytes = @filesize($target_path);
if ($bytes === false || $bytes < 1)
{
$reason = 'empty';
return false;
}
$actual = @getimagesize($target_path);
if (!is_array($actual) || (int)($actual[0] ?? 0) < 1 || (int)($actual[1] ?? 0) < 1)
{
$reason = 'not-image';
return false;
}
if (is_object($derivative) && method_exists($derivative, 'get_size'))
{
$expected = $derivative->get_size();
$expected_width = (int)($expected[0] ?? 0);
$expected_height = (int)($expected[1] ?? 0);
if ($expected_width > 0 && $expected_height > 0)
{
if ((int)$actual[0] !== $expected_width || (int)$actual[1] !== $expected_height)
{
$reason = 'dimension-mismatch:'.(int)$actual[0].'x'.(int)$actual[1].'!='.$expected_width.'x'.$expected_height;
return false;
}
}
}
if (is_object($params) && isset($params->last_mod_time))
{
$mtime = @filemtime($target_path);
if ($mtime === false || (int)$mtime < (int)$params->last_mod_time)
{
$reason = 'stale-params';
return false;
}
}
$reason = 'valid';
return true;
}

View 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;
}

View File

@@ -0,0 +1,297 @@
<?php
if (!defined('PHPWG_ROOT_PATH'))
{
die('Hacking attempt!');
}
function bratonien_tools_webdav_materialize_source_info($image_id)
{
static $cache = array();
$image_id = (int)$image_id;
if ($image_id < 1) return null;
$warmup_cli = PHP_SAPI === 'cli'
&& strpos((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 'Bratonien-WebDAV-Cache-Warmup/') === 0;
if (!$warmup_cli && array_key_exists($image_id, $cache)) return $cache[$image_id];
$result = pwg_query('SELECT path, coi FROM '.IMAGES_TABLE.' WHERE id='.$image_id.' LIMIT 1');
if (!pwg_db_num_rows($result)) return $cache[$image_id] = null;
$row = pwg_db_fetch_assoc($result);
$path = (string)($row['path'] ?? '');
if ($path === '') return $cache[$image_id] = null;
$absolute = $path;
if (strpos($absolute, '/') !== 0)
{
$absolute = PHPWG_ROOT_PATH.ltrim(preg_replace('#^\./#', '', $absolute), '/');
}
$resolved = realpath($absolute);
if ($resolved === false) return $cache[$image_id] = null;
$normalized = str_replace('\\', '/', $resolved);
if (!preg_match('#/nc-webdav-source/connection-([0-9]+)/root-([0-9]+)/(.*)$#', $normalized, $match))
{
return $cache[$image_id] = null;
}
$connection_id = (int)$match[1];
$root_fileid = (int)$match[2];
$relative_path = trim((string)$match[3], '/');
if ($connection_id < 1 || $root_fileid < 1 || $relative_path === '')
{
return $cache[$image_id] = null;
}
$table = defined('BRATONIEN_TOOLS_NC_CONNECTIONS_TABLE')
? BRATONIEN_TOOLS_NC_CONNECTIONS_TABLE
: $GLOBALS['prefixeTable'].'bratonien_tools_nc_connections';
$connection_result = pwg_query('SELECT config_json FROM `'.$table.'` WHERE id='.$connection_id.' LIMIT 1');
if (!pwg_db_num_rows($connection_result)) return $cache[$image_id] = null;
$connection_row = pwg_db_fetch_assoc($connection_result);
$config = json_decode((string)$connection_row['config_json'], true);
if (!is_array($config) || (string)($config['source_mode'] ?? '') !== 'webdav-placeholder')
{
return $cache[$image_id] = null;
}
$root_found = false;
$root_path = '';
$roots = isset($config['roots']) && is_array($config['roots']) ? $config['roots'] : array();
foreach ($roots as $root)
{
if ((int)($root['fileid'] ?? 0) === $root_fileid)
{
$root_found = true;
$root_path = trim((string)($root['webdav_path'] ?? ''), '/');
break;
}
}
if (!$root_found) return $cache[$image_id] = null;
$webdav_path = trim($root_path === '' ? $relative_path : $root_path.'/'.$relative_path, '/');
if ($webdav_path === '') return $cache[$image_id] = null;
$content_type = '';
$size = 0;
$etag = '';
$fileid = 0;
$width = 0;
$height = 0;
$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']))
{
$files = $mapping['files'];
$entry = $files[$resolved] ?? $files[$normalized] ?? null;
if (!is_array($entry))
{
foreach ($files as $candidate)
{
if (!is_array($candidate) || (string)($candidate['kind'] ?? '') !== 'file') continue;
if (trim((string)($candidate['webdav_path'] ?? ''), '/') !== $webdav_path) continue;
$entry = $candidate;
break;
}
}
if (is_array($entry) && (string)($entry['kind'] ?? '') === 'file')
{
$mapped_path = trim((string)($entry['webdav_path'] ?? ''), '/');
if ($mapped_path !== '') $webdav_path = $mapped_path;
$content_type = (string)($entry['content_type'] ?? '');
$size = (int)($entry['size'] ?? 0);
$etag = (string)($entry['etag'] ?? '');
$fileid = (int)($entry['fileid'] ?? 0);
$width = (int)($entry['width'] ?? 0);
$height = (int)($entry['height'] ?? 0);
}
}
}
}
return $cache[$image_id] = array(
'image_id'=>$image_id,
'connection_id'=>$connection_id,
'root_fileid'=>$root_fileid,
'relative_path'=>$relative_path,
'webdav_path'=>$webdav_path,
'content_type'=>$content_type,
'size'=>$size,
'etag'=>$etag,
'fileid'=>$fileid,
'width'=>$width,
'height'=>$height,
'state_dir'=>$state_dir,
'coi'=>$row['coi'] ?? null,
);
}
function bratonien_tools_webdav_materialize_image_url($image_id)
{
$info = bratonien_tools_webdav_materialize_source_info($image_id);
if (!$info) return null;
$url = get_root_url().'plugins/'.BRATONIEN_TOOLS_ID.'/webdav-image.php?id='.(int)$image_id;
if ($info['etag'] !== '') $url .= '&v='.rawurlencode(substr(sha1($info['etag']), 0, 12));
return $url;
}
function bratonien_tools_webdav_materialize_custom_params($key)
{
if (!class_exists('DerivativeParams') || !class_exists('SizingParams')) return null;
$tokens = explode('_', trim((string)$key));
if (!$tokens || $tokens[0] === '') return null;
$parse_size = function($value)
{
if (!preg_match('/^[0-9]+(?:x[0-9]+)?$/', (string)$value)) return null;
$parts = explode('x', (string)$value, 2);
$width = (int)$parts[0];
$height = count($parts) === 1 ? $width : (int)$parts[1];
if ($width < 1 || $height < 1 || $width > 20000 || $height > 20000) return null;
return array($width, $height);
};
$token = array_shift($tokens);
$crop = 0;
$min_size = null;
if (isset($token[0]) && $token[0] === 's')
{
$size = $parse_size(substr($token, 1));
}
elseif (isset($token[0]) && $token[0] === 'e')
{
$crop = 1;
$size = $min_size = $parse_size(substr($token, 1));
}
else
{
if (count($tokens) < 2) return null;
$size = $parse_size($token);
$crop_token = (string)array_shift($tokens);
$min_size = $parse_size(array_shift($tokens));
if (!preg_match('/^[a-z]$/', $crop_token) || $min_size === null) return null;
$crop = function_exists('char_to_fraction') ? char_to_fraction($crop_token) : 0;
}
if ($size === null) return null;
$params = new DerivativeParams(new SizingParams($size, $crop, $min_size));
if (class_exists('ImageStdParams')) ImageStdParams::apply_global($params);
return $params;
}
function bratonien_tools_webdav_materialize_variant_from_params($params)
{
if (!is_object($params) || !class_exists('ImageStdParams')) return null;
$type = (string)($params->type ?? '');
$defined = ImageStdParams::get_defined_type_map();
if ($type !== '' && defined('IMG_CUSTOM') && $type !== IMG_CUSTOM && isset($defined[$type]))
{
return 'standard:'.$type;
}
if (!method_exists($params, 'add_url_tokens')) return null;
$tokens = array();
$params->add_url_tokens($tokens);
if (!$tokens) return null;
$key = implode('_', $tokens);
if (!preg_match('/^[A-Za-z0-9_x-]+$/', $key)) return null;
return 'custom:'.$key;
}
function bratonien_tools_webdav_materialize_params_from_variant($variant)
{
$variant = trim((string)$variant);
if ($variant === '' || !class_exists('ImageStdParams')) return null;
if (strpos($variant, 'standard:') === 0)
{
$type = substr($variant, strlen('standard:'));
$defined = ImageStdParams::get_defined_type_map();
return isset($defined[$type]) ? $defined[$type] : null;
}
if (strpos($variant, 'custom:') === 0)
{
$key = substr($variant, strlen('custom:'));
if (!preg_match('/^[A-Za-z0-9_x-]+$/', $key)) return null;
return bratonien_tools_webdav_materialize_custom_params($key);
}
return null;
}
function bratonien_tools_webdav_materialize_b64url_encode($value)
{
return rtrim(strtr(base64_encode((string)$value), '+/', '-_'), '=');
}
function bratonien_tools_webdav_materialize_after_signature($image_id, $variant, $after_url)
{
global $conf;
$key = !empty($conf['secret_key']) ? $conf['secret_key'] : ($conf['db_password'] ?? 'bratonien-tools');
return hash_hmac('sha256', (int)$image_id.'|'.(string)$variant.'|'.(string)$after_url, $key);
}
function bratonien_tools_webdav_materialize_derivative_url($image_id, $variant, array $info, $after_url='')
{
$url = get_root_url().'plugins/'.BRATONIEN_TOOLS_ID.'/webdav-derivative-guard.php?id='.(int)$image_id.'&variant='.rawurlencode($variant);
if ($after_url !== '')
{
$url .= '&after='.rawurlencode(bratonien_tools_webdav_materialize_b64url_encode($after_url));
$url .= '&sig='.rawurlencode(bratonien_tools_webdav_materialize_after_signature($image_id, $variant, $after_url));
}
if (!empty($info['etag'])) $url .= '&v='.rawurlencode(substr(sha1((string)$info['etag']), 0, 12));
return $url;
}
function bratonien_tools_filter_webdav_materialize_src_url($url, $src_image)
{
if (!is_object($src_image) || empty($src_image->id)) return $url;
$webdav_url = bratonien_tools_webdav_materialize_image_url((int)$src_image->id);
return $webdav_url ?: $url;
}
function bratonien_tools_filter_webdav_materialize_derivative_url($url, $params, $src_image, $rel_url)
{
if (!is_object($src_image) || empty($src_image->id)) return $url;
$image_id = (int)$src_image->id;
$info = bratonien_tools_webdav_materialize_source_info($image_id);
if (!$info) return $url;
try
{
$derivative = new DerivativeImage($params, $src_image);
if ($derivative->same_as_source())
{
$source_url = bratonien_tools_webdav_materialize_image_url($image_id);
return $source_url ?: $url;
}
$path = $derivative->get_path();
if ($path !== '' && is_file($path) && is_readable($path)) return $url;
$variant = bratonien_tools_webdav_materialize_variant_from_params($params);
if ($variant === null) return $url;
return bratonien_tools_webdav_materialize_derivative_url($image_id, $variant, $info, (string)$url);
}
catch (Throwable $e)
{
error_log('Bratonien WebDAV materialize derivative #'.$image_id.': '.$e->getMessage());
return $url;
}
}

View File

@@ -0,0 +1,88 @@
<?php
if (!defined('PHPWG_ROOT_PATH'))
{
die('Hacking attempt!');
}
function bratonien_tools_run_webdav_scan_diagnostic()
{
if (!function_exists('exec')) throw new RuntimeException('PHP exec() ist deaktiviert; der Scan-Test kann nicht gestartet werden.');
if (!function_exists('bratonien_tools_nc_connector_connections') || !function_exists('bratonien_tools_nc_connector_is_webdav'))
{
throw new RuntimeException('Connector-Verbindungen koennen nicht gelesen werden.');
}
$php = function_exists('bratonien_tools_webdav_warmup_php_cli') ? bratonien_tools_webdav_warmup_php_cli() : null;
if (!$php) throw new RuntimeException('PHP-CLI wurde fuer den Scan-Test nicht gefunden.');
$script = realpath(BRATONIEN_TOOLS_PATH.'runtime/lib/webdav-scan-diagnostic.php');
if (!$script || !is_file($script)) throw new RuntimeException('WebDAV-Scan-Diagnose wurde nicht gefunden.');
$reports = array();
$failed = false;
foreach (bratonien_tools_nc_connector_connections() as $connection)
{
if (empty($connection['enabled']) || !bratonien_tools_nc_connector_is_webdav($connection)) continue;
$connection_id = (int)($connection['id'] ?? 0);
if ($connection_id < 1) continue;
$output = array();
$exit = 1;
@exec(
escapeshellarg($php).' '.escapeshellarg($script).' --connection-id='.$connection_id.' 2>&1',
$output,
$exit
);
$text = trim(implode("\n", $output));
$decoded = $text !== '' ? json_decode($text, true) : null;
if (!is_array($decoded))
{
$decoded = array(
'ok'=>false,
'connection_id'=>$connection_id,
'fatal'=>'Diagnose lieferte kein gueltiges JSON.',
'raw'=>$text,
);
}
$decoded['exit_code'] = (int)$exit;
$reports[] = $decoded;
if ($exit !== 0 || empty($decoded['ok'])) $failed = true;
}
if (!$reports) throw new RuntimeException('Keine aktive WebDAV-Verbindung gefunden.');
$parts = array();
foreach ($reports as $report)
{
$id = (int)($report['connection_id'] ?? 0);
if (!empty($report['fatal']))
{
$parts[] = 'WebDAV #'.$id.': FEHLER: '.(string)$report['fatal'].' (Exit '.(int)$report['exit_code'].')';
continue;
}
$lock_state = (string)($report['worker_lock_state'] ?? 'unknown');
if ($lock_state === 'free') $lock_text = 'Worker-Lock frei';
elseif ($lock_state === 'busy') $lock_text = 'Worker-Lock BELEGT';
elseif ($lock_state === 'open_failed') $lock_text = 'Worker-Lock NICHT OEFFENBAR';
else $lock_text = 'Worker-Lock unbekannt';
$parts[] = sprintf(
'WebDAV #%d: Mapping %d Dateien, Shadow %d Links, %d passend, %d defekt, %d ohne Mapping, %d doppelt; %s%s (Exit %d).',
$id,
(int)($report['mapping_files'] ?? 0),
(int)($report['shadow_links'] ?? 0),
(int)($report['matched'] ?? 0),
(int)($report['broken'] ?? 0),
(int)($report['unmapped'] ?? 0),
(int)($report['duplicates'] ?? 0),
$lock_text,
!empty($report['worker_lock_detail']) ? ' - '.(string)$report['worker_lock_detail'] : '',
(int)$report['exit_code']
);
}
return array(
'message'=>($failed ? 'Scan-/Lock-Test auffaellig. ' : 'Scan-/Lock-Test erfolgreich. ').implode(' ', $parts),
);
}

View File

@@ -0,0 +1,151 @@
<?php
if (!defined('PHPWG_ROOT_PATH'))
{
die('Hacking attempt!');
}
if (!defined('BRATONIEN_WEBDAV_GENERATION_VERSION'))
{
define('BRATONIEN_WEBDAV_GENERATION_VERSION', 2);
}
function bratonien_tools_webdav_source_index_file($state_dir, $connection_id=0)
{
// Der Quellenindex gehoert dem Piwigo-Worker und muss deshalb in einem
// Verzeichnis liegen, das derselbe Benutzer wie der Admin-/CLI-Worker
// schreiben kann. Das Connector-State-Verzeichnis ist fuer den Worker nur
// lesende Eingabe (Mapping/Priority), nicht sein eigener persistenter State.
$connection_id = (int)$connection_id;
if ($connection_id < 1) throw new RuntimeException('Verbindungs-ID fehlt fuer den WebDAV-Quellenindex.');
return PHPWG_ROOT_PATH.PWG_LOCAL_DIR.'bratonien-webdav-cache-index.connection-'.$connection_id.'.json';
}
function bratonien_tools_webdav_source_index_empty($connection_id)
{
return array(
'schema_version'=>3,
'connection_id'=>(int)$connection_id,
'updated_at'=>0,
'last_periodic_at'=>0,
'sources'=>array(),
);
}
function bratonien_tools_webdav_source_index_load($state_dir, $connection_id)
{
$file = bratonien_tools_webdav_source_index_file($state_dir, $connection_id);
if (!is_file($file) || !is_readable($file)) return null;
$raw = @file_get_contents($file);
$index = $raw !== false ? json_decode($raw, true) : null;
if (!is_array($index)) return null;
$base = bratonien_tools_webdav_source_index_empty($connection_id);
$index = array_merge($base, $index);
if (!isset($index['sources']) || !is_array($index['sources'])) $index['sources'] = array();
$index['connection_id'] = (int)$connection_id;
return $index;
}
function bratonien_tools_webdav_source_index_save($state_dir, $connection_id, array $index)
{
$file = bratonien_tools_webdav_source_index_file($state_dir, $connection_id);
$directory = dirname($file);
if (!is_dir($directory) && !@mkdir($directory, 0775, true) && !is_dir($directory))
{
throw new RuntimeException('WebDAV-Quellenindex-Verzeichnis konnte nicht angelegt werden.');
}
$index['schema_version'] = 3;
$index['connection_id'] = (int)$connection_id;
$index['updated_at'] = time();
if (!isset($index['sources']) || !is_array($index['sources'])) $index['sources'] = array();
ksort($index['sources'], SORT_STRING);
$json = json_encode($index, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
if ($json === false) throw new RuntimeException('WebDAV-Quellenindex konnte nicht serialisiert werden.');
$tmp = $file.'.tmp-'.bin2hex(random_bytes(4));
if (@file_put_contents($tmp, $json."\n", LOCK_EX) === false)
{
throw new RuntimeException('WebDAV-Quellenindex konnte nicht geschrieben werden.');
}
@chmod($tmp, 0664);
if (!@rename($tmp, $file))
{
@unlink($tmp);
throw new RuntimeException('WebDAV-Quellenindex konnte nicht atomar gespeichert werden.');
}
}
function bratonien_tools_webdav_source_index_key(array $source)
{
$connection_id = (int)($source['connection_id'] ?? 0);
$fileid = (int)($source['fileid'] ?? 0);
if ($fileid > 0) return 'c'.$connection_id.':f'.$fileid;
$root_fileid = (int)($source['root_fileid'] ?? 0);
$path = trim((string)($source['webdav_path'] ?? ''), '/');
return 'c'.$connection_id.':r'.$root_fileid.':p'.sha1($path);
}
function bratonien_tools_webdav_source_index_signature(array $source)
{
return sha1(implode('|', array(
'generation-v'.(int)BRATONIEN_WEBDAV_GENERATION_VERSION,
(int)($source['connection_id'] ?? 0),
(int)($source['root_fileid'] ?? 0),
(int)($source['fileid'] ?? 0),
trim((string)($source['webdav_path'] ?? ''), '/'),
(string)($source['etag'] ?? ''),
(int)($source['size'] ?? 0),
strtolower((string)($source['content_type'] ?? $source['mime'] ?? '')),
(int)($source['width'] ?? 0),
(int)($source['height'] ?? 0),
)));
}
function bratonien_tools_webdav_source_index_metadata(array $source, $shadow_relative)
{
$path = trim((string)($source['webdav_path'] ?? ''), '/');
return array(
'fileid'=>(int)($source['fileid'] ?? 0),
'root_fileid'=>(int)($source['root_fileid'] ?? 0),
'webdav_path'=>$path,
'name'=>basename($path),
'etag'=>(string)($source['etag'] ?? ''),
'size'=>(int)($source['size'] ?? 0),
'content_type'=>(string)($source['content_type'] ?? $source['mime'] ?? ''),
'width'=>(int)($source['width'] ?? 0),
'height'=>(int)($source['height'] ?? 0),
'shadow_relative'=>ltrim((string)$shadow_relative, '/'),
'source_signature'=>bratonien_tools_webdav_source_index_signature($source),
'generation_version'=>(int)BRATONIEN_WEBDAV_GENERATION_VERSION,
'last_seen_at'=>time(),
);
}
function bratonien_tools_webdav_source_index_is_current(array $entry, $signature)
{
$signature = (string)$signature;
return isset($entry['source_signature'], $entry['stage1_signature'], $entry['stage2_signature'])
&& (int)($entry['generation_version'] ?? 0) === (int)BRATONIEN_WEBDAV_GENERATION_VERSION
&& hash_equals((string)$entry['source_signature'], $signature)
&& hash_equals((string)$entry['stage1_signature'], $signature)
&& hash_equals((string)$entry['stage2_signature'], $signature);
}
function bratonien_tools_webdav_source_index_prune(array &$index, array $current_keys)
{
$keep = array_fill_keys($current_keys, true);
$removed = 0;
foreach (array_keys((array)$index['sources']) as $key)
{
if (!isset($keep[$key]))
{
unset($index['sources'][$key]);
$removed++;
}
}
return $removed;
}

View File

@@ -0,0 +1,394 @@
<?php
if (!defined('PHPWG_ROOT_PATH'))
{
die('Hacking attempt!');
}
require_once(BRATONIEN_TOOLS_PATH.'include/webdav_source_index.inc.php');
function bratonien_tools_webdav_warmup_settings_file()
{
return PHPWG_ROOT_PATH.PWG_LOCAL_DIR.'bratonien-webdav-warmup.settings.json';
}
function bratonien_tools_get_webdav_warmup_settings()
{
$settings = array(
'enabled'=>false,
'batch_size'=>10,
'periodic_hours'=>12,
);
$file = bratonien_tools_webdav_warmup_settings_file();
if (is_file($file) && is_readable($file))
{
$raw = @file_get_contents($file);
$saved = $raw !== false ? json_decode($raw, true) : null;
if (is_array($saved))
{
if (array_key_exists('enabled', $saved)) $settings['enabled'] = (bool)$saved['enabled'];
if (isset($saved['batch_size'])) $settings['batch_size'] = max(1, min(50, (int)$saved['batch_size']));
if (isset($saved['periodic_hours'])) $settings['periodic_hours'] = max(1, min(168, (int)$saved['periodic_hours']));
}
}
return $settings;
}
function bratonien_tools_webdav_warmup_connections()
{
$result = array();
if (!function_exists('bratonien_tools_nc_connector_connections') || !function_exists('bratonien_tools_nc_connector_is_webdav')) return $result;
foreach (bratonien_tools_nc_connector_connections() as $connection)
{
if (empty($connection['enabled']) || !bratonien_tools_nc_connector_is_webdav($connection)) continue;
$connection_id = (int)($connection['id'] ?? 0);
if ($connection_id < 1) continue;
$config = isset($connection['config']) && is_array($connection['config']) ? $connection['config'] : array();
$state_dir = rtrim((string)($config['state_dir'] ?? ''), '/');
if ($state_dir === '') continue;
$result[$connection_id] = array('id'=>$connection_id, 'state_dir'=>$state_dir, 'connection'=>$connection);
}
return $result;
}
function bratonien_tools_webdav_warmup_status_file_for_connection($connection_id)
{
return PHPWG_ROOT_PATH.PWG_LOCAL_DIR.'bratonien-webdav-warmup.status-'.(int)$connection_id.'.json';
}
function bratonien_tools_webdav_warmup_cancel_file_for_connection($connection_id)
{
return PHPWG_ROOT_PATH.PWG_LOCAL_DIR.'bratonien-webdav-warmup.cancel-'.(int)$connection_id;
}
function bratonien_tools_webdav_warmup_write_status($connection_id, $state, $message, array $extra=array())
{
$file = bratonien_tools_webdav_warmup_status_file_for_connection($connection_id);
$payload = array_merge(array(
'state'=>(string)$state,
'message'=>(string)$message,
'connection_id'=>(int)$connection_id,
'updated_at'=>time(),
), $extra);
$json = json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
if ($json === false) throw new RuntimeException('WebDAV-Worker-Status konnte nicht serialisiert werden.');
$directory = dirname($file);
if (!is_dir($directory) && !@mkdir($directory, 0775, true) && !is_dir($directory)) throw new RuntimeException('WebDAV-Worker-Statusverzeichnis konnte nicht angelegt werden.');
$tmp = $file.'.tmp-'.bin2hex(random_bytes(4));
if (@file_put_contents($tmp, $json."\n", LOCK_EX) === false) throw new RuntimeException('WebDAV-Worker-Status konnte nicht geschrieben werden.');
@chmod($tmp, 0664);
if (!@rename($tmp, $file))
{
@unlink($tmp);
throw new RuntimeException('WebDAV-Worker-Status konnte nicht atomar gespeichert werden.');
}
}
function bratonien_tools_invalidate_webdav_cache_completion($reason='Piwigo-Bildcache wurde geleert.')
{
$invalidated = 0;
foreach (bratonien_tools_webdav_warmup_connections() as $connection_id=>$runtime)
{
$index = bratonien_tools_webdav_source_index_load($runtime['state_dir'], $connection_id);
if (is_array($index))
{
foreach ($index['sources'] as &$entry)
{
if (!is_array($entry)) continue;
unset($entry['stage1_signature'], $entry['stage2_signature']);
}
unset($entry);
bratonien_tools_webdav_source_index_save($runtime['state_dir'], $connection_id, $index);
$invalidated++;
}
bratonien_tools_webdav_warmup_write_status(
$connection_id,
'idle',
$reason.' Der Quellenindex bleibt erhalten; seine Cache-Fertigmarkierungen wurden verworfen.',
array('cache_invalidated'=>true)
);
}
return $invalidated;
}
function bratonien_tools_save_webdav_warmup_settings()
{
$current = bratonien_tools_get_webdav_warmup_settings();
$enabled = !empty($_POST['webdav_warmup_enabled']);
$batch_size = isset($_POST['webdav_warmup_batch_size']) ? (int)$_POST['webdav_warmup_batch_size'] : (int)$current['batch_size'];
$periodic_hours = isset($_POST['webdav_warmup_periodic_hours']) ? (int)$_POST['webdav_warmup_periodic_hours'] : (int)$current['periodic_hours'];
$batch_size = max(1, min(50, $batch_size));
$periodic_hours = max(1, min(168, $periodic_hours));
$payload = array(
'enabled'=>$enabled,
'batch_size'=>$batch_size,
'periodic_hours'=>$periodic_hours,
);
$json = json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
if ($json === false) throw new RuntimeException('Warmup-Einstellungen konnten nicht serialisiert werden.');
$file = bratonien_tools_webdav_warmup_settings_file();
$directory = dirname($file);
if (!is_dir($directory) && !@mkdir($directory, 0775, true) && !is_dir($directory))
{
throw new RuntimeException('Warmup-Einstellungsverzeichnis konnte nicht angelegt werden.');
}
$tmp = $file.'.tmp-'.bin2hex(random_bytes(4));
if (@file_put_contents($tmp, $json."\n", LOCK_EX) === false)
{
throw new RuntimeException('Warmup-Einstellungen konnten nicht gespeichert werden.');
}
@chmod($tmp, 0664);
if (!@rename($tmp, $file))
{
@unlink($tmp);
throw new RuntimeException('Warmup-Einstellungen konnten nicht atomar gespeichert werden.');
}
return array('message'=>sprintf(
'WebDAV-Worker gespeichert: %s, %d Bilder pro Batch, Shadow-Tree-Abgleich alle %d Stunden. Der Worker-Index wird bei Bedarf automatisch aus dem Shadow-Tree aufgebaut.',
$enabled ? 'automatisch aktiv' : 'Automatik deaktiviert',
$batch_size,
$periodic_hours
));
}
function bratonien_tools_webdav_warmup_php_cli()
{
if (function_exists('bratonien_tools_find_php_cli'))
{
$php = bratonien_tools_find_php_cli();
if ($php) return $php;
}
foreach (array('/usr/bin/php', '/usr/bin/php8.4', '/usr/bin/php8.3', '/usr/local/bin/php') as $candidate)
{
if (is_file($candidate) && is_executable($candidate)) return $candidate;
}
return null;
}
function bratonien_tools_start_webdav_warmup_mode($mode, $message)
{
if (!function_exists('exec')) throw new RuntimeException('PHP exec() ist deaktiviert; Worker kann nicht gestartet werden.');
$php = bratonien_tools_webdav_warmup_php_cli();
if (!$php) throw new RuntimeException('PHP-CLI wurde für den WebDAV-Worker nicht gefunden.');
$dispatcher = realpath(BRATONIEN_TOOLS_PATH.'runtime/webdav-warmup-dispatch.php');
if (!$dispatcher || !is_file($dispatcher)) throw new RuntimeException('WebDAV-Worker-Dispatcher wurde nicht gefunden.');
if (!in_array($mode, array('manual','rebuild'), true)) throw new RuntimeException('Ungültiger manueller Worker-Modus.');
$connections = bratonien_tools_webdav_warmup_connections();
if (!$connections) throw new RuntimeException('Keine aktive WebDAV-Verbindung mit vollständiger Runtime gefunden.');
$run_id = date('YmdHis').'-'.bin2hex(random_bytes(4));
foreach ($connections as $connection_id=>$runtime)
{
// Ein altes Abbruchsignal darf niemals den nächsten bewusst gestarteten
// Lauf stoppen. Es wird unmittelbar vor dem neuen Start entfernt.
@unlink(bratonien_tools_webdav_warmup_cancel_file_for_connection($connection_id));
bratonien_tools_webdav_warmup_write_status(
$connection_id,
'queued',
$mode === 'rebuild'
? 'Cache-Rebuild wurde angefordert. Der Worker wartet auf den Start und gleicht danach Shadow-Tree und eigenen Index ab.'
: 'Cache-Abgleich wurde angefordert. Bereits erfolgreich abgeschlossene Stufen bleiben erhalten; geladen werden nur Quellen mit fehlender Stufe 1 oder Stufe 2.',
array('mode'=>$mode, 'run_id'=>$run_id)
);
}
$log = PHPWG_ROOT_PATH.PWG_LOCAL_DIR.'bratonien-webdav-warmup-dispatch.log';
$command = 'nohup '.escapeshellarg($php).' '.escapeshellarg($dispatcher).' --mode='.escapeshellarg($mode).' >> '.escapeshellarg($log).' 2>&1 < /dev/null & echo $!';
$output = array();
$exit = 1;
@exec($command, $output, $exit);
$pid = isset($output[0]) ? (int)$output[0] : 0;
if ($exit !== 0 || $pid <= 0)
{
foreach ($connections as $connection_id=>$runtime)
{
bratonien_tools_webdav_warmup_write_status($connection_id, 'error', 'WebDAV-Worker konnte nicht gestartet werden.', array('mode'=>$mode, 'run_id'=>$run_id));
}
throw new RuntimeException('WebDAV-Worker konnte nicht gestartet werden.');
}
return array('message'=>$message, 'pid'=>$pid, 'run_id'=>$run_id);
}
function bratonien_tools_start_webdav_warmup_manual()
{
return bratonien_tools_start_webdav_warmup_mode(
'manual',
'WebDAV-Worker: Shadow-Tree und Worker-Index werden abgeglichen; vollständig erledigte Quellen werden nicht aus Nextcloud geladen.'
);
}
function bratonien_tools_start_webdav_cache_rebuild()
{
return bratonien_tools_start_webdav_warmup_mode(
'rebuild',
'WebDAV-Bildcache: der vollständige aktuelle Shadow-Bestand wird erneut an Piwigo übergeben.'
);
}
function bratonien_tools_request_webdav_cache_cancel()
{
$requested = 0;
foreach (bratonien_tools_webdav_warmup_connections() as $connection_id=>$runtime)
{
$status_file = bratonien_tools_webdav_warmup_status_file_for_connection($connection_id);
$status = null;
if (is_file($status_file) && is_readable($status_file))
{
$raw = @file_get_contents($status_file);
$status = $raw !== false ? json_decode($raw, true) : null;
}
if (!is_array($status)) $status = array();
$state = (string)($status['state'] ?? 'idle');
if (!in_array($state, array('queued','scan','running','cancelling'), true)) continue;
$cancel = bratonien_tools_webdav_warmup_cancel_file_for_connection($connection_id);
if (@file_put_contents($cancel, (string)time()."\n", LOCK_EX) === false)
{
throw new RuntimeException('WebDAV-Abbruchsignal für Verbindung #'.(int)$connection_id.' konnte nicht geschrieben werden.');
}
@chmod($cancel, 0664);
$extra = $status;
unset($extra['state'], $extra['message'], $extra['connection_id'], $extra['updated_at']);
$extra['cancel_requested'] = true;
bratonien_tools_webdav_warmup_write_status(
$connection_id,
'cancelling',
'Abbruch angefordert. Der aktuell laufende Batch wird noch vollständig beendet; danach werden keine weiteren Nextcloud-Originale geladen.',
$extra
);
$requested++;
}
return $requested;
}
function bratonien_tools_cancel_combined_image_cache_build()
{
$webdav = bratonien_tools_request_webdav_cache_cancel();
$local = false;
if (function_exists('bratonien_tools_main_cache_process_active') && function_exists('bratonien_tools_main_cache_is_running'))
{
$local = bratonien_tools_main_cache_process_active() || bratonien_tools_main_cache_is_running();
}
if ($local && function_exists('bratonien_tools_request_main_cache_cancel'))
{
bratonien_tools_request_main_cache_cancel();
}
if ($webdav > 0 && $local)
{
return array('message'=>'Cache-Abbruch angefordert. Der aktuelle WebDAV-Batch wird noch beendet; lokale Cache-Worker erhalten ebenfalls sofort das Abbruchsignal.');
}
if ($webdav > 0)
{
return array('message'=>'WebDAV-Cache-Abbruch angefordert. Der aktuell laufende Batch wird noch vollständig beendet; danach ist Schluss.');
}
if ($local)
{
return array('message'=>'Lokaler Piwigo-Cache-Abbruch wurde angefordert.');
}
return array('message'=>'Es läuft aktuell kein Cache-Aufbau.');
}
function bratonien_tools_has_local_cache_sources()
{
if (!function_exists('bratonien_tools_webdav_materialize_source_info')) return true;
$result = pwg_query('SELECT id FROM '.IMAGES_TABLE.' ORDER BY id');
while ($row = pwg_db_fetch_assoc($result))
{
$image_id = (int)($row['id'] ?? 0);
if ($image_id < 1) continue;
if (!bratonien_tools_webdav_materialize_source_info($image_id)) return true;
}
return false;
}
function bratonien_tools_start_combined_image_cache_build()
{
// Der normale "Piwigo-Bildcache aufbauen"-Lauf ist immer inkrementell.
// Der Worker liest zuerst ausschließlich Shadow-Tree/Mapping und seinen
// eigenen Index. Nur Quellen, denen laut Index Stufe 1 oder Stufe 2 fehlt,
// dürfen anschließend aus Nextcloud geladen werden. Ein kompletter
// Neuaufbau entsteht nur nach einer echten Cache-Invalidierung (z.B. Cache
// leeren), denn genau dort werden die Stage-Signaturen bewusst entfernt.
$webdav = bratonien_tools_start_webdav_warmup_manual();
$main = array('started'=>false, 'message'=>'');
if (bratonien_tools_has_local_cache_sources())
{
$main = bratonien_tools_start_main_cache_build();
}
else
{
bratonien_tools_write_main_cache_status(array(
'state'=>'complete',
'message'=>'Lokaler Piwigo-Teil nicht erforderlich. Der WebDAV-Worker arbeitet ausschließlich mit Shadow-Tree und eigenem Index.',
'total'=>0,
'completed'=>0,
'generated'=>0,
'cached'=>0,
'skipped'=>0,
'errors'=>0,
'current'=>'',
'worker_count'=>0,
));
$main['message'] = 'Lokaler Piwigo-Teil nicht gestartet, weil keine lokalen Bildquellen vorhanden sind.';
}
$parts = array();
if (!empty($main['message'])) $parts[] = $main['message'];
if (!empty($webdav['message'])) $parts[] = $webdav['message'];
return array(
'started'=>!empty($main['started']) || !empty($webdav['pid']),
'message'=>implode(' ', $parts),
);
}
function bratonien_tools_run_webdav_warmup_audit()
{
if (!function_exists('exec')) throw new RuntimeException('PHP exec() ist deaktiviert; Pfadaudit kann nicht gestartet werden.');
$php = bratonien_tools_webdav_warmup_php_cli();
if (!$php) throw new RuntimeException('PHP-CLI wurde für den Pfadaudit nicht gefunden.');
$audit = realpath(BRATONIEN_TOOLS_PATH.'runtime/lib/webdav-warmup-audit.php');
if (!$audit || !is_file($audit)) throw new RuntimeException('WebDAV-Pfadaudit wurde nicht gefunden.');
$output = array();
$exit = 1;
@exec(escapeshellarg($php).' '.escapeshellarg($audit).' 2>&1', $output, $exit);
$text = trim(implode(' | ', array_slice($output, -8)));
if ($exit !== 0) throw new RuntimeException('WebDAV-Pfadaudit meldet einen unsicheren Zustand'.($text !== '' ? ': '.$text : '.'));
return array('message'=>'WebDAV-Pfadaudit erfolgreich'.($text !== '' ? ': '.$text : '.'));
}
function bratonien_tools_get_webdav_warmup_status()
{
$status = array(
'state'=>'idle',
'message'=>'Noch kein Shadow-Tree-/Worker-Lauf protokolliert.',
'updated_at'=>0,
);
$files = glob(PHPWG_ROOT_PATH.PWG_LOCAL_DIR.'bratonien-webdav-warmup.status-*.json');
if (!$files) return $status;
$latest = null;
foreach ($files as $file)
{
if (!is_readable($file)) continue;
$raw = @file_get_contents($file);
$data = $raw !== false ? json_decode($raw, true) : null;
if (!is_array($data)) continue;
if ($latest === null || (int)($data['updated_at'] ?? 0) > (int)($latest['updated_at'] ?? 0)) $latest = $data;
}
return is_array($latest) ? array_merge($status, $latest) : $status;
}

View File

@@ -1,6 +1,40 @@
(function () {
'use strict';
function initNcConnectorRunNow() {
var section = document.getElementById('nc-connector');
if (!section || section.querySelector('[data-nc-run-now]')) return;
var statusCard = section.querySelector('.bratonien-card');
var token = section.querySelector('input[name="pwg_token"]');
if (!statusCard || !token) return;
var actions = document.createElement('div');
actions.className = 'bratonien-actions';
actions.style.marginTop = '1rem';
actions.setAttribute('data-nc-run-now', '1');
var form = document.createElement('form');
form.method = 'post';
var tokenInput = document.createElement('input');
tokenInput.type = 'hidden';
tokenInput.name = 'pwg_token';
tokenInput.value = token.value;
var button = document.createElement('button');
button.className = 'buttonLike';
button.type = 'submit';
button.name = 'bratonien_tool';
button.value = 'nc_connector_run_now';
button.textContent = 'Jetzt abrufen';
form.appendChild(tokenInput);
form.appendChild(button);
actions.appendChild(form);
statusCard.appendChild(actions);
}
function initBratonienTabs() {
var admin = document.querySelector('.bratonien-admin');
if (!admin) return;
@@ -113,9 +147,14 @@
activate(initial, false);
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initBratonienTabs);
} else {
function init() {
initBratonienTabs();
initNcConnectorRunNow();
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init);
} else {
init();
}
})();

View File

@@ -216,12 +216,105 @@
resizeTimer = window.setTimeout(updateMap, 60);
}
function isWebdavThumbnail(image) {
if (!image || image.id === 'theMainImage') {
return false;
}
var src = image.getAttribute('src') || '';
var dataSrc = image.getAttribute('data-src') || '';
return src.indexOf('plugins/bratonien_tools/webdav-derivative.php') !== -1 ||
dataSrc.indexOf('plugins/bratonien_tools/webdav-derivative.php') !== -1 ||
image.getAttribute('data-bratonien-webdav-thumbnail') === '1';
}
function setThumbnailPlaceholder(image) {
var parent = image.parentElement;
if (!parent || parent.getAttribute('data-bratonien-placeholder-active') === '1') {
return;
}
parent.setAttribute('data-bratonien-placeholder-active', '1');
parent.setAttribute('data-bratonien-placeholder-background-image', parent.style.backgroundImage || '');
parent.setAttribute('data-bratonien-placeholder-background-repeat', parent.style.backgroundRepeat || '');
parent.setAttribute('data-bratonien-placeholder-background-position', parent.style.backgroundPosition || '');
parent.setAttribute('data-bratonien-placeholder-background-size', parent.style.backgroundSize || '');
parent.style.backgroundImage = 'url("' + absoluteUrl('themes/default/icon/img_small.png') + '")';
parent.style.backgroundRepeat = 'no-repeat';
parent.style.backgroundPosition = 'center';
parent.style.backgroundSize = 'auto';
}
function clearThumbnailPlaceholder(image) {
var parent = image.parentElement;
if (!parent || parent.getAttribute('data-bratonien-placeholder-active') !== '1') {
return;
}
parent.style.backgroundImage = parent.getAttribute('data-bratonien-placeholder-background-image') || '';
parent.style.backgroundRepeat = parent.getAttribute('data-bratonien-placeholder-background-repeat') || '';
parent.style.backgroundPosition = parent.getAttribute('data-bratonien-placeholder-background-position') || '';
parent.style.backgroundSize = parent.getAttribute('data-bratonien-placeholder-background-size') || '';
parent.removeAttribute('data-bratonien-placeholder-active');
parent.removeAttribute('data-bratonien-placeholder-background-image');
parent.removeAttribute('data-bratonien-placeholder-background-repeat');
parent.removeAttribute('data-bratonien-placeholder-background-position');
parent.removeAttribute('data-bratonien-placeholder-background-size');
}
function markThumbnailPending(image) {
image.setAttribute('data-bratonien-webdav-thumbnail', '1');
image.classList.remove('bratonien-webdav-thumbnail-ready');
image.classList.add('bratonien-webdav-thumbnail-pending');
setThumbnailPlaceholder(image);
}
function markThumbnailReady(image) {
image.classList.remove('bratonien-webdav-thumbnail-pending');
image.classList.add('bratonien-webdav-thumbnail-ready');
clearThumbnailPlaceholder(image);
}
function protectWebdavThumbnail(image) {
if (!isWebdavThumbnail(image)) {
return;
}
if (image.getAttribute('data-bratonien-thumbnail-bound') !== '1') {
image.setAttribute('data-bratonien-thumbnail-bound', '1');
image.addEventListener('load', function () {
if (image.naturalWidth > 0 && image.naturalHeight > 0) {
markThumbnailReady(image);
}
});
image.addEventListener('error', function () {
markThumbnailPending(image);
});
}
if (image.complete && image.naturalWidth > 0 && image.naturalHeight > 0) {
markThumbnailReady(image);
} else {
markThumbnailPending(image);
}
}
function protectWebdavThumbnails(root) {
var scope = root || document;
var images = scope.querySelectorAll ? scope.querySelectorAll('img') : [];
for (var i = 0; i < images.length; i += 1) {
protectWebdavThumbnail(images[i]);
}
}
$(function () {
var image = document.getElementById('theMainImage');
if (!image) {
return;
}
protectWebdavThumbnails(document.getElementById('theImageAndInfos') || document);
if (image.complete) {
updateMap();
} else {
@@ -241,6 +334,35 @@
attributes: true,
attributeFilter: ['src', 'srcset', 'usemap', 'class', 'style']
});
var thumbnailRoot = document.getElementById('theImageAndInfos');
if (thumbnailRoot) {
var thumbnailObserver = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
if (mutation.type === 'attributes' && mutation.target.tagName === 'IMG') {
protectWebdavThumbnail(mutation.target);
return;
}
for (var i = 0; i < mutation.addedNodes.length; i += 1) {
var node = mutation.addedNodes[i];
if (node.nodeType !== 1) {
continue;
}
if (node.tagName === 'IMG') {
protectWebdavThumbnail(node);
}
protectWebdavThumbnails(node);
}
});
});
thumbnailObserver.observe(thumbnailRoot, {
childList: true,
subtree: true,
attributes: true,
attributeFilter: ['src', 'data-src']
});
}
}
});
})(jQuery);

View File

@@ -23,7 +23,7 @@ $_SERVER['REQUEST_URI'] = '/';
$_SERVER['SCRIPT_NAME'] = '/plugins/bratonien_tools/main-cache-build.php';
$_SERVER['PHP_SELF'] = $_SERVER['SCRIPT_NAME'];
$_SERVER['QUERY_STRING'] = '';
$_SERVER['HTTP_USER_AGENT'] = 'Bratonien-Piwigo-Cache-Builder/1.4';
$_SERVER['HTTP_USER_AGENT'] = 'Bratonien-Piwigo-Cache-Builder/1.5';
$_SERVER['HTTPS'] = 'off';
require_once(PHPWG_ROOT_PATH.'include/common.inc.php');
@@ -35,6 +35,7 @@ if (!defined('BRATONIEN_TOOLS_PATH'))
require_once(BRATONIEN_TOOLS_PATH.'tools/image_cache.inc.php');
require_once(BRATONIEN_TOOLS_PATH.'include/watermark_engine.inc.php');
require_once(BRATONIEN_TOOLS_PATH.'include/webdav_materialize_runtime.inc.php');
require_once(PHPWG_ROOT_PATH.'include/derivative.inc.php');
require_once(PHPWG_ROOT_PATH.'admin/include/image.class.php');
@@ -207,7 +208,18 @@ function bratonien_tools_cache_builder_worker($worker_index, $worker_count, $run
$result = pwg_query('SELECT * FROM '.IMAGES_TABLE.' ORDER BY id');
while ($row = pwg_db_fetch_assoc($result))
{
if (((int)$row['id'] % $worker_count) === $worker_index)
$image_id = (int)$row['id'];
// WebDAV-Bilder gehören vollständig in den materialisierenden Rebuild-/Warmup-Pfad.
// Sie dürfen im Legacy-Worker weder erzeugt noch als "übersprungen" gezählt werden,
// weil das die Fortschrittsanzeige nach einem Cache-Leeren fälschlich wie einen
// abgeschlossenen Lauf aussehen lässt.
if (bratonien_tools_webdav_materialize_source_info($image_id))
{
continue;
}
if (($image_id % $worker_count) === $worker_index)
{
$rows[] = $row;
}
@@ -248,6 +260,7 @@ function bratonien_tools_cache_builder_worker($worker_index, $worker_count, $run
{
$derivative = new DerivativeImage($requested_params, $src);
$target_path = $derivative->get_path();
if (strpos($target_path, PHPWG_ROOT_PATH.PWG_DERIVATIVE_DIR) !== 0)
{
$skipped++;
@@ -473,7 +486,7 @@ for ($i=0; $i<$worker_count; $i++)
}
}
$running_message = sprintf('Piwigo-Bildcache wird mit %d parallelen Worker(n) aufgebaut.', $worker_count);
$running_message = sprintf('Piwigo-Bildcache wird mit %d parallelen Worker(n) aufgebaut. WebDAV-Bilder laufen getrennt über den Piwigo-Rebuild.', $worker_count);
bratonien_tools_write_main_cache_status(array(
'state'=>'running',
'message'=>$running_message,
@@ -522,7 +535,7 @@ $state = bratonien_tools_cache_builder_aggregate(
$worker_count,
$was_cancelled
? 'Piwigo-Bildcache-Aufbau wurde abgebrochen.'
: ($exit_error ? 'Piwigo-Bildcache beendet; mindestens ein Worker meldete einen Prozessfehler.' : 'Piwigo-Bildcache wurde aufgebaut.')
: ($exit_error ? 'Piwigo-Bildcache beendet; mindestens ein Worker meldete einen Prozessfehler.' : 'Lokaler Piwigo-Bildcache wurde aufgebaut; WebDAV-Bilder laufen getrennt über den Piwigo-Rebuild.')
);
for ($i=0; $i<$worker_count; $i++)
@@ -536,3 +549,4 @@ fclose($lock);
@unlink($lock_path);
exit(($state === 'error' || $exit_error) ? 1 : 0);
}

View File

@@ -25,32 +25,266 @@ if (!function_exists('is_admin') || !is_admin())
}
require_once(BRATONIEN_TOOLS_PATH.'tools/image_cache.inc.php');
$file = bratonien_tools_main_cache_status_file();
if (!is_file($file) || !is_readable($file))
function bratonien_tools_status_read_json($file)
{
echo json_encode(array(
'state'=>'idle','message'=>'Noch kein manueller Cache-Aufbau gestartet.',
if (!is_file($file) || !is_readable($file)) return null;
$raw = @file_get_contents($file);
$data = $raw !== false ? json_decode($raw, true) : null;
return is_array($data) ? $data : null;
}
function bratonien_tools_status_webdav_label(array $status)
{
$connection = (int)($status['connection_id'] ?? 0);
$state = (string)($status['state'] ?? 'idle');
$prefix = $connection > 0 ? 'WebDAV #'.$connection.': ' : 'WebDAV: ';
if ($state === 'queued' || $state === 'waiting') return $prefix.((string)($status['message'] ?? '') !== '' ? (string)$status['message'] : 'Worker wartet auf den nächsten sicheren Startpunkt.');
if ($state === 'scan')
{
$sources = (int)($status['shadow_sources'] ?? 0);
$selected = (int)($status['selected'] ?? 0);
$removed = (int)($status['removed_from_index'] ?? 0);
$created = !empty($status['index_created']);
return $prefix.'Shadow-Tree wird mit dem eigenen Worker-Index verglichen · '.$sources.' Quellen im Shadow-Tree · '.$selected.' zu verarbeiten'.($removed > 0 ? ' · '.$removed.' gelöschte Quelle(n) aus dem Worker-Index entfernt' : '').($created ? ' · Worker-Index wurde neu angelegt' : '').'.';
}
if ($state === 'running')
{
$stage = (int)($status['stage'] ?? 0);
$batch = (int)($status['batch'] ?? 0);
$requested = (int)($status['batch_requested'] ?? 0);
$downloaded = (int)($status['batch_downloaded'] ?? 0);
$completed = (int)($status['stage_completed'] ?? 0);
$total = (int)($status['selected_total'] ?? 0);
$parts = array($prefix.'Worker stellt Originale temporär bereit; Piwigo erzeugt die Derivate');
if ($stage > 0) $parts[] = 'Stufe '.$stage;
if ($batch > 0) $parts[] = 'Batch '.$batch;
if ($requested > 0) $parts[] = $downloaded.' / '.$requested.' Quellen dieses Batches geladen';
if ($total > 0) $parts[] = $completed.' / '.$total.' Quellen dieser Stufe abgeschlossen';
return implode(' · ', $parts).'.';
}
if ($state === 'cancelling') return $prefix.((string)($status['message'] ?? '') !== '' ? (string)$status['message'] : 'Abbruch angefordert; aktueller Batch wird noch beendet.');
if ($state === 'cancelled') return $prefix.((string)($status['message'] ?? '') !== '' ? (string)$status['message'] : 'Cache-Aufbau wurde abgebrochen.');
if ($state === 'partial') return $prefix.((string)($status['message'] ?? '') !== '' ? (string)$status['message'] : 'Einzelne Quellen sind noch offen und werden beim nächsten Lauf erneut versucht.');
if ($state === 'preempted') return $prefix.'Stufe 2 wurde nach einem vollständigen Batch unterbrochen, damit neue Connector-Inhalte zuerst verarbeitet werden können.';
if ($state === 'complete') return $prefix.((string)($status['message'] ?? '') !== '' ? (string)$status['message'] : 'Verarbeitung abgeschlossen.');
if ($state === 'error' || $state === 'fatal') return $prefix.'FEHLER: '.((string)($status['message'] ?? '') !== '' ? (string)$status['message'] : 'WebDAV-Verarbeitung fehlgeschlagen.');
return $prefix.((string)($status['message'] ?? '') !== '' ? (string)$status['message'] : 'wartet.');
}
$local_file = bratonien_tools_main_cache_status_file();
$local = bratonien_tools_status_read_json($local_file);
if ($local === null)
{
$local = array(
'state'=>'idle','message'=>'Noch kein lokaler Piwigo-Cache-Aufbau gestartet.',
'total'=>0,'completed'=>0,'generated'=>0,'cached'=>0,'skipped'=>0,'errors'=>0,'current'=>'','updated_at'=>0,
), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
exit;
);
}
$raw = @file_get_contents($file);
$data = $raw !== false ? json_decode($raw, true) : null;
if (!is_array($data))
$webdav = array();
foreach ((array)glob(PHPWG_ROOT_PATH.PWG_LOCAL_DIR.'bratonien-webdav-warmup.status-*.json') as $file)
{
http_response_code(500);
echo json_encode(array('state'=>'error','message'=>'Cache-Status ist nicht lesbar.'));
exit;
$status = bratonien_tools_status_read_json($file);
if (!$status) continue;
if (!isset($status['connection_id']) && preg_match('/status-(\d+)\.json$/', $file, $m)) $status['connection_id'] = (int)$m[1];
$webdav[] = $status;
}
usort($webdav, function($a, $b) {
return (int)($a['connection_id'] ?? 0) <=> (int)($b['connection_id'] ?? 0);
});
$state = (string)($data['state'] ?? 'idle');
$updated = (int)($data['updated_at'] ?? 0);
if (($state === 'running' || $state === 'queued') && $updated > 0 && (time() - $updated) > 45)
$webdav_active = false;
$webdav_waiting = false;
$webdav_partial = false;
$webdav_cancelling = false;
$webdav_cancelled = false;
$webdav_error = false;
$webdav_pending = false;
$webdav_latest = 0;
$webdav_lines = array();
$webdav_all_complete = !empty($webdav);
$webdav_progress_total = 0;
$webdav_progress_completed = 0;
$webdav_source_total = 0;
foreach ($webdav as &$status)
{
$data['state'] = 'error';
$data['message'] = 'Cache-Aufbau liefert seit mehr als 45 Sekunden keinen Fortschritt. Der Prozess ist vermutlich beendet oder festgefahren.';
$data['errors'] = max(1, (int)($data['errors'] ?? 0));
$state = (string)($status['state'] ?? 'idle');
$updated = (int)($status['updated_at'] ?? 0);
$webdav_latest = max($webdav_latest, $updated);
if ($state === 'queued' && $updated > 0 && (time() - $updated) > 45)
{
$state = 'error';
$status['state'] = 'error';
$status['message'] = 'Worker wurde angefordert, hat aber innerhalb von 45 Sekunden keinen Scan gestartet.';
}
// Ältere Dispatcher-Versionen konnten den Zustand "waiting" schreiben und
// anschließend ohne Fortsetzungsauftrag enden. Dieser reine Statuswert ist
// kein Beweis für einen laufenden Connector und darf die Cache-Seite nicht
// dauerhaft blockieren. Neue Wartezustände tragen resume_scheduled=true und
// besitzen einen echten Hintergrund-Warter.
if ($state === 'waiting' && empty($status['resume_scheduled']) && $updated > 0 && (time() - $updated) > 45)
{
$state = 'idle';
$status['state'] = 'idle';
$status['message'] = 'Veralteter Connector-Wartezustand wurde verworfen; aktuell ist kein fortsetzbarer Cache-Auftrag registriert.';
}
if ($state === 'scan')
{
$selected = max(0, (int)($status['selected'] ?? 0));
$webdav_source_total += $selected;
$webdav_progress_total += $selected * 2;
}
elseif ($state === 'running' || $state === 'cancelling')
{
$selected = max(0, (int)($status['selected_total'] ?? $status['selected'] ?? 0));
$stage = max(1, (int)($status['stage'] ?? 1));
$stage_completed = max(0, min($selected, (int)($status['stage_completed'] ?? 0)));
$webdav_source_total += $selected;
$webdav_progress_total += $selected * 2;
$webdav_progress_completed += $stage >= 2 ? $selected + $stage_completed : $stage_completed;
}
elseif (in_array($state, array('complete','error','fatal','preempted','cancelled','waiting','partial'), true))
{
$selected = max(0, (int)($status['selected'] ?? 0));
if ($selected > 0)
{
$stage1_completed = max(0, (int)($status['stage1_completed'] ?? 0));
$stage2_completed = max(0, (int)($status['stage2_completed'] ?? 0));
$stage1_failed = max(0, (int)($status['stage1_failed'] ?? 0));
$stage2_failed = max(0, (int)($status['stage2_failed'] ?? 0));
$stage1_deferred = max(0, (int)($status['stage1_deferred'] ?? 0));
$stage2_deferred = max(0, (int)($status['stage2_deferred'] ?? 0));
$webdav_source_total += $selected;
$webdav_progress_total += $selected * 2;
$webdav_progress_completed += min($selected * 2, $stage1_completed + $stage2_completed + $stage1_failed + $stage2_failed + $stage1_deferred + $stage2_deferred);
}
}
if (in_array($state, array('queued','scan','running'), true)) $webdav_active = true;
if ($state === 'waiting') $webdav_waiting = true;
if ($state === 'partial') $webdav_partial = true;
if ($state === 'cancelling') $webdav_cancelling = true;
if ($state === 'cancelled') $webdav_cancelled = true;
if ($state === 'preempted') $webdav_pending = true;
if (in_array($state, array('error','fatal'), true)) $webdav_error = true;
if ($state !== 'complete' && $state !== 'idle') $webdav_all_complete = false;
$webdav_lines[] = bratonien_tools_status_webdav_label($status);
}
unset($status);
$local_state = (string)($local['state'] ?? 'idle');
$local_updated = (int)($local['updated_at'] ?? 0);
$local_stale = in_array($local_state, array('running','queued'), true) && $local_updated > 0 && (time() - $local_updated) > 45;
if ($local_stale && !$webdav_active && !$webdav_cancelling && !$webdav_waiting)
{
$local['state'] = 'error';
$local['message'] = 'Der lokale Piwigo-Teil liefert seit mehr als 45 Sekunden keinen Fortschritt.';
$local['errors'] = max(1, (int)($local['errors'] ?? 0));
$local_state = 'error';
}
echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
if ($local_state === 'running' || $local_state === 'queued') $local_label = 'Lokaler Piwigo-Teil läuft: '.((string)($local['message'] ?? '') !== '' ? (string)$local['message'] : 'Cache-Varianten werden verarbeitet.');
elseif ($local_state === 'complete') $local_label = 'Lokaler Piwigo-Teil fertig.';
elseif ($local_state === 'cancelled') $local_label = 'Lokaler Piwigo-Teil wurde abgebrochen.';
elseif ($local_state === 'error') $local_label = 'Lokaler Piwigo-Teil mit Fehler: '.((string)($local['message'] ?? '') !== '' ? (string)$local['message'] : 'unbekannter Fehler');
else $local_label = 'Lokaler Piwigo-Teil: keine relevanten lokalen Bildquellen aktiv.';
$overall = $local;
$overall['local'] = $local;
$overall['webdav'] = $webdav;
$overall['updated_at'] = max($local_updated, $webdav_latest);
$overall['source_total'] = $webdav_source_total;
$local_total = max(0, (int)($local['total'] ?? 0));
$local_completed = max(0, min($local_total, (int)($local['completed'] ?? 0)));
$combined_total = $local_total + $webdav_progress_total;
$combined_completed = $local_completed + min($webdav_progress_total, $webdav_progress_completed);
if ($webdav_cancelling || $local_state === 'cancelling')
{
$overall['state'] = 'cancelling';
$overall['total'] = $combined_total;
$overall['completed'] = $combined_completed;
$overall['message'] = 'Cache-Aufbau wird nach dem aktuell laufenden Batch beendet'.($webdav_source_total > 0 ? ' · '.$webdav_source_total.' WebDAV-Quellen' : '').'.';
$overall['current'] = implode(' ', $webdav_lines);
}
elseif ($webdav_active)
{
$overall['state'] = 'running';
$overall['total'] = $combined_total;
$overall['completed'] = $combined_completed;
$overall['generated'] = (int)($local['generated'] ?? 0);
$overall['cached'] = (int)($local['cached'] ?? 0);
$overall['skipped'] = (int)($local['skipped'] ?? 0);
$overall['message'] = 'Gesamtaufbau läuft'.($webdav_source_total > 0 ? ' · '.$webdav_source_total.' WebDAV-Quellen' : '').'. '.$local_label;
$overall['current'] = implode(' ', $webdav_lines);
}
elseif ($webdav_waiting)
{
$overall['state'] = 'queued';
$overall['total'] = $combined_total;
$overall['completed'] = $combined_completed;
$overall['message'] = 'Cache-Aufbau pausiert für laufende Connector-Synchronisierung'.($webdav_source_total > 0 ? ' · '.$webdav_source_total.' WebDAV-Quellen' : '').'. Der Fortsetzungsauftrag bleibt registriert.';
$overall['current'] = implode(' ', $webdav_lines);
}
elseif ($webdav_partial)
{
$overall['state'] = 'queued';
$overall['total'] = $combined_total;
$overall['completed'] = $combined_completed;
$overall['errors'] = 0;
$overall['message'] = 'Cache-Aufbau bleibt fortsetzbar: einzelne Quellen sind noch offen; der restliche Bestand wurde weiterverarbeitet.';
$overall['current'] = implode(' ', $webdav_lines);
}
elseif ($webdav_error || $local_state === 'error')
{
$overall['state'] = 'error';
if ($combined_total > 0)
{
$overall['total'] = $combined_total;
$overall['completed'] = $combined_completed;
}
$overall['message'] = 'Cache-Aufbau mit Fehlern'.($webdav_source_total > 0 ? ' · '.$webdav_source_total.' WebDAV-Quellen' : '').'. '.$local_label;
$overall['current'] = implode(' ', $webdav_lines);
$overall['errors'] = max(1, (int)($overall['errors'] ?? 0));
}
elseif ($webdav_pending)
{
$overall['state'] = 'queued';
$overall['total'] = $combined_total;
$overall['completed'] = $combined_completed;
$overall['message'] = 'Cache-Aufbau wartet auf priorisierte Connector-Inhalte'.($webdav_source_total > 0 ? ' · '.$webdav_source_total.' WebDAV-Quellen' : '').'. '.$local_label;
$overall['current'] = implode(' ', $webdav_lines);
}
elseif ($webdav_cancelled || $local_state === 'cancelled')
{
$overall['state'] = 'cancelled';
$overall['total'] = $combined_total;
$overall['completed'] = $combined_completed;
$overall['message'] = 'Cache-Aufbau wurde nach dem letzten vollständig abgeschlossenen Batch beendet.';
$overall['current'] = implode(' ', $webdav_lines);
}
elseif ($webdav_all_complete && $local_state === 'complete')
{
$overall['state'] = 'complete';
if ($combined_total > 0)
{
$overall['total'] = $combined_total;
$overall['completed'] = $combined_total;
}
$overall['message'] = 'Cache-Aufbau abgeschlossen'.($webdav_source_total > 0 ? ' · '.$webdav_source_total.' WebDAV-Quellen' : '').'. '.$local_label;
$overall['current'] = implode(' ', $webdav_lines);
}
else
{
$overall['state'] = $local_state === 'complete' ? 'idle' : $local_state;
$overall['message'] = $local_label;
if ($webdav_lines) $overall['current'] = implode(' ', $webdav_lines);
}
echo json_encode($overall, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

View File

@@ -1,7 +1,7 @@
<?php
/*
Plugin Name: Bratonien Tools
Version: 0.9.3.32
Version: 0.9.7.1.51
Description: Erweiterbare Administrationswerkzeuge fuer die Bratonien-Piwigo-Installation.
Plugin URI: https://github.com/Terranom674/Piwigo_Bratonien_Tools
Author: Bratonien
@@ -16,24 +16,34 @@ 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/webdav_cache_validation.inc.php');
require_once(BRATONIEN_TOOLS_PATH . 'include/webdav_materialize_runtime.inc.php');
require_once(BRATONIEN_TOOLS_PATH . 'include/presentation_refresh.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');
require_once(BRATONIEN_TOOLS_PATH . 'include/album_shares.inc.php');
require_once(BRATONIEN_TOOLS_PATH . 'include/nc_connector_ws.inc.php');
require_once(BRATONIEN_TOOLS_PATH . 'include/nc_orphan_ws.inc.php');
require_once(BRATONIEN_TOOLS_PATH . 'include/nc_productive_ws.inc.php');
require_once(BRATONIEN_TOOLS_PATH . 'include/customer_qr_upload.inc.php');
require_once(BRATONIEN_TOOLS_PATH . 'include/customer_qr_frontend_menu.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_materialize_src_url', EVENT_HANDLER_PRIORITY_NEUTRAL + 50, 2);
add_event_handler('get_derivative_url', 'bratonien_tools_filter_webdav_materialize_derivative_url', EVENT_HANDLER_PRIORITY_NEUTRAL + 50, 4);
add_event_handler('loc_end_element_set_global', 'bratonien_tools_batch_titles_register_action');
add_event_handler('element_set_global_action', 'bratonien_tools_batch_titles_apply', EVENT_HANDLER_PRIORITY_NEUTRAL, 2);
add_event_handler('init', 'bratonien_tools_prepare_connector_private_import', EVENT_HANDLER_PRIORITY_NEUTRAL - 30);
add_event_handler('init', 'bratonien_tools_prepare_private_album_permissions', EVENT_HANDLER_PRIORITY_NEUTRAL - 20);
add_event_handler('init', 'bratonien_tools_preserve_private_album_access', EVENT_HANDLER_PRIORITY_NEUTRAL - 10);
add_event_handler('init', 'bratonien_tools_preserve_connector_top_level_access', EVENT_HANDLER_PRIORITY_NEUTRAL - 9);
add_event_handler('init', 'bratonien_tools_presentation_refresh_watch_admin_categories', EVENT_HANDLER_PRIORITY_NEUTRAL - 8);
add_event_handler('init', 'bratonien_tools_album_shares_init');
add_event_handler('loc_end_intro', 'bratonien_tools_fix_admin_album_stat_tile');
add_event_handler('loc_end_page_tail', 'bratonien_tools_add_legal_footer_links');
add_event_handler('delete_categories', 'bratonien_tools_album_shares_on_delete_categories');
add_event_handler('ws_add_methods', 'bratonien_tools_register_ws_methods');
add_event_handler('ws_add_methods', 'bratonien_tools_register_nc_orphan_ws_methods');
add_event_handler('ws_add_methods', 'bratonien_tools_register_nc_productive_ws_methods');
@@ -80,36 +90,124 @@ function bratonien_tools_prepare_private_album_permissions()
return;
}
$result = pwg_query('SELECT status FROM '.CATEGORIES_TABLE.' WHERE id = '.$category_id.' LIMIT 1');
if (!pwg_db_num_rows($result))
bratonien_tools_grant_private_album_access($category_id, (int)$user['id']);
}
function bratonien_tools_preserve_connector_top_level_access()
{
global $user;
if (
!defined('IN_ADMIN')
|| ($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST'
|| (string)($_GET['page'] ?? '') !== 'site_update'
|| (string)($_POST['bratonien_connector'] ?? '') !== '1'
|| empty($user['id'])
)
{
return;
}
$category = pwg_db_fetch_assoc($result);
if ($category['status'] !== 'public')
$site_id = (int)($_GET['site'] ?? 0);
$user_id = (int)$user['id'];
if ($site_id < 1 || $user_id < 1)
{
return;
}
$users = isset($_POST['users']) && is_array($_POST['users']) ? $_POST['users'] : array();
$current_user_id = (int)$user['id'];
$normalized_user_ids = array_map('intval', $users);
register_shutdown_function(function () use ($site_id, $user_id) {
$query = '\nSELECT id\n FROM '.CATEGORIES_TABLE.'\n WHERE site_id = '.$site_id.'\n AND dir IS NOT NULL\n AND id_uppercat IS NULL\n AND status = \'private\'\n;';
$result = pwg_query($query);
$changed = false;
while ($row = pwg_db_fetch_assoc($result))
{
$category_id = (int)$row['id'];
if ($category_id < 1)
{
continue;
}
if (!in_array($current_user_id, $normalized_user_ids, true))
$access_query = '\nSELECT 1\n FROM '.USER_ACCESS_TABLE.'\n WHERE user_id = '.$user_id.'\n AND cat_id = '.$category_id.'\n LIMIT 1\n;';
if (pwg_db_num_rows(pwg_query($access_query)) > 0)
{
continue;
}
bratonien_tools_grant_private_album_access($category_id, $user_id);
$changed = true;
}
if ($changed && function_exists('invalidate_user_cache'))
{
invalidate_user_cache(true);
}
});
}
function bratonien_tools_grant_private_album_access($category_id, $user_id)
{
$category_id = (int)$category_id;
$user_id = (int)$user_id;
if ($category_id < 1 || $user_id < 1)
{
$users[] = $current_user_id;
return;
}
$_POST['users'] = $users;
$query = '\nSELECT 1\n FROM '.USER_ACCESS_TABLE.'\n WHERE user_id = '.$user_id.'\n AND cat_id = '.$category_id.'\n LIMIT 1\n;';
$result = pwg_query($query);
if (pwg_db_num_rows($result) > 0)
{
return;
}
single_insert(
USER_ACCESS_TABLE,
array(
'user_id' => $user_id,
'cat_id' => $category_id,
)
);
}
function bratonien_tools_fix_admin_album_stat_tile()
{
global $template;
if (!defined('IN_ADMIN'))
{
return;
}
$template->set_prefilter('intro', 'bratonien_tools_prefilter_admin_album_stat_tile');
}
function bratonien_tools_prefilter_admin_album_stat_tile($source)
{
return str_replace('{if $NB_ALBUMS > 1}', '{if $NB_ALBUMS > 0}', $source);
}
function bratonien_tools_add_legal_footer_links()
{
global $template;
if (defined('IN_ADMIN'))
{
return;
}
$template->append(
'footer_elements',
' - <a href="https://links.bratonien.de/@bratonien_cosplay#bratonien-popup-856170002" rel="noopener">Impressum</a>'
.' - <a href="https://links.bratonien.de/@bratonien_cosplay#bratonien-popup-907192090" rel="noopener">Datenschutzerklärung</a>'
);
}
function bratonien_tools_admin_menu($menu)
{
$menu[] = array(
'NAME' => 'Bratonien Tools',
'URL' => get_root_url() . 'admin.php?page=plugin-' . BRATONIEN_TOOLS_ID,
'URL' => get_root_url() . 'admin.php?page=plugin-' . BRATONIEN_TOOLS_ID,
);
return $menu;
}
?>

View File

@@ -1,397 +0,0 @@
#!/usr/bin/env php
<?php
if (PHP_SAPI !== 'cli')
{
fwrite(STDERR, "Dieses Hilfsprogramm darf nur auf der Kommandozeile ausgefuehrt werden.\n");
exit(1);
}
if (function_exists('posix_geteuid') && posix_geteuid() !== 0)
{
fwrite(STDERR, "Bitte als root ausfuehren.\n");
exit(1);
}
if ($argc !== 2 || !preg_match('/^[1-9][0-9]*$/', $argv[1]))
{
fwrite(STDERR, "Aufruf: php nc-connector-cutover-v2.php <connection-id>\n");
exit(1);
}
$connectionId = (int)$argv[1];
$piwigoRoot = dirname(__DIR__, 2);
$dbConfig = $piwigoRoot.'/local/config/database.inc.php';
$legacyConfig = '/etc/piwigo-sync/piwigo.conf';
$legacyRuntime = '/opt/piwigo-sync/sync.sh';
$newTimer = 'bratonien-nc-connector.timer';
$newService = 'bratonien-nc-connector.service';
$legacyTimer = 'piwigo-sync.timer';
function fail($message)
{
throw new RuntimeException($message);
}
function readKeyValueFile($path)
{
if (!is_readable($path))
{
fail('Konfiguration nicht lesbar: '.$path);
}
$result = array();
foreach (file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $line)
{
$line = trim($line);
if ($line === '' || $line[0] === '#')
{
continue;
}
if (!preg_match('/^([A-Z0-9_]+)=(.*)$/', $line, $matches))
{
continue;
}
$value = trim($matches[2]);
if (strlen($value) >= 2)
{
$first = $value[0];
$last = $value[strlen($value)-1];
if (($first === '"' && $last === '"') || ($first === "'" && $last === "'"))
{
$value = substr($value, 1, -1);
}
}
$result[$matches[1]] = $value;
}
return $result;
}
function runCommand(array $command, $allowFailure = false)
{
$spec = array(
0 => array('file', '/dev/null', 'r'),
1 => array('pipe', 'w'),
2 => array('pipe', 'w'),
);
$process = proc_open($command, $spec, $pipes);
if (!is_resource($process))
{
fail('Prozess konnte nicht gestartet werden: '.implode(' ', $command));
}
$stdout = stream_get_contents($pipes[1]);
$stderr = stream_get_contents($pipes[2]);
fclose($pipes[1]);
fclose($pipes[2]);
$exit = proc_close($process);
if ($exit !== 0 && !$allowFailure)
{
$detail = trim($stderr) !== '' ? trim($stderr) : trim($stdout);
fail('Befehl fehlgeschlagen ('.$exit.'): '.implode(' ', $command).($detail !== '' ? "\n".$detail : ''));
}
return array('exit'=>$exit, 'stdout'=>(string)$stdout, 'stderr'=>(string)$stderr);
}
function decryptConnectorSecret($blob, $hexKey)
{
if (!preg_match('/^[a-f0-9]{64}$/', $hexKey))
{
fail('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('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('Connector-Zugangsdaten konnten nicht entschluesselt werden.');
}
return (string)$plain;
}
function sqlEscape(mysqli $db, $value)
{
return $db->real_escape_string((string)$value);
}
function saveTakeoverResult(mysqli $db, $table, $connectionId, array $config, $state, $enabled)
{
$json = json_encode($config, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
if (!is_string($json))
{
fail('Connector-Status konnte nicht serialisiert werden.');
}
$now = date('Y-m-d H:i:s');
$sql = "UPDATE `".$table."` SET takeover_state='".sqlEscape($db, $state)."', enabled=".($enabled ? 1 : 0).", config_json='".sqlEscape($db, $json)."', updated='".sqlEscape($db, $now)."' WHERE id=".(int)$connectionId;
if (!$db->query($sql))
{
fail('Connector-Status konnte nicht gespeichert werden: '.$db->error);
}
}
$legacyTimerWasEnabled = false;
$newTimerInstalled = false;
$db = null;
$table = '';
$config = array();
try
{
if (!is_readable($dbConfig))
{
fail('Piwigo-Datenbankkonfiguration nicht lesbar: '.$dbConfig);
}
if (!is_executable($legacyRuntime))
{
fail('Bestehende Sync-Runtime fehlt: '.$legacyRuntime);
}
$conf = array();
$prefixeTable = 'piwigo_';
require $dbConfig;
foreach (array('db_host','db_user','db_password','db_base') as $key)
{
if (!isset($conf[$key]))
{
fail('Piwigo-Datenbankkonfiguration enthaelt '.$key.' nicht.');
}
}
$db = new mysqli($conf['db_host'], $conf['db_user'], $conf['db_password'], $conf['db_base']);
if ($db->connect_errno)
{
fail('Piwigo-Datenbank nicht erreichbar: '.$db->connect_error);
}
$db->set_charset('utf8mb4');
$table = $prefixeTable.'bratonien_tools_nc_connections';
$result = $db->query("SELECT id, takeover_state, enabled, config_json, secret_blob FROM `".$table."` WHERE id=".$connectionId." LIMIT 1");
if (!$result || !$result->num_rows)
{
fail('Connector-Verbindung #'.$connectionId.' wurde nicht gefunden.');
}
$row = $result->fetch_assoc();
if ((string)$row['takeover_state'] !== 'ready' || (int)$row['enabled'] !== 0)
{
fail('Connector-Verbindung muss im Zustand ready und deaktiviert sein.');
}
$config = json_decode((string)$row['config_json'], true);
if (!is_array($config) || empty($config['verification']['ok']))
{
fail('Connector-Verbindung besitzt keine erfolgreiche Verifikation.');
}
$keyResult = $db->query("SELECT value FROM `".$prefixeTable."config` WHERE param='bratonien_nc_connector_secret' LIMIT 1");
if (!$keyResult || !$keyResult->num_rows)
{
fail('Connector-Schluessel wurde in Piwigo nicht gefunden.');
}
$keyRow = $keyResult->fetch_assoc();
$dbPassword = decryptConnectorSecret($row['secret_blob'], (string)$keyRow['value']);
$legacy = readKeyValueFile($legacyConfig);
$piwigoUser = trim((string)($legacy['PIWIGO_SYNC_USER'] ?? ''));
$piwigoPasswordFile = trim((string)($legacy['PIWIGO_SYNC_PASSWORD_FILE'] ?? '/etc/piwigo-sync/piwigo-password'));
if ($piwigoUser === '' || !is_readable($piwigoPasswordFile))
{
fail('Legacy-Piwigo-Sync-Zugangsdaten konnten fuer den einmaligen Cutover nicht gelesen werden.');
}
$piwigoPassword = trim((string)file_get_contents($piwigoPasswordFile));
if ($piwigoPassword === '')
{
fail('Legacy-Piwigo-Sync-Passwort ist leer.');
}
foreach (array('host','port','database','user','source_view','gallery_root','state_dir') as $key)
{
if (!isset($config[$key]) || trim((string)$config[$key]) === '')
{
fail('Connector-Konfiguration ist unvollstaendig: '.$key.' fehlt.');
}
}
$runtimeDir = '/etc/bratonien-tools/nc-connector';
if (!is_dir($runtimeDir) && !mkdir($runtimeDir, 0700, true))
{
fail('Connector-Laufzeitverzeichnis konnte nicht angelegt werden.');
}
chmod($runtimeDir, 0700);
$base = $runtimeDir.'/connection-'.$connectionId;
$dbPasswordPath = $base.'.db-password';
$piwigoPasswordPath = $base.'.piwigo-password';
$storagePath = $base.'.storages.tsv';
$configPath = $base.'.conf';
$statusPath = rtrim((string)$config['state_dir'], '/').'/connector-status.json';
file_put_contents($dbPasswordPath, $dbPassword."\n", LOCK_EX);
file_put_contents($piwigoPasswordPath, $piwigoPassword."\n", LOCK_EX);
chmod($dbPasswordPath, 0600);
chmod($piwigoPasswordPath, 0600);
$storageLines = array('# storage_id<TAB>source_prefix<TAB>local_mount');
foreach ((array)($config['storages'] ?? array()) as $storage)
{
$storageLines[] = (string)($storage['storage_id'] ?? '')."\t".(string)($storage['source_prefix'] ?? '')."\t".(string)($storage['local_mount'] ?? '');
}
file_put_contents($storagePath, implode("\n", $storageLines)."\n", LOCK_EX);
chmod($storagePath, 0600);
$piwigoRootConfigured = isset($legacy['PIWIGO_ROOT']) && trim((string)$legacy['PIWIGO_ROOT']) !== '' ? trim((string)$legacy['PIWIGO_ROOT']) : $piwigoRoot;
$lines = array(
'PIWIGO_ROOT='.$piwigoRootConfigured,
'GALLERY_ROOT='.(string)$config['gallery_root'],
'STATE_DIR='.(string)$config['state_dir'],
'STATUS_FILE='.$statusPath,
'NC_DB_HOST='.(string)$config['host'],
'NC_DB_PORT='.(string)$config['port'],
'NC_DB_NAME='.(string)$config['database'],
'NC_DB_USER='.(string)$config['user'],
'NC_DB_VIEW='.(string)$config['source_view'],
'NC_DB_PASSWORD_FILE='.$dbPasswordPath,
'STORAGE_CONFIG='.$storagePath,
'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),
'PIWIGO_SYNC_ENABLED=1',
'PIWIGO_SYNC_USER='.$piwigoUser,
'PIWIGO_SYNC_PASSWORD_FILE='.$piwigoPasswordPath,
);
file_put_contents($configPath, implode("\n", $lines)."\n", LOCK_EX);
chmod($configPath, 0600);
$enabledCheck = runCommand(array('systemctl', 'is-enabled', $legacyTimer), true);
$legacyTimerWasEnabled = $enabledCheck['exit'] === 0;
echo "Stoppe Legacy-Timer...\n";
runCommand(array('systemctl', 'stop', $legacyTimer));
$deadline = time() + 120;
do
{
$active = runCommand(array('systemctl', 'is-active', '--quiet', 'piwigo-sync.service'), true);
if ($active['exit'] !== 0)
{
break;
}
if (time() >= $deadline)
{
fail('Ein laufender Legacy-Sync wurde nach 120 Sekunden nicht beendet.');
}
sleep(2);
}
while (true);
@unlink($statusPath);
echo "Fuehre ersten Connector-Lauf aus...\n";
$firstRun = runCommand(array('env', 'PIWIGO_CONFIG='.$configPath, $legacyRuntime), true);
if ($firstRun['exit'] !== 0)
{
$detail = trim($firstRun['stderr']) !== '' ? trim($firstRun['stderr']) : trim($firstRun['stdout']);
fail('Erster Connector-Lauf ist technisch fehlgeschlagen'.($detail !== '' ? ': '.$detail : '.'));
}
$runResult = 'no_changes';
$statusState = '';
$statusMessage = '';
if (is_readable($statusPath))
{
$status = json_decode((string)file_get_contents($statusPath), true);
if (is_array($status))
{
$statusState = trim((string)($status['state'] ?? ''));
$statusMessage = trim((string)($status['message'] ?? ''));
}
$legacyNoChangeMessage = 'Synchronisierung fehlgeschlagen; bestehende Galerie blieb unverändert';
if ($statusState === 'error' && $statusMessage !== $legacyNoChangeMessage)
{
fail('Erster Connector-Lauf meldete einen technischen Fehler'.($statusMessage !== '' ? ': '.$statusMessage : '.'));
}
if ($statusState === 'ok')
{
$runResult = 'changed';
}
elseif ($statusState === 'error' && $statusMessage === $legacyNoChangeMessage)
{
$runResult = 'no_changes';
echo "Hinweis: Legacy-Runtime hat den erwarteten Activity-Gate-No-Op faelschlich als error markiert; Exit-Code 0 bestaetigt den erfolgreichen No-Change-Lauf.\n";
}
}
echo 'Erster Lauf Exit-Code: '.$firstRun['exit']."\n";
echo 'Connector-Status: '.($statusState !== '' ? $statusState : 'kein Abschlussstatus').($statusMessage !== '' ? ' - '.$statusMessage : '')."\n";
echo 'Bewertung: '.$runResult."\n";
$servicePath = '/etc/systemd/system/'.$newService;
$timerPath = '/etc/systemd/system/'.$newTimer;
$service = "[Unit]\nDescription=Bratonien NC Connector Sync\nAfter=network-online.target\nWants=network-online.target\n\n[Service]\nType=oneshot\nEnvironment=PIWIGO_CONFIG=".$configPath."\nExecStart=".$legacyRuntime."\n\n";
$timer = "[Unit]\nDescription=Bratonien NC Connector regelmaessig pruefen\n\n[Timer]\nOnBootSec=3min\nOnUnitActiveSec=1min\nRandomizedDelaySec=15s\nPersistent=true\n\n[Install]\nWantedBy=timers.target\n";
file_put_contents($servicePath, $service, LOCK_EX);
file_put_contents($timerPath, $timer, LOCK_EX);
chmod($servicePath, 0644);
chmod($timerPath, 0644);
$newTimerInstalled = true;
runCommand(array('systemctl', 'daemon-reload'));
runCommand(array('systemctl', 'disable', $legacyTimer), true);
runCommand(array('systemctl', 'enable', '--now', $newTimer));
$config['takeover']['cutover_at'] = date('Y-m-d H:i:s');
$config['takeover']['legacy_timer_disabled'] = true;
$config['takeover']['connector_timer'] = $newTimer;
$config['takeover']['runtime'] = 'legacy-runtime-transition';
$config['takeover']['first_run'] = array(
'state' => 'success',
'result' => $runResult,
'status_state' => $statusState,
'status_message' => $statusMessage,
'checked_at' => date('Y-m-d H:i:s'),
);
saveTakeoverResult($db, $table, $connectionId, $config, 'active', true);
echo "Cutover erfolgreich.\n";
echo "Erster Connector-Lauf: ".$runResult."\n";
echo "Legacy-Timer ist deaktiviert; ".$newTimer." ist aktiv.\n";
echo "Die bisherige Sync-Runtime bleibt fuer diesen Uebergangsschritt noch als Laufzeit erhalten.\n";
}
catch (Throwable $e)
{
if ($db instanceof mysqli && $table !== '' && $config)
{
try
{
$config['takeover']['first_run'] = array(
'state' => 'error',
'result' => 'error',
'checked_at' => date('Y-m-d H:i:s'),
'message' => substr($e->getMessage(), 0, 500),
);
saveTakeoverResult($db, $table, $connectionId, $config, 'ready', false);
}
catch (Throwable $ignored)
{
}
}
if ($newTimerInstalled)
{
runCommand(array('systemctl', 'disable', '--now', $newTimer), true);
}
if ($legacyTimerWasEnabled)
{
runCommand(array('systemctl', 'enable', '--now', $legacyTimer), true);
}
else
{
runCommand(array('systemctl', 'start', $legacyTimer), true);
}
fwrite(STDERR, "Cutover fehlgeschlagen: ".$e->getMessage()."\n");
fwrite(STDERR, "Legacy-Timer wurde wieder aktiviert/gestartet.\n");
exit(1);
}

View File

@@ -1,374 +0,0 @@
#!/usr/bin/env php
<?php
if (PHP_SAPI !== 'cli')
{
fwrite(STDERR, "Dieses Hilfsprogramm darf nur auf der Kommandozeile ausgefuehrt werden.\n");
exit(1);
}
if (function_exists('posix_geteuid') && posix_geteuid() !== 0)
{
fwrite(STDERR, "Bitte als root ausfuehren.\n");
exit(1);
}
if ($argc !== 2 || !preg_match('/^[1-9][0-9]*$/', $argv[1]))
{
fwrite(STDERR, "Aufruf: sudo php nc-connector-cutover.php <connection-id>\n");
exit(1);
}
$connectionId = (int)$argv[1];
$piwigoRoot = dirname(__DIR__, 2);
$dbConfig = $piwigoRoot.'/local/config/database.inc.php';
$legacyConfig = '/etc/piwigo-sync/piwigo.conf';
$legacyRuntime = '/opt/piwigo-sync/sync.sh';
$newTimer = 'bratonien-nc-connector.timer';
$newService = 'bratonien-nc-connector.service';
$legacyTimer = 'piwigo-sync.timer';
function fail($message)
{
throw new RuntimeException($message);
}
function readKeyValueFile($path)
{
if (!is_readable($path))
{
fail('Konfiguration nicht lesbar: '.$path);
}
$result = array();
foreach (file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $line)
{
$line = trim($line);
if ($line === '' || $line[0] === '#')
{
continue;
}
if (!preg_match('/^([A-Z0-9_]+)=(.*)$/', $line, $matches))
{
continue;
}
$value = trim($matches[2]);
if (strlen($value) >= 2)
{
$first = $value[0];
$last = $value[strlen($value)-1];
if (($first === '"' && $last === '"') || ($first === "'" && $last === "'"))
{
$value = substr($value, 1, -1);
}
}
$result[$matches[1]] = $value;
}
return $result;
}
function runCommand(array $command, $allowFailure = false)
{
$spec = array(
0 => array('file', '/dev/null', 'r'),
1 => array('pipe', 'w'),
2 => array('pipe', 'w'),
);
$process = proc_open($command, $spec, $pipes);
if (!is_resource($process))
{
fail('Prozess konnte nicht gestartet werden: '.implode(' ', $command));
}
$stdout = stream_get_contents($pipes[1]);
$stderr = stream_get_contents($pipes[2]);
fclose($pipes[1]);
fclose($pipes[2]);
$exit = proc_close($process);
if ($exit !== 0 && !$allowFailure)
{
$detail = trim($stderr) !== '' ? trim($stderr) : trim($stdout);
fail('Befehl fehlgeschlagen ('.$exit.'): '.implode(' ', $command).($detail !== '' ? "\n".$detail : ''));
}
return array('exit'=>$exit, 'stdout'=>(string)$stdout, 'stderr'=>(string)$stderr);
}
function decryptConnectorSecret($blob, $hexKey)
{
if (!preg_match('/^[a-f0-9]{64}$/', $hexKey))
{
fail('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('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('Connector-Zugangsdaten konnten nicht entschluesselt werden.');
}
return (string)$plain;
}
function sqlEscape(mysqli $db, $value)
{
return $db->real_escape_string((string)$value);
}
function saveTakeoverResult(mysqli $db, $table, $connectionId, array $config, $state, $enabled)
{
$json = json_encode($config, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
if (!is_string($json))
{
fail('Connector-Status konnte nicht serialisiert werden.');
}
$now = date('Y-m-d H:i:s');
$sql = "UPDATE `".$table."` SET takeover_state='".sqlEscape($db, $state)."', enabled=".($enabled ? 1 : 0).", config_json='".sqlEscape($db, $json)."', updated='".sqlEscape($db, $now)."' WHERE id=".(int)$connectionId;
if (!$db->query($sql))
{
fail('Connector-Status konnte nicht gespeichert werden: '.$db->error);
}
}
$legacyTimerWasEnabled = false;
$newTimerInstalled = false;
$db = null;
$table = '';
$config = array();
try
{
if (!is_readable($dbConfig))
{
fail('Piwigo-Datenbankkonfiguration nicht lesbar: '.$dbConfig);
}
if (!is_executable($legacyRuntime))
{
fail('Bestehende Sync-Runtime fehlt: '.$legacyRuntime);
}
$conf = array();
$prefixeTable = 'piwigo_';
require $dbConfig;
foreach (array('db_host','db_user','db_password','db_base') as $key)
{
if (!isset($conf[$key]))
{
fail('Piwigo-Datenbankkonfiguration enthaelt '.$key.' nicht.');
}
}
$db = new mysqli($conf['db_host'], $conf['db_user'], $conf['db_password'], $conf['db_base']);
if ($db->connect_errno)
{
fail('Piwigo-Datenbank nicht erreichbar: '.$db->connect_error);
}
$db->set_charset('utf8mb4');
$table = $prefixeTable.'bratonien_tools_nc_connections';
$result = $db->query("SELECT id, takeover_state, enabled, config_json, secret_blob FROM `".$table."` WHERE id=".$connectionId." LIMIT 1");
if (!$result || !$result->num_rows)
{
fail('Connector-Verbindung #'.$connectionId.' wurde nicht gefunden.');
}
$row = $result->fetch_assoc();
if ((string)$row['takeover_state'] !== 'ready' || (int)$row['enabled'] !== 0)
{
fail('Connector-Verbindung muss im Zustand ready und deaktiviert sein.');
}
$config = json_decode((string)$row['config_json'], true);
if (!is_array($config) || empty($config['verification']['ok']))
{
fail('Connector-Verbindung besitzt keine erfolgreiche Verifikation.');
}
$keyResult = $db->query("SELECT value FROM `".$prefixeTable."config` WHERE param='bratonien_nc_connector_secret' LIMIT 1");
if (!$keyResult || !$keyResult->num_rows)
{
fail('Connector-Schluessel wurde in Piwigo nicht gefunden.');
}
$keyRow = $keyResult->fetch_assoc();
$dbPassword = decryptConnectorSecret($row['secret_blob'], (string)$keyRow['value']);
$legacy = readKeyValueFile($legacyConfig);
$piwigoUser = trim((string)($legacy['PIWIGO_SYNC_USER'] ?? ''));
$piwigoPasswordFile = trim((string)($legacy['PIWIGO_SYNC_PASSWORD_FILE'] ?? '/etc/piwigo-sync/piwigo-password'));
if ($piwigoUser === '' || !is_readable($piwigoPasswordFile))
{
fail('Legacy-Piwigo-Sync-Zugangsdaten konnten fuer den einmaligen Cutover nicht gelesen werden.');
}
$piwigoPassword = trim((string)file_get_contents($piwigoPasswordFile));
if ($piwigoPassword === '')
{
fail('Legacy-Piwigo-Sync-Passwort ist leer.');
}
foreach (array('host','port','database','user','source_view','gallery_root','state_dir') as $key)
{
if (!isset($config[$key]) || trim((string)$config[$key]) === '')
{
fail('Connector-Konfiguration ist unvollstaendig: '.$key.' fehlt.');
}
}
$runtimeDir = '/etc/bratonien-tools/nc-connector';
if (!is_dir($runtimeDir) && !mkdir($runtimeDir, 0700, true))
{
fail('Connector-Laufzeitverzeichnis konnte nicht angelegt werden.');
}
chmod($runtimeDir, 0700);
$base = $runtimeDir.'/connection-'.$connectionId;
$dbPasswordPath = $base.'.db-password';
$piwigoPasswordPath = $base.'.piwigo-password';
$storagePath = $base.'.storages.tsv';
$configPath = $base.'.conf';
$statusPath = rtrim((string)$config['state_dir'], '/').'/connector-status.json';
file_put_contents($dbPasswordPath, $dbPassword."\n", LOCK_EX);
file_put_contents($piwigoPasswordPath, $piwigoPassword."\n", LOCK_EX);
chmod($dbPasswordPath, 0600);
chmod($piwigoPasswordPath, 0600);
$storageLines = array('# storage_id<TAB>source_prefix<TAB>local_mount');
foreach ((array)($config['storages'] ?? array()) as $storage)
{
$storageLines[] = (string)($storage['storage_id'] ?? '')."\t".(string)($storage['source_prefix'] ?? '')."\t".(string)($storage['local_mount'] ?? '');
}
file_put_contents($storagePath, implode("\n", $storageLines)."\n", LOCK_EX);
chmod($storagePath, 0600);
$piwigoRootConfigured = isset($legacy['PIWIGO_ROOT']) && trim((string)$legacy['PIWIGO_ROOT']) !== '' ? trim((string)$legacy['PIWIGO_ROOT']) : $piwigoRoot;
$lines = array(
'PIWIGO_ROOT='.$piwigoRootConfigured,
'GALLERY_ROOT='.(string)$config['gallery_root'],
'STATE_DIR='.(string)$config['state_dir'],
'STATUS_FILE='.$statusPath,
'NC_DB_HOST='.(string)$config['host'],
'NC_DB_PORT='.(string)$config['port'],
'NC_DB_NAME='.(string)$config['database'],
'NC_DB_USER='.(string)$config['user'],
'NC_DB_VIEW='.(string)$config['source_view'],
'NC_DB_PASSWORD_FILE='.$dbPasswordPath,
'STORAGE_CONFIG='.$storagePath,
'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),
'PIWIGO_SYNC_ENABLED=1',
'PIWIGO_SYNC_USER='.$piwigoUser,
'PIWIGO_SYNC_PASSWORD_FILE='.$piwigoPasswordPath,
);
file_put_contents($configPath, implode("\n", $lines)."\n", LOCK_EX);
chmod($configPath, 0600);
$enabledCheck = runCommand(array('systemctl', 'is-enabled', $legacyTimer), true);
$legacyTimerWasEnabled = $enabledCheck['exit'] === 0;
echo "Stoppe Legacy-Timer...\n";
runCommand(array('systemctl', 'stop', $legacyTimer));
$deadline = time() + 120;
do
{
$active = runCommand(array('systemctl', 'is-active', '--quiet', 'piwigo-sync.service'), true);
if ($active['exit'] !== 0)
{
break;
}
if (time() >= $deadline)
{
fail('Ein laufender Legacy-Sync wurde nach 120 Sekunden nicht beendet.');
}
sleep(2);
}
while (true);
@unlink($statusPath);
echo "Fuehre ersten Connector-Lauf aus...\n";
$firstRun = runCommand(array('env', 'PIWIGO_CONFIG='.$configPath, $legacyRuntime), true);
if ($firstRun['exit'] !== 0)
{
$detail = trim($firstRun['stderr']) !== '' ? trim($firstRun['stderr']) : trim($firstRun['stdout']);
fail('Erster Connector-Lauf ist technisch fehlgeschlagen'.($detail !== '' ? ': '.$detail : '.'));
}
$runResult = 'no_changes';
if (is_readable($statusPath))
{
$status = json_decode((string)file_get_contents($statusPath), true);
if (!is_array($status) || (string)($status['state'] ?? '') !== 'ok')
{
fail('Erster Connector-Lauf lieferte keinen gueltigen Erfolgsstatus.');
}
$runResult = 'changed';
}
$servicePath = '/etc/systemd/system/'.$newService;
$timerPath = '/etc/systemd/system/'.$newTimer;
$service = "[Unit]\nDescription=Bratonien NC Connector Sync\nAfter=network-online.target\nWants=network-online.target\n\n[Service]\nType=oneshot\nEnvironment=PIWIGO_CONFIG=".$configPath."\nExecStart=".$legacyRuntime."\n\n";
$timer = "[Unit]\nDescription=Bratonien NC Connector regelmaessig pruefen\n\n[Timer]\nOnBootSec=3min\nOnUnitActiveSec=1min\nRandomizedDelaySec=15s\nPersistent=true\n\n[Install]\nWantedBy=timers.target\n";
file_put_contents($servicePath, $service, LOCK_EX);
file_put_contents($timerPath, $timer, LOCK_EX);
chmod($servicePath, 0644);
chmod($timerPath, 0644);
$newTimerInstalled = true;
runCommand(array('systemctl', 'daemon-reload'));
runCommand(array('systemctl', 'disable', $legacyTimer), true);
runCommand(array('systemctl', 'enable', '--now', $newTimer));
$config['takeover']['cutover_at'] = date('Y-m-d H:i:s');
$config['takeover']['legacy_timer_disabled'] = true;
$config['takeover']['connector_timer'] = $newTimer;
$config['takeover']['runtime'] = 'legacy-runtime-transition';
$config['takeover']['first_run'] = array(
'state' => 'success',
'result' => $runResult,
'checked_at' => date('Y-m-d H:i:s'),
);
saveTakeoverResult($db, $table, $connectionId, $config, 'active', true);
echo "Cutover erfolgreich.\n";
echo "Erster Connector-Lauf: ".$runResult."\n";
echo "Legacy-Timer ist deaktiviert; ".$newTimer." ist aktiv.\n";
echo "Die bisherige Sync-Runtime bleibt fuer diesen Uebergangsschritt noch als Laufzeit erhalten.\n";
}
catch (Throwable $e)
{
if ($db instanceof mysqli && $table !== '' && $config)
{
try
{
$config['takeover']['first_run'] = array(
'state' => 'error',
'result' => 'error',
'checked_at' => date('Y-m-d H:i:s'),
'message' => substr($e->getMessage(), 0, 500),
);
saveTakeoverResult($db, $table, $connectionId, $config, 'ready', false);
}
catch (Throwable $ignored)
{
}
}
if ($newTimerInstalled)
{
runCommand(array('systemctl', 'disable', '--now', $newTimer), true);
}
if ($legacyTimerWasEnabled)
{
runCommand(array('systemctl', 'enable', '--now', $legacyTimer), true);
}
else
{
runCommand(array('systemctl', 'start', $legacyTimer), true);
}
fwrite(STDERR, "Cutover fehlgeschlagen: ".$e->getMessage()."\n");
fwrite(STDERR, "Legacy-Timer wurde wieder aktiviert/gestartet.\n");
exit(1);
}

View File

@@ -1,110 +0,0 @@
#!/usr/bin/env php
<?php
if (PHP_SAPI !== 'cli')
{
fwrite(STDERR, "Dieses Hilfsprogramm darf nur auf der Kommandozeile ausgefuehrt werden.\n");
exit(1);
}
if (function_exists('posix_geteuid') && posix_geteuid() !== 0)
{
fwrite(STDERR, "Bitte als root ausfuehren.\n");
exit(1);
}
if ($argc !== 2 || !preg_match('/^[1-9][0-9]*$/', $argv[1]))
{
fwrite(STDERR, "Aufruf: php nc-connector-diagnose.php <connection-id>\n");
exit(1);
}
$connectionId = (int)$argv[1];
$configPath = '/etc/bratonien-tools/nc-connector/connection-'.$connectionId.'.conf';
$runtime = '/opt/piwigo-sync/sync.sh';
$legacyTimer = 'piwigo-sync.timer';
$legacyService = 'piwigo-sync.service';
function runCommand(array $command, $allowFailure = false)
{
$spec = array(
0 => array('file', '/dev/null', 'r'),
1 => array('pipe', 'w'),
2 => array('pipe', 'w'),
);
$process = proc_open($command, $spec, $pipes);
if (!is_resource($process))
{
throw new RuntimeException('Prozess konnte nicht gestartet werden: '.implode(' ', $command));
}
$stdout = stream_get_contents($pipes[1]);
$stderr = stream_get_contents($pipes[2]);
fclose($pipes[1]);
fclose($pipes[2]);
$exit = proc_close($process);
if ($exit !== 0 && !$allowFailure)
{
throw new RuntimeException('Befehl fehlgeschlagen: '.implode(' ', $command));
}
return array('exit'=>$exit, 'stdout'=>(string)$stdout, 'stderr'=>(string)$stderr);
}
$timerWasEnabled = false;
try
{
if (!is_readable($configPath))
{
throw new RuntimeException('Connector-Konfiguration fehlt oder ist nicht lesbar: '.$configPath.'. Fuehre zuerst den Cutover-Versuch mindestens einmal aus, damit die Laufzeitkonfiguration erzeugt wird.');
}
if (!is_executable($runtime))
{
throw new RuntimeException('Sync-Runtime fehlt: '.$runtime);
}
$enabled = runCommand(array('systemctl', 'is-enabled', $legacyTimer), true);
$timerWasEnabled = $enabled['exit'] === 0;
echo "Stoppe Legacy-Timer fuer die Diagnose...\n";
runCommand(array('systemctl', 'stop', $legacyTimer), true);
$deadline = time() + 120;
while (true)
{
$active = runCommand(array('systemctl', 'is-active', '--quiet', $legacyService), true);
if ($active['exit'] !== 0)
{
break;
}
if (time() >= $deadline)
{
throw new RuntimeException('Ein laufender Legacy-Sync wurde nach 120 Sekunden nicht beendet.');
}
sleep(2);
}
echo "Fuehre Connector-Lauf im Diagnosemodus aus...\n\n";
$result = runCommand(array('env', 'PIWIGO_CONFIG='.$configPath, 'bash', '-x', $runtime), true);
echo "===== STDOUT =====\n";
echo trim($result['stdout'])."\n";
echo "===== STDERR / TRACE =====\n";
echo trim($result['stderr'])."\n";
echo "===== ENDE =====\n";
echo 'Exit-Code: '.$result['exit']."\n";
}
catch (Throwable $e)
{
fwrite(STDERR, 'Diagnose fehlgeschlagen: '.$e->getMessage()."\n");
}
finally
{
if ($timerWasEnabled)
{
runCommand(array('systemctl', 'enable', '--now', $legacyTimer), true);
}
else
{
runCommand(array('systemctl', 'start', $legacyTimer), true);
}
echo "Legacy-Timer wurde nach der Diagnose wieder aktiviert/gestartet.\n";
}

View File

@@ -1,81 +0,0 @@
#!/usr/bin/env php
<?php
if (PHP_SAPI !== 'cli')
{
fwrite(STDERR, "Dieses Hilfsprogramm darf nur auf der Kommandozeile ausgefuehrt werden.\n");
exit(1);
}
if (function_exists('posix_geteuid') && posix_geteuid() !== 0)
{
fwrite(STDERR, "Bitte als root ausfuehren.\n");
exit(1);
}
if ($argc !== 2 || !preg_match('/^[1-9][0-9]*$/', $argv[1]))
{
fwrite(STDERR, "Aufruf: php nc-connector-disable.php <connection-id>\n");
exit(1);
}
$id = (int)$argv[1];
$piwigoRoot = dirname(__DIR__, 2);
$dbConfig = $piwigoRoot.'/local/config/database.inc.php';
$configDir = '/etc/bratonien-tools/nc-connector';
try
{
$conf = array();
$prefixeTable = 'piwigo_';
if (!is_readable($dbConfig)) throw new RuntimeException('Piwigo-Datenbankkonfiguration nicht lesbar.');
require $dbConfig;
$db = new mysqli($conf['db_host'], $conf['db_user'], $conf['db_password'], $conf['db_base']);
if ($db->connect_errno) throw new RuntimeException('Piwigo-Datenbank nicht erreichbar: '.$db->connect_error);
$db->set_charset('utf8mb4');
$table = $prefixeTable.'bratonien_tools_nc_connections';
$result = $db->query("SELECT id, enabled, takeover_state, config_json FROM `".$table."` WHERE id=".$id." LIMIT 1");
if (!$result || !$result->num_rows) throw new RuntimeException('Connector-Verbindung #'.$id.' wurde nicht gefunden.');
$row = $result->fetch_assoc();
if ((int)$row['enabled'] !== 1 || (string)$row['takeover_state'] !== 'active')
{
throw new RuntimeException('Die Verbindung ist nicht aktiv.');
}
passthru('systemctl stop bratonien-nc-connector.timer', $stopExit);
if ($stopExit !== 0) throw new RuntimeException('Connector-Timer konnte nicht gestoppt werden.');
$base = $configDir.'/connection-'.$id;
foreach (array('.conf','.storages.tsv','.db-password','.piwigo-password') as $suffix)
{
$path = $base.$suffix;
if (is_file($path) && !unlink($path)) throw new RuntimeException('Datei konnte nicht entfernt werden: '.$path);
}
$config = json_decode((string)$row['config_json'], true);
if (!is_array($config)) $config = array();
unset($config['runtime']);
$json = json_encode($config, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$now = date('Y-m-d H:i:s');
$jsonEsc = $db->real_escape_string((string)$json);
$nowEsc = $db->real_escape_string($now);
if (!$db->query("UPDATE `".$table."` SET enabled=0, takeover_state='disabled', config_json='".$jsonEsc."', updated='".$nowEsc."' WHERE id=".$id))
{
throw new RuntimeException('Connector-Status konnte nicht gespeichert werden: '.$db->error);
}
$remaining = glob($configDir.'/connection-*.conf') ?: array();
if ($remaining)
{
passthru('systemctl start bratonien-nc-connector.timer', $startExit);
if ($startExit !== 0) throw new RuntimeException('Connector-Timer konnte nicht wieder gestartet werden.');
echo "Verbindung #".$id." deaktiviert. Andere Connector-Verbindungen bleiben aktiv.\n";
}
else
{
passthru('systemctl disable bratonien-nc-connector.timer', $disableExit);
echo "Verbindung #".$id." deaktiviert. Es gibt keine weitere aktive Connector-Verbindung; der Timer bleibt gestoppt.\n";
}
}
catch (Throwable $e)
{
fwrite(STDERR, $e->getMessage()."\n");
exit(1);
}

View File

@@ -1,221 +0,0 @@
#!/usr/bin/env php
<?php
if (PHP_SAPI !== 'cli')
{
fwrite(STDERR, "Dieses Hilfsprogramm darf nur auf der Kommandozeile ausgefuehrt werden.\n");
exit(1);
}
if (function_exists('posix_geteuid') && posix_geteuid() !== 0)
{
fwrite(STDERR, "Bitte als root ausfuehren.\n");
exit(1);
}
if ($argc !== 2 || !preg_match('/^[1-9][0-9]*$/', $argv[1]))
{
fwrite(STDERR, "Aufruf: php nc-connector-install.php <connection-id>\n");
exit(1);
}
$id = (int)$argv[1];
$pluginRoot = __DIR__;
$piwigoRoot = dirname(__DIR__, 2);
$dbConfig = $piwigoRoot.'/local/config/database.inc.php';
$configDir = '/etc/bratonien-tools/nc-connector';
$stateRoot = '/var/lib/bratonien-tools/nc-connector';
$servicePath = '/etc/systemd/system/bratonien-nc-connector.service';
$timerPath = '/etc/systemd/system/bratonien-nc-connector.timer';
function fail_install($message)
{
throw new RuntimeException($message);
}
function run_install(array $command, $allowFailure = false)
{
$spec = array(
0 => array('file', '/dev/null', 'r'),
1 => array('pipe', 'w'),
2 => array('pipe', 'w'),
);
$process = proc_open($command, $spec, $pipes);
if (!is_resource($process))
{
fail_install('Prozess konnte nicht gestartet werden: '.implode(' ', $command));
}
$stdout = stream_get_contents($pipes[1]);
$stderr = stream_get_contents($pipes[2]);
fclose($pipes[1]);
fclose($pipes[2]);
$exit = proc_close($process);
if ($exit !== 0 && !$allowFailure)
{
$detail = trim($stderr) !== '' ? trim($stderr) : trim($stdout);
fail_install('Befehl fehlgeschlagen ('.$exit.'): '.implode(' ', $command).($detail !== '' ? "\n".$detail : ''));
}
return array('exit'=>$exit, 'stdout'=>(string)$stdout, 'stderr'=>(string)$stderr);
}
function decrypt_install_credentials($blob, $hexKey)
{
if (!preg_match('/^[a-f0-9]{64}$/', $hexKey))
{
fail_install('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_install('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_install('Connector-Zugangsdaten konnten nicht entschluesselt werden.');
}
$decoded = json_decode($plain, true);
if (!is_array($decoded) || empty($decoded['db_password']) || empty($decoded['piwigo_user']) || empty($decoded['piwigo_password']))
{
fail_install('Fuer eine native Aktivierung muessen Datenbank- und Piwigo-Zugangsdaten vollstaendig gespeichert sein.');
}
return $decoded;
}
function sql_install(mysqli $db, $value)
{
return $db->real_escape_string((string)$value);
}
try
{
if (!is_readable($dbConfig))
{
fail_install('Piwigo-Datenbankkonfiguration 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_install('Piwigo-Datenbankkonfiguration enthaelt '.$key.' nicht.');
}
$db = new mysqli($conf['db_host'], $conf['db_user'], $conf['db_password'], $conf['db_base']);
if ($db->connect_errno) fail_install('Piwigo-Datenbank nicht erreichbar: '.$db->connect_error);
$db->set_charset('utf8mb4');
$table = $prefixeTable.'bratonien_tools_nc_connections';
$result = $db->query("SELECT id, name, adapter, enabled, takeover_state, config_json, secret_blob FROM `".$table."` WHERE id=".$id." LIMIT 1");
if (!$result || !$result->num_rows) fail_install('Connector-Verbindung #'.$id.' wurde nicht gefunden.');
$row = $result->fetch_assoc();
if ((string)$row['adapter'] !== 'local') fail_install('Native Aktivierung ist derzeit nur fuer lokale Verbindungen verfuegbar.');
if ((string)$row['takeover_state'] !== 'verified' || (int)$row['enabled'] !== 0)
{
fail_install('Die Verbindung muss zuerst erfolgreich verifiziert und deaktiviert sein.');
}
$config = json_decode((string)$row['config_json'], true);
if (!is_array($config) || empty($config['verification']['ok'])) fail_install('Erfolgreiche Verifikation fehlt.');
foreach (array('host','port','database','user','source_view','activity_view','gallery_root') as $key)
{
if (trim((string)($config[$key] ?? '')) === '') fail_install('Connector-Konfiguration ist unvollstaendig: '.$key.' fehlt.');
}
$keyResult = $db->query("SELECT value FROM `".$prefixeTable."config` WHERE param='bratonien_nc_connector_secret' LIMIT 1");
if (!$keyResult || !$keyResult->num_rows) fail_install('Connector-Schluessel wurde in Piwigo nicht gefunden.');
$keyRow = $keyResult->fetch_assoc();
$credentials = decrypt_install_credentials((string)$row['secret_blob'], (string)$keyRow['value']);
$stateDir = $stateRoot.'/connection-'.$id;
$statusFile = $stateDir.'/connector-status.json';
if (!is_dir($configDir) && !mkdir($configDir, 0700, true)) fail_install('Konfigurationsverzeichnis konnte nicht angelegt werden.');
if (!is_dir($stateDir) && !mkdir($stateDir, 0750, true)) fail_install('State-Verzeichnis konnte nicht angelegt werden.');
chmod($configDir, 0700);
chmod($stateDir, 0750);
$base = $configDir.'/connection-'.$id;
$dbPasswordPath = $base.'.db-password';
$piwigoPasswordPath = $base.'.piwigo-password';
$storagePath = $base.'.storages.tsv';
$configPath = $base.'.conf';
file_put_contents($dbPasswordPath, (string)$credentials['db_password']."\n", LOCK_EX);
file_put_contents($piwigoPasswordPath, (string)$credentials['piwigo_password']."\n", LOCK_EX);
chmod($dbPasswordPath, 0600);
chmod($piwigoPasswordPath, 0600);
$storageLines = array('# storage_id<TAB>source_prefix<TAB>local_mount');
foreach ((array)($config['storages'] ?? array()) as $storage)
{
$storageLines[] = (string)($storage['storage_id'] ?? '')."\t".(string)($storage['source_prefix'] ?? '')."\t".(string)($storage['local_mount'] ?? '');
}
if (count($storageLines) === 1) fail_install('Keine Storage-Zuordnungen gespeichert.');
file_put_contents($storagePath, implode("\n", $storageLines)."\n", LOCK_EX);
chmod($storagePath, 0600);
$lines = array(
'PIWIGO_ROOT='.$piwigoRoot,
'GALLERY_ROOT='.(string)$config['gallery_root'],
'STATE_DIR='.$stateDir,
'STATUS_FILE='.$statusFile,
'NC_DB_HOST='.(string)$config['host'],
'NC_DB_PORT='.(string)$config['port'],
'NC_DB_NAME='.(string)$config['database'],
'NC_DB_USER='.(string)$config['user'],
'NC_DB_VIEW='.(string)$config['source_view'],
'NC_ACTIVITY_VIEW='.(string)$config['activity_view'],
'NC_DB_PASSWORD_FILE='.$dbPasswordPath,
'STORAGE_CONFIG='.$storagePath,
'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),
'PIWIGO_SYNC_ENABLED=1',
'PIWIGO_SYNC_USER='.(string)$credentials['piwigo_user'],
'PIWIGO_SYNC_PASSWORD_FILE='.$piwigoPasswordPath,
);
file_put_contents($configPath, implode("\n", $lines)."\n", LOCK_EX);
chmod($configPath, 0600);
echo "Teste Verbindung mit Plugin-Runtime...\n";
$test = run_install(array('env', 'PIWIGO_CONFIG='.$configPath, 'bash', $pluginRoot.'/runtime/sync.sh'), true);
if ($test['exit'] !== 0)
{
@unlink($configPath);
@unlink($storagePath);
@unlink($dbPasswordPath);
@unlink($piwigoPasswordPath);
$detail = trim($test['stderr']) !== '' ? trim($test['stderr']) : trim($test['stdout']);
fail_install('Runtime-Test fehlgeschlagen'.($detail !== '' ? ': '.$detail : '.'));
}
$service = "[Unit]\nDescription=Bratonien NC Connector Sync\nAfter=network-online.target\nWants=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/usr/bin/env bash ".$pluginRoot."/runtime/run-all.sh\n\n";
$timer = "[Unit]\nDescription=Bratonien NC Connector regelmaessig pruefen\n\n[Timer]\nOnBootSec=3min\nOnUnitActiveSec=1min\nRandomizedDelaySec=15s\nPersistent=true\n\n[Install]\nWantedBy=timers.target\n";
file_put_contents($servicePath, $service, LOCK_EX);
file_put_contents($timerPath, $timer, LOCK_EX);
chmod($servicePath, 0644);
chmod($timerPath, 0644);
$config['state_dir'] = $stateDir;
$config['status_file'] = $statusFile;
$config['runtime'] = array('mode'=>'plugin-runtime', 'config'=>$configPath);
$json = json_encode($config, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$now = date('Y-m-d H:i:s');
if (!$db->query("UPDATE `".$table."` SET enabled=1, takeover_state='active', config_json='".sql_install($db, $json)."', updated='".sql_install($db, $now)."' WHERE id=".$id))
{
fail_install('Connector-Status konnte nicht gespeichert werden: '.$db->error);
}
run_install(array('systemctl', 'daemon-reload'));
run_install(array('systemctl', 'enable', '--now', 'bratonien-nc-connector.timer'));
echo "Aktivierung erfolgreich.\n";
echo "Verbindung #".$id." verwendet jetzt den nativen Bratonien-Tools-State unter ".$stateDir.".\n";
echo "Der gemeinsame Connector-Timer verarbeitet alle installierten connection-*.conf Dateien.\n";
}
catch (Throwable $e)
{
fwrite(STDERR, $e->getMessage()."\n");
exit(1);
}

View File

@@ -1,183 +0,0 @@
#!/usr/bin/env php
<?php
if (PHP_SAPI !== 'cli')
{
fwrite(STDERR, "Dieses Hilfsprogramm darf nur auf der Kommandozeile ausgefuehrt werden.\n");
exit(1);
}
if (function_exists('posix_geteuid') && posix_geteuid() !== 0)
{
fwrite(STDERR, "Bitte als root ausfuehren.\n");
exit(1);
}
if ($argc !== 2 || !preg_match('/^[1-9][0-9]*$/', $argv[1]))
{
fwrite(STDERR, "Aufruf: php nc-connector-legacy-cleanup.php <connection-id>\n");
exit(1);
}
$connectionId = (int)$argv[1];
$piwigoRoot = dirname(__DIR__, 2);
$dbConfig = $piwigoRoot.'/local/config/database.inc.php';
$pluginRuntime = __DIR__.'/runtime/sync.sh';
$configPath = '/etc/bratonien-tools/nc-connector/connection-'.$connectionId.'.conf';
$connectorService = '/etc/systemd/system/bratonien-nc-connector.service';
$connectorTimer = 'bratonien-nc-connector.timer';
$legacyServiceName = 'piwigo-sync.service';
$legacyTimerName = 'piwigo-sync.timer';
$legacyServicePath = '/etc/systemd/system/'.$legacyServiceName;
$legacyTimerPath = '/etc/systemd/system/'.$legacyTimerName;
function cleanupFail($message)
{
throw new RuntimeException($message);
}
function cleanupRun(array $command, $allowFailure = false)
{
$spec = array(
0 => array('file', '/dev/null', 'r'),
1 => array('pipe', 'w'),
2 => array('pipe', 'w'),
);
$process = proc_open($command, $spec, $pipes);
if (!is_resource($process))
{
cleanupFail('Prozess konnte nicht gestartet werden: '.implode(' ', $command));
}
$stdout = stream_get_contents($pipes[1]);
$stderr = stream_get_contents($pipes[2]);
fclose($pipes[1]);
fclose($pipes[2]);
$exit = proc_close($process);
if ($exit !== 0 && !$allowFailure)
{
$detail = trim($stderr) !== '' ? trim($stderr) : trim($stdout);
cleanupFail('Befehl fehlgeschlagen ('.$exit.'): '.implode(' ', $command).($detail !== '' ? "\n".$detail : ''));
}
return array('exit'=>$exit, 'stdout'=>(string)$stdout, 'stderr'=>(string)$stderr);
}
function cleanupRemoveTree($path)
{
if (!file_exists($path) && !is_link($path))
{
return;
}
if (is_link($path) || is_file($path))
{
if (!@unlink($path))
{
cleanupFail('Datei konnte nicht entfernt werden: '.$path);
}
return;
}
$items = scandir($path);
if (!is_array($items))
{
cleanupFail('Verzeichnis konnte nicht gelesen werden: '.$path);
}
foreach ($items as $item)
{
if ($item === '.' || $item === '..')
{
continue;
}
cleanupRemoveTree($path.'/'.$item);
}
if (!@rmdir($path))
{
cleanupFail('Verzeichnis konnte nicht entfernt werden: '.$path);
}
}
try
{
foreach (array($dbConfig, $configPath, $connectorService, $pluginRuntime) as $required)
{
if (!is_readable($required))
{
cleanupFail('Erforderliche Connector-Datei fehlt oder ist nicht lesbar: '.$required);
}
}
$serviceDefinition = (string)file_get_contents($connectorService);
if (strpos($serviceDefinition, $pluginRuntime) === false)
{
cleanupFail('Der aktive Connector-Service verwendet noch nicht die Plugin-eigene Runtime. Legacy-Bestand wird nicht entfernt.');
}
$conf = array();
$prefixeTable = 'piwigo_';
require $dbConfig;
$db = new mysqli($conf['db_host'], $conf['db_user'], $conf['db_password'], $conf['db_base']);
if ($db->connect_errno)
{
cleanupFail('Piwigo-Datenbank nicht erreichbar: '.$db->connect_error);
}
$db->set_charset('utf8mb4');
$table = $prefixeTable.'bratonien_tools_nc_connections';
$result = $db->query("SELECT takeover_state, enabled, config_json FROM `".$table."` WHERE id=".$connectionId." LIMIT 1");
if (!$result || !$result->num_rows)
{
cleanupFail('Connector-Verbindung #'.$connectionId.' wurde nicht gefunden.');
}
$row = $result->fetch_assoc();
$config = json_decode((string)$row['config_json'], true);
if ((string)$row['takeover_state'] !== 'active' || (int)$row['enabled'] !== 1 || !is_array($config))
{
cleanupFail('Legacy-Cleanup ist nur fuer eine aktive Connector-Verbindung erlaubt.');
}
if (($config['takeover']['runtime'] ?? '') !== 'plugin-runtime')
{
cleanupFail('Connector-Status bestaetigt die Plugin-Runtime noch nicht. Legacy-Bestand wird nicht entfernt.');
}
$active = cleanupRun(array('systemctl', 'is-active', $connectorTimer), true);
if ($active['exit'] !== 0)
{
cleanupFail('Der Connector-Timer ist nicht aktiv. Vor dem Cleanup muss der produktive Connector laufen.');
}
echo "Deaktiviere verbliebene Legacy-Units...\n";
cleanupRun(array('systemctl', 'disable', '--now', $legacyTimerName), true);
cleanupRun(array('systemctl', 'stop', $legacyServiceName), true);
echo "Entferne alte systemd-Units...\n";
foreach (array($legacyTimerPath, $legacyServicePath) as $path)
{
if (is_file($path) || is_link($path))
{
@unlink($path);
}
}
echo "Entferne /opt/piwigo-sync...\n";
cleanupRemoveTree('/opt/piwigo-sync');
echo "Entferne /etc/piwigo-sync...\n";
cleanupRemoveTree('/etc/piwigo-sync');
cleanupRun(array('systemctl', 'daemon-reload'));
cleanupRun(array('systemctl', 'reset-failed', $legacyServiceName), true);
$config['takeover']['legacy_cleaned_at'] = date('Y-m-d H:i:s');
$config['takeover']['legacy_cleanup'] = true;
$json = json_encode($config, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
if (is_string($json))
{
$now = date('Y-m-d H:i:s');
$escapedJson = $db->real_escape_string($json);
$escapedNow = $db->real_escape_string($now);
$db->query("UPDATE `".$table."` SET config_json='".$escapedJson."', updated='".$escapedNow."' WHERE id=".$connectionId);
}
echo "Legacy-Cleanup erfolgreich.\n";
echo "Entfernt: /opt/piwigo-sync, /etc/piwigo-sync sowie piwigo-sync.service/timer.\n";
echo "/var/lib/piwigo-sync bleibt bestehen, weil dort der aktive Connector seinen Laufzeitstatus, Name-Map und Activity-State fuehrt.\n";
}
catch (Throwable $e)
{
fwrite(STDERR, "Legacy-Cleanup abgebrochen: ".$e->getMessage()."\n");
exit(1);
}

View File

@@ -1,133 +0,0 @@
#!/usr/bin/env php
<?php
if (PHP_SAPI !== 'cli')
{
fwrite(STDERR, "Dieses Hilfsprogramm darf nur auf der Kommandozeile ausgefuehrt werden.\n");
exit(1);
}
if (function_exists('posix_geteuid') && posix_geteuid() !== 0)
{
fwrite(STDERR, "Bitte als root ausfuehren.\n");
exit(1);
}
$configPath = '/etc/piwigo-sync/piwigo.conf';
$storagePath = '/etc/piwigo-sync/storages.tsv';
$bundlePath = '/tmp/bratonien-tools-nc-import.json';
function readLegacyConfig($path)
{
if (!is_readable($path))
{
throw new RuntimeException('Legacy-Konfiguration nicht lesbar: '.$path);
}
$config = array();
foreach (file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $line)
{
$line = trim($line);
if ($line === '' || $line[0] === '#')
{
continue;
}
if (!preg_match('/^([A-Z0-9_]+)=(.*)$/', $line, $matches))
{
continue;
}
$value = trim($matches[2]);
if (strlen($value) >= 2)
{
$first = $value[0];
$last = $value[strlen($value)-1];
if (($first === '"' && $last === '"') || ($first === "'" && $last === "'"))
{
$value = substr($value, 1, -1);
}
}
$config[$matches[1]] = $value;
}
return $config;
}
function readStorages($path)
{
$storages = array();
if (!is_readable($path))
{
return $storages;
}
foreach (file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $line)
{
if ($line === '' || $line[0] === '#')
{
continue;
}
$parts = explode("\t", $line);
if (count($parts) !== 3)
{
continue;
}
$storages[] = array(
'storage_id' => $parts[0],
'source_prefix' => $parts[1],
'local_mount' => $parts[2],
);
}
return $storages;
}
try
{
$config = readLegacyConfig($configPath);
$passwordPath = isset($config['NC_DB_PASSWORD_FILE']) ? $config['NC_DB_PASSWORD_FILE'] : '/etc/piwigo-sync/nextcloud-db-password';
if (!is_readable($passwordPath))
{
throw new RuntimeException('Nextcloud-Datenbankpasswort nicht lesbar: '.$passwordPath);
}
$password = trim((string)file_get_contents($passwordPath));
if ($password === '')
{
throw new RuntimeException('Nextcloud-Datenbankpasswort ist leer.');
}
$bundle = array(
'format' => 1,
'created_at' => gmdate('c'),
'config' => $config,
'db_password' => $password,
'storages' => readStorages($storagePath),
);
$json = json_encode($bundle, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
if (!is_string($json))
{
throw new RuntimeException('Migrationspaket konnte nicht erzeugt werden.');
}
if (file_put_contents($bundlePath, $json."\n", LOCK_EX) === false)
{
throw new RuntimeException('Migrationspaket konnte nicht geschrieben werden: '.$bundlePath);
}
@chmod($bundlePath, 0600);
if (!@chown($bundlePath, 'www-data'))
{
@unlink($bundlePath);
throw new RuntimeException('Migrationspaket konnte nicht sicher an www-data uebergeben werden.');
}
@chgrp($bundlePath, 'www-data');
echo "Migrationspaket wurde bereitgestellt.\n";
echo "Jetzt in Piwigo -> Bratonien Tools -> NC Connector wechseln und 'Bestehende Verbindung importieren' ausfuehren.\n";
echo "Der laufende piwigo-sync wurde nicht veraendert oder gestoppt.\n";
}
catch (Throwable $e)
{
fwrite(STDERR, 'Fehler: '.$e->getMessage()."\n");
exit(1);
}

View File

@@ -1,149 +0,0 @@
#!/usr/bin/env php
<?php
if (PHP_SAPI !== 'cli')
{
fwrite(STDERR, "Dieses Hilfsprogramm darf nur auf der Kommandozeile ausgefuehrt werden.\n");
exit(1);
}
if (function_exists('posix_geteuid') && posix_geteuid() !== 0)
{
fwrite(STDERR, "Bitte als root ausfuehren.\n");
exit(1);
}
if ($argc !== 2 || !preg_match('/^[1-9][0-9]*$/', $argv[1]))
{
fwrite(STDERR, "Aufruf: php nc-connector-normalize.php <connection-id>\n");
exit(1);
}
$id = (int)$argv[1];
$pluginRoot = __DIR__;
$piwigoRoot = dirname(__DIR__, 2);
$dbConfig = $piwigoRoot.'/local/config/database.inc.php';
$configPath = '/etc/bratonien-tools/nc-connector/connection-'.$id.'.conf';
$newState = '/var/lib/bratonien-tools/nc-connector/connection-'.$id;
$servicePath = '/etc/systemd/system/bratonien-nc-connector.service';
$timer = 'bratonien-nc-connector.timer';
$service = 'bratonien-nc-connector.service';
function normalize_run(array $command, $allowFailure = false)
{
$spec = array(0=>array('file','/dev/null','r'), 1=>array('pipe','w'), 2=>array('pipe','w'));
$process = proc_open($command, $spec, $pipes);
if (!is_resource($process)) throw new RuntimeException('Prozess konnte nicht gestartet werden.');
$stdout = stream_get_contents($pipes[1]);
$stderr = stream_get_contents($pipes[2]);
fclose($pipes[1]); fclose($pipes[2]);
$exit = proc_close($process);
if ($exit !== 0 && !$allowFailure)
{
$detail = trim($stderr) !== '' ? trim($stderr) : trim($stdout);
throw new RuntimeException('Befehl fehlgeschlagen ('.$exit.'): '.implode(' ', $command).($detail !== '' ? "\n".$detail : ''));
}
return array('exit'=>$exit, 'stdout'=>$stdout, 'stderr'=>$stderr);
}
function remove_tree($path)
{
if (!is_dir($path)) return;
$items = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS),
RecursiveIteratorIterator::CHILD_FIRST
);
foreach ($items as $item)
{
if ($item->isDir()) @rmdir($item->getPathname()); else @unlink($item->getPathname());
}
@rmdir($path);
}
try
{
$conf = array();
$prefixeTable = 'piwigo_';
if (!is_readable($dbConfig)) throw new RuntimeException('Piwigo-Datenbankkonfiguration nicht lesbar.');
require $dbConfig;
$db = new mysqli($conf['db_host'], $conf['db_user'], $conf['db_password'], $conf['db_base']);
if ($db->connect_errno) throw new RuntimeException('Piwigo-Datenbank nicht erreichbar: '.$db->connect_error);
$db->set_charset('utf8mb4');
$table = $prefixeTable.'bratonien_tools_nc_connections';
$result = $db->query("SELECT id, enabled, takeover_state, config_json FROM `".$table."` WHERE id=".$id." LIMIT 1");
if (!$result || !$result->num_rows) throw new RuntimeException('Connector-Verbindung #'.$id.' wurde nicht gefunden.');
$row = $result->fetch_assoc();
if ((int)$row['enabled'] !== 1 || (string)$row['takeover_state'] !== 'active') throw new RuntimeException('Die Verbindung muss aktiv sein.');
$config = json_decode((string)$row['config_json'], true);
if (!is_array($config)) throw new RuntimeException('Connector-Konfiguration ist ungueltig.');
$oldState = rtrim((string)($config['state_dir'] ?? ''), '/');
if ($oldState === '') throw new RuntimeException('Bisheriger State-Pfad fehlt.');
if ($oldState === $newState)
{
echo "Verbindung #".$id." verwendet bereits den nativen State-Pfad.\n";
exit(0);
}
if (!is_readable($configPath)) throw new RuntimeException('Aktive Runtime-Konfiguration fehlt: '.$configPath);
echo "Stoppe Connector-Timer...\n";
normalize_run(array('systemctl','stop',$timer));
$deadline = time() + 120;
while (normalize_run(array('systemctl','is-active','--quiet',$service), true)['exit'] === 0)
{
if (time() >= $deadline) throw new RuntimeException('Laufender Connector-Lauf wurde nach 120 Sekunden nicht beendet.');
sleep(2);
}
if (!is_dir(dirname($newState)) && !mkdir(dirname($newState), 0750, true)) throw new RuntimeException('Neues State-Wurzelverzeichnis konnte nicht angelegt werden.');
if (!is_dir($newState) && !mkdir($newState, 0750, true)) throw new RuntimeException('Neues State-Verzeichnis konnte nicht angelegt werden.');
if (is_dir($oldState)) normalize_run(array('cp','-a',$oldState.'/.',$newState.'/'));
chmod($newState, 0750);
$originalConfig = file_get_contents($configPath);
if (!is_string($originalConfig)) throw new RuntimeException('Runtime-Konfiguration konnte nicht gelesen werden.');
$newStatus = $newState.'/connector-status.json';
$updatedConfig = preg_replace('/^STATE_DIR=.*$/m', 'STATE_DIR='.$newState, $originalConfig, 1);
$updatedConfig = preg_replace('/^STATUS_FILE=.*$/m', 'STATUS_FILE='.$newStatus, $updatedConfig, 1);
if (!is_string($updatedConfig) || $updatedConfig === $originalConfig) throw new RuntimeException('Runtime-Konfiguration konnte nicht auf nativen State umgestellt werden.');
file_put_contents($configPath, $updatedConfig, LOCK_EX);
chmod($configPath, 0600);
echo "Teste Plugin-Runtime mit neuem State...\n";
$test = normalize_run(array('env','PIWIGO_CONFIG='.$configPath,'bash',$pluginRoot.'/runtime/sync.sh'), true);
if ($test['exit'] !== 0)
{
file_put_contents($configPath, $originalConfig, LOCK_EX);
remove_tree($newState);
normalize_run(array('systemctl','start',$timer), true);
$detail = trim($test['stderr']) !== '' ? trim($test['stderr']) : trim($test['stdout']);
throw new RuntimeException('Normalisierung abgebrochen; alter Zustand wiederhergestellt'.($detail !== '' ? ': '.$detail : '.'));
}
$serviceContent = "[Unit]\nDescription=Bratonien NC Connector Sync\nAfter=network-online.target\nWants=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/usr/bin/env bash ".$pluginRoot."/runtime/run-all.sh\n\n";
file_put_contents($servicePath, $serviceContent, LOCK_EX);
chmod($servicePath, 0644);
$config['state_dir'] = $newState;
$config['status_file'] = $newStatus;
$config['origin'] = 'native';
$config['runtime'] = array('mode'=>'plugin-runtime', 'config'=>$configPath);
if (isset($config['takeover']) && is_array($config['takeover'])) $config['takeover']['runtime'] = 'plugin-runtime';
$json = json_encode($config, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$jsonEsc = $db->real_escape_string((string)$json);
$nowEsc = $db->real_escape_string(date('Y-m-d H:i:s'));
if (!$db->query("UPDATE `".$table."` SET config_json='".$jsonEsc."', updated='".$nowEsc."' WHERE id=".$id)) throw new RuntimeException('Connector-Datenbankstatus konnte nicht aktualisiert werden: '.$db->error);
normalize_run(array('systemctl','daemon-reload'));
normalize_run(array('systemctl','enable','--now',$timer));
if ($oldState !== '/var/lib' && $oldState !== '/' && strpos($oldState, '/var/lib/') === 0)
{
remove_tree($oldState);
}
echo "Normalisierung erfolgreich.\n";
echo "State: ".$newState."\n";
echo "Service: gemeinsamer Multi-Connection-Runner aus Bratonien Tools.\n";
}
catch (Throwable $e)
{
fwrite(STDERR, $e->getMessage()."\n");
exit(1);
}

View File

@@ -1,226 +0,0 @@
#!/usr/bin/env php
<?php
if (PHP_SAPI !== 'cli')
{
fwrite(STDERR, "Dieses Hilfsprogramm darf nur auf der Kommandozeile ausgefuehrt werden.\n");
exit(1);
}
if (function_exists('posix_geteuid') && posix_geteuid() !== 0)
{
fwrite(STDERR, "Bitte als root ausfuehren.\n");
exit(1);
}
if ($argc !== 2 || !preg_match('/^[1-9][0-9]*$/', $argv[1]))
{
fwrite(STDERR, "Aufruf: php nc-connector-runtime-switch.php <connection-id>\n");
exit(1);
}
$connectionId = (int)$argv[1];
$piwigoRoot = dirname(__DIR__, 2);
$dbConfig = $piwigoRoot.'/local/config/database.inc.php';
$pluginRuntime = __DIR__.'/runtime/sync.sh';
$configPath = '/etc/bratonien-tools/nc-connector/connection-'.$connectionId.'.conf';
$serviceName = 'bratonien-nc-connector.service';
$timerName = 'bratonien-nc-connector.timer';
$servicePath = '/etc/systemd/system/'.$serviceName;
function failRuntimeSwitch($message)
{
throw new RuntimeException($message);
}
function runRuntimeSwitch(array $command, $allowFailure = false)
{
$spec = array(
0 => array('file', '/dev/null', 'r'),
1 => array('pipe', 'w'),
2 => array('pipe', 'w'),
);
$process = proc_open($command, $spec, $pipes);
if (!is_resource($process))
{
failRuntimeSwitch('Prozess konnte nicht gestartet werden: '.implode(' ', $command));
}
$stdout = stream_get_contents($pipes[1]);
$stderr = stream_get_contents($pipes[2]);
fclose($pipes[1]);
fclose($pipes[2]);
$exit = proc_close($process);
if ($exit !== 0 && !$allowFailure)
{
$detail = trim($stderr) !== '' ? trim($stderr) : trim($stdout);
failRuntimeSwitch('Befehl fehlgeschlagen ('.$exit.'): '.implode(' ', $command).($detail !== '' ? "\n".$detail : ''));
}
return array('exit'=>$exit, 'stdout'=>(string)$stdout, 'stderr'=>(string)$stderr);
}
function parseRuntimeConfig($path)
{
if (!is_readable($path))
{
failRuntimeSwitch('Connector-Konfiguration nicht lesbar: '.$path);
}
$result = array();
foreach (file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $line)
{
$line = trim($line);
if ($line === '' || $line[0] === '#')
{
continue;
}
if (preg_match('/^([A-Z0-9_]+)=(.*)$/', $line, $matches))
{
$result[$matches[1]] = trim($matches[2]);
}
}
return $result;
}
function dbEscapeRuntime(mysqli $db, $value)
{
return $db->real_escape_string((string)$value);
}
$oldService = null;
$db = null;
$table = '';
$config = array();
$timerStopped = false;
try
{
if (!is_file($pluginRuntime) || !is_readable($pluginRuntime))
{
failRuntimeSwitch('Plugin-Runtime fehlt: '.$pluginRuntime);
}
if (!is_readable($dbConfig))
{
failRuntimeSwitch('Piwigo-Datenbankkonfiguration nicht lesbar.');
}
if (!is_readable($servicePath))
{
failRuntimeSwitch('Bestehender Connector-Service wurde nicht gefunden: '.$servicePath);
}
$conf = array();
$prefixeTable = 'piwigo_';
require $dbConfig;
$db = new mysqli($conf['db_host'], $conf['db_user'], $conf['db_password'], $conf['db_base']);
if ($db->connect_errno)
{
failRuntimeSwitch('Piwigo-Datenbank nicht erreichbar: '.$db->connect_error);
}
$db->set_charset('utf8mb4');
$table = $prefixeTable.'bratonien_tools_nc_connections';
$result = $db->query("SELECT takeover_state, enabled, config_json FROM `".$table."` WHERE id=".$connectionId." LIMIT 1");
if (!$result || !$result->num_rows)
{
failRuntimeSwitch('Connector-Verbindung #'.$connectionId.' wurde nicht gefunden.');
}
$row = $result->fetch_assoc();
if ((string)$row['takeover_state'] !== 'active' || (int)$row['enabled'] !== 1)
{
failRuntimeSwitch('Runtime-Switch ist nur fuer eine aktive Connector-Verbindung erlaubt.');
}
$config = json_decode((string)$row['config_json'], true);
if (!is_array($config))
{
failRuntimeSwitch('Connector-Konfiguration ist ungueltig.');
}
$runtimeConfig = parseRuntimeConfig($configPath);
$statusPath = isset($runtimeConfig['STATUS_FILE']) ? (string)$runtimeConfig['STATUS_FILE'] : '';
if ($statusPath === '')
{
failRuntimeSwitch('STATUS_FILE fehlt in der Connector-Konfiguration.');
}
$oldService = file_get_contents($servicePath);
if (!is_string($oldService) || $oldService === '')
{
failRuntimeSwitch('Bestehende Service-Definition konnte nicht gesichert werden.');
}
echo "Stoppe Connector-Timer fuer den Runtime-Test...\n";
runRuntimeSwitch(array('systemctl', 'stop', $timerName));
$timerStopped = true;
$deadline = time() + 120;
do
{
$active = runRuntimeSwitch(array('systemctl', 'is-active', '--quiet', $serviceName), true);
if ($active['exit'] !== 0)
{
break;
}
if (time() >= $deadline)
{
failRuntimeSwitch('Ein laufender Connector-Sync wurde nach 120 Sekunden nicht beendet.');
}
sleep(2);
}
while (true);
@unlink($statusPath);
echo "Teste Plugin-eigene Sync-Runtime...\n";
$test = runRuntimeSwitch(array('env', 'PIWIGO_CONFIG='.$configPath, '/bin/bash', $pluginRuntime), true);
if ($test['exit'] !== 0)
{
$detail = trim($test['stderr']) !== '' ? trim($test['stderr']) : trim($test['stdout']);
failRuntimeSwitch('Plugin-Runtime-Test fehlgeschlagen'.($detail !== '' ? ': '.$detail : '.'));
}
$status = is_readable($statusPath) ? json_decode((string)file_get_contents($statusPath), true) : null;
$state = is_array($status) ? trim((string)($status['state'] ?? '')) : '';
$message = is_array($status) ? trim((string)($status['message'] ?? '')) : '';
if ($state === 'error')
{
failRuntimeSwitch('Plugin-Runtime meldete einen Fehler'.($message !== '' ? ': '.$message : '.'));
}
echo 'Runtime-Test erfolgreich: '.($message !== '' ? $message : 'Exit-Code 0')."\n";
$service = "[Unit]\nDescription=Bratonien NC Connector Sync\nAfter=network-online.target\nWants=network-online.target\n\n[Service]\nType=oneshot\nEnvironment=PIWIGO_CONFIG=".$configPath."\nExecStart=/bin/bash ".$pluginRuntime."\n\n";
if (file_put_contents($servicePath, $service, LOCK_EX) === false)
{
failRuntimeSwitch('Neue Service-Definition konnte nicht geschrieben werden.');
}
chmod($servicePath, 0644);
runRuntimeSwitch(array('systemctl', 'daemon-reload'));
runRuntimeSwitch(array('systemctl', 'enable', '--now', $timerName));
$timerStopped = false;
$config['takeover']['runtime'] = 'plugin-runtime';
$config['takeover']['runtime_switched_at'] = date('Y-m-d H:i:s');
$config['takeover']['runtime_path'] = $pluginRuntime;
$json = json_encode($config, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
if (!is_string($json))
{
failRuntimeSwitch('Connector-Status konnte nicht serialisiert werden.');
}
$now = date('Y-m-d H:i:s');
$sql = "UPDATE `".$table."` SET config_json='".dbEscapeRuntime($db, $json)."', updated='".dbEscapeRuntime($db, $now)."' WHERE id=".$connectionId;
if (!$db->query($sql))
{
failRuntimeSwitch('Connector-Status konnte nicht aktualisiert werden: '.$db->error);
}
echo "Runtime-Switch erfolgreich.\n";
echo "Der Connector verwendet jetzt ausschliesslich die Plugin-eigene Sync-Runtime.\n";
}
catch (Throwable $e)
{
if (is_string($oldService) && $oldService !== '')
{
@file_put_contents($servicePath, $oldService, LOCK_EX);
runRuntimeSwitch(array('systemctl', 'daemon-reload'), true);
}
if ($timerStopped)
{
runRuntimeSwitch(array('systemctl', 'enable', '--now', $timerName), true);
}
fwrite(STDERR, "Runtime-Switch fehlgeschlagen: ".$e->getMessage()."\n");
fwrite(STDERR, "Die bisherige Connector-Runtime wurde beibehalten/wiederhergestellt.\n");
exit(1);
}

View File

@@ -29,6 +29,9 @@ $latest = array(
'state'=>'idle',
'message'=>'Noch kein Connector-Status verfügbar.',
'timestamp'=>0,
'last_run_label'=>'Nicht verfügbar',
'next_run_timestamp'=>0,
'next_run_label'=>'Nicht verfügbar',
'auth_mode'=>'',
'api'=>array('state'=>'not_run','message'=>''),
'fallback'=>array('state'=>'not_run','message'=>''),
@@ -56,4 +59,21 @@ if (is_dir($dir))
}
}
if ((int)$latest['timestamp'] > 0)
{
$latest['last_run_label'] = date('d.m.Y H:i:s', (int)$latest['timestamp']);
}
$system_file = BRATONIEN_TOOLS_PATH.'include/nc_connector_system.inc.php';
if (is_readable($system_file))
{
include_once($system_file);
if (function_exists('bratonien_tools_nc_connector_system_status'))
{
$system = bratonien_tools_nc_connector_system_status(array());
$latest['next_run_timestamp'] = (int)($system['next_run_timestamp'] ?? 0);
$latest['next_run_label'] = (string)($system['next_run_label'] ?? 'Nicht verfügbar');
}
}
echo json_encode($latest, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

View 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);
}

View File

@@ -1,115 +0,0 @@
#!/usr/bin/env python3
"""Debounce Nextcloud activity and request a periodic safety reconciliation."""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import subprocess
import sys
import tempfile
import time
from pathlib import Path
def load(path: Path) -> dict[str, object]:
defaults: dict[str, object] = {
"processed": 0,
"observed": 0,
"pending_since": 0,
"last_change": 0,
"last_full": 0,
"source_signature": "",
}
if not path.exists():
return defaults
data = json.loads(path.read_text(encoding="utf-8"))
return {
"processed": int(data.get("processed", 0)),
"observed": int(data.get("observed", 0)),
"pending_since": int(data.get("pending_since", 0)),
"last_change": int(data.get("last_change", 0)),
"last_full": int(data.get("last_full", 0)),
"source_signature": str(data.get("source_signature", "")),
}
def save(path: Path, state: dict[str, object]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
fd, name = tempfile.mkstemp(dir=path.parent)
with os.fdopen(fd, "w", encoding="utf-8") as handle:
json.dump(state, handle, sort_keys=True)
handle.write("\n")
Path(name).replace(path)
def query(args: argparse.Namespace, sql: str) -> str:
env = os.environ.copy()
env["PGPASSWORD"] = args.password_file.read_text(encoding="utf-8").strip()
command = ["psql", "-XAt", "-h", args.host, "-p", str(args.port), "-U", args.user, "-d", args.database, "-c", sql]
return subprocess.run(command, env=env, check=True, text=True, capture_output=True).stdout
def latest(args: argparse.Namespace) -> int:
return int(query(args, f"SELECT COALESCE(MAX(activity_id), 0) FROM {args.view}").strip())
def source_signature(args: argparse.Namespace) -> str:
if not args.source_view:
return ""
payload = query(args, f"SELECT share_id, display_name, storage_id, source_path FROM {args.source_view} ORDER BY share_id")
return hashlib.sha256(payload.encode("utf-8")).hexdigest()
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("action", choices=("check", "commit"))
parser.add_argument("--state", required=True, type=Path)
parser.add_argument("--host", required=True)
parser.add_argument("--port", type=int, default=5432)
parser.add_argument("--database", required=True)
parser.add_argument("--user", required=True)
parser.add_argument("--password-file", required=True, type=Path)
parser.add_argument("--view", default="piwigo_showcase_activity")
parser.add_argument("--source-view", default="")
parser.add_argument("--quiet", type=int, default=120)
parser.add_argument("--max-wait", type=int, default=900)
parser.add_argument("--full-after", type=int, default=86400)
args = parser.parse_args()
try:
state = load(args.state)
now = int(time.time())
current = latest(args)
current_source = source_signature(args)
if args.action == "commit":
state.update(processed=current, observed=current, pending_since=0, last_change=0, last_full=now, source_signature=current_source)
save(args.state, state)
return 0
if not int(state["last_full"]):
return 0
if current_source and current_source != str(state["source_signature"]):
return 0
if current > int(state["observed"]):
state["observed"] = current
state["last_change"] = now
state["pending_since"] = int(state["pending_since"]) or now
save(args.state, state)
if now - int(state["last_full"]) >= args.full_after:
return 0
if int(state["observed"]) <= int(state["processed"]):
return 3
if now - int(state["last_change"]) >= args.quiet or now - int(state["pending_since"]) >= args.max_wait:
return 0
return 3
except Exception as error:
print(f"activity-gate: {error}", file=sys.stderr)
return 1
if __name__ == "__main__":
raise SystemExit(main())

View File

@@ -0,0 +1,46 @@
<?php
if (PHP_SAPI !== 'cli')
{
http_response_code(404);
exit;
}
$query = '';
foreach ($argv as $arg)
{
if (strpos($arg, '--query=') === 0)
{
$query = substr($arg, strlen('--query='));
}
}
if ($query === '')
{
fwrite(STDERR, "Parameter --query fehlt.\n");
exit(2);
}
$piwigo_root = realpath(dirname(__DIR__, 4));
$plugin_root = realpath(dirname(__DIR__, 2));
if ($piwigo_root === false || $plugin_root === false || !is_file($plugin_root.'/watermark.php'))
{
fwrite(STDERR, "Piwigo-Root oder Bratonien-Wasserzeichenmodul wurde nicht gefunden.\n");
exit(3);
}
$plugin_id = basename($plugin_root);
parse_str($query, $_GET);
$_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'] = '/plugins/'.$plugin_id.'/watermark.php?'.$query;
$_SERVER['SCRIPT_NAME'] = '/plugins/'.$plugin_id.'/watermark.php';
$_SERVER['PHP_SELF'] = $_SERVER['SCRIPT_NAME'];
$_SERVER['QUERY_STRING'] = $query;
$_SERVER['HTTP_USER_AGENT'] = 'Bratonien-Presentation-Refresh/0.9.7.1.41';
$_SERVER['HTTPS'] = 'off';
chdir($piwigo_root);
include $plugin_root.'/watermark.php';

View 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);
}

View File

@@ -1,180 +0,0 @@
#!/usr/bin/env python3
"""Resolve Nextcloud view rows through explicitly configured storage mounts."""
from __future__ import annotations
import argparse
import csv
import json
import os
import subprocess
import sys
import tempfile
from pathlib import Path, PurePosixPath
def read_config(path: Path) -> dict[str, tuple[str, Path]]:
result: dict[str, tuple[str, Path]] = {}
with path.open(encoding="utf-8") as handle:
for number, line in enumerate(handle, 1):
line = line.rstrip("\n")
if not line or line.startswith("#"):
continue
fields = line.split("\t")
if len(fields) != 3:
raise ValueError(f"{path}:{number}: expected storage_id, source_prefix and local_mount")
storage_id, prefix, mount = fields
result[storage_id] = (prefix.strip("/"), Path(mount))
return result
def run_query(args: argparse.Namespace, env: dict[str, str], sql: str) -> subprocess.CompletedProcess[str]:
command = [
"psql", "-X", "-A", "-F", "\t", "-t",
"-h", args.host, "-p", str(args.port), "-U", args.user, "-d", args.database,
"-c", sql,
]
return subprocess.run(command, env=env, check=False, text=True, capture_output=True)
def query_rows(args: argparse.Namespace) -> list[list[str]]:
password = args.password_file.read_text(encoding="utf-8").strip()
env = os.environ.copy()
env["PGPASSWORD"] = password
modern_sql = f"SELECT share_id, item_type, display_name, storage_id, source_path FROM {args.view} ORDER BY share_id"
completed = run_query(args, env, modern_sql)
if completed.returncode == 0:
return list(csv.reader(completed.stdout.splitlines(), delimiter="\t"))
# Existing installations may still expose the original four-column view.
# Keep them usable and derive folder/file from the resolved source path.
if "item_type" not in completed.stderr or "does not exist" not in completed.stderr:
raise RuntimeError(completed.stderr.strip() or "Nextcloud source view query failed")
legacy_sql = f"SELECT share_id, display_name, storage_id, source_path FROM {args.view} ORDER BY share_id"
completed = run_query(args, env, legacy_sql)
if completed.returncode != 0:
raise RuntimeError(completed.stderr.strip() or "legacy Nextcloud source view query failed")
rows: list[list[str]] = []
for row in csv.reader(completed.stdout.splitlines(), delimiter="\t"):
if len(row) == 4:
share_id, display_name, storage_id, source_path = row
rows.append([share_id, "", display_name, storage_id, source_path])
else:
rows.append(row)
return rows
def contained_join(root: Path, relative: str) -> Path:
parts = PurePosixPath(relative).parts
if relative.startswith("/") or ".." in parts:
raise ValueError(f"unsafe source path: {relative}")
return root.joinpath(*parts)
def build(args: argparse.Namespace) -> dict[str, object]:
adapters = read_config(args.storage_config)
rows = query_rows(args)
if not rows and not args.allow_empty:
raise RuntimeError("Nextcloud returned no Showcase shares; refusing an empty manifest")
manifest: list[str] = []
errors: list[str] = []
folder_count = 0
file_count = 0
for row in rows:
if len(row) != 5:
errors.append(f"invalid database row with {len(row)} columns")
continue
share_id, item_type, display_name, storage_id, source_path = row
item_type = item_type.strip().lower()
if item_type and item_type not in {"folder", "file"}:
errors.append(f"share {share_id}: unsupported item_type {item_type!r}")
continue
adapter = adapters.get(storage_id)
if not adapter:
errors.append(f"share {share_id}: unknown storage {storage_id}")
continue
prefix, mount = adapter
relative = source_path.strip("/")
if prefix:
expected = prefix + "/"
if relative != prefix and not relative.startswith(expected):
errors.append(f"share {share_id}: path does not match configured prefix")
continue
relative = relative[len(prefix):].lstrip("/")
source = contained_join(mount, relative)
if not mount.is_mount():
errors.append(f"share {share_id}: storage mount unavailable: {mount}")
continue
if not item_type:
if source.is_dir():
item_type = "folder"
elif source.is_file():
item_type = "file"
else:
errors.append(f"share {share_id}: source unavailable: {source}")
continue
if item_type == "folder":
if not source.is_dir():
errors.append(f"share {share_id}: source directory unavailable: {source}")
continue
folder_count += 1
else:
if not source.is_file():
errors.append(f"share {share_id}: source file unavailable: {source}")
continue
file_count += 1
manifest.append(f"{share_id}\t{item_type}\t{display_name.lstrip('/')}\t{source}")
if errors:
raise RuntimeError("; ".join(errors))
if len(manifest) != len(rows):
raise RuntimeError("not all Showcase shares could be resolved")
args.output.parent.mkdir(parents=True, exist_ok=True)
with tempfile.NamedTemporaryFile("w", encoding="utf-8", dir=args.output.parent, delete=False) as handle:
handle.write("\n".join(manifest) + ("\n" if manifest else ""))
temporary = Path(handle.name)
temporary.replace(args.output)
return {
"shares": len(manifest),
"folders": folder_count,
"files": file_count,
"manifest": str(args.output),
}
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--host", required=True)
parser.add_argument("--port", type=int, default=5432)
parser.add_argument("--database", required=True)
parser.add_argument("--user", required=True)
parser.add_argument("--password-file", required=True, type=Path)
parser.add_argument("--view", default="piwigo_showcase_sources")
parser.add_argument("--storage-config", required=True, type=Path)
parser.add_argument("--output", required=True, type=Path)
parser.add_argument("--allow-empty", action="store_true")
args = parser.parse_args()
try:
print(json.dumps(build(args), ensure_ascii=False))
except Exception as error:
print(f"manifest: {error}", file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
raise SystemExit(main())

View File

@@ -0,0 +1,451 @@
#!/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"
NC = "http://nextcloud.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==")
class WebDavAuthenticationError(RuntimeError):
pass
class WebDavPathUnavailable(RuntimeError):
def __init__(self, relative: str, status: int) -> None:
self.relative = validate_relative(relative)
self.status = int(status)
super().__init__(f"Nextcloud path unavailable with HTTP {self.status}: {self.relative or '/'}")
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
def parse_image_dimensions(prop: ET.Element) -> tuple[int, int]:
for property_name in ("metadata-photos-size", "file-metadata-size"):
element = prop.find(f"{{{NC}}}{property_name}")
if element is None:
continue
width = 0
height = 0
for child in list(element):
local_name = child.tag.rsplit("}", 1)[-1]
text = (child.text or "").strip()
if not text:
continue
try:
value = int(text)
except ValueError:
continue
if local_name == "width":
width = value
elif local_name == "height":
height = value
if width > 0 and height > 0:
return width, height
raw = (element.text or "").strip()
if not raw:
continue
try:
value = json.loads(raw)
except (TypeError, ValueError, json.JSONDecodeError):
continue
if not isinstance(value, dict):
continue
try:
width = int(value.get("width", 0) or 0)
height = int(value.get("height", 0) or 0)
except (TypeError, ValueError):
continue
if width > 0 and height > 0:
return width, height
return 0, 0
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" xmlns:nc="http://nextcloud.org/ns">'
'<d:prop><d:displayname/><d:resourcetype/><d:getcontenttype/>'
'<d:getcontentlength/><d:getetag/><oc:fileid/>'
'<nc:file-metadata-size/><nc:metadata-photos-size/>'
'</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 == 401:
raise WebDavAuthenticationError("Nextcloud rejected the WebDAV credentials") from error
if error.code in {403, 404}:
raise WebDavPathUnavailable(relative, error.code) from error
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
width, height = parse_image_dimensions(prop)
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('"'),
"width": width,
"height": height,
}
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 confirmed_removed_root(client: WebDavClient, remote_root: str, error: WebDavPathUnavailable) -> bool:
remote_root = validate_relative(remote_root)
if remote_root == "":
return False
if error.status == 404:
return True
if error.status != 403:
return False
parent_path = PurePosixPath(remote_root).parent
parent = "" if str(parent_path) == "." else str(parent_path).strip("/")
_, siblings = client.list_collection(parent)
wanted = PurePosixPath(remote_root).name.casefold()
for sibling in siblings:
if str(sibling.get("display_name", "")).casefold() == wanted:
return False
return True
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", "")),
"width": int(child.get("width", 0) or 0),
"height": int(child.get("height", 0) or 0),
}
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))
# A successful request against the user's WebDAV root proves that the
# credentials and the Nextcloud endpoint are healthy. Only after this
# guard may an individual configured root be interpreted as removed.
webdav_home, _ = client.list_collection("")
mapping: dict[str, dict[str, object]] = {}
manifest: list[str] = []
total_files = total_folders = total_skipped = 0
used_names: set[str] = set()
removed_roots: list[dict[str, object]] = []
for remote_root_raw in args.root:
remote_root = validate_relative(remote_root_raw)
try:
current, _ = client.list_collection(remote_root)
except WebDavPathUnavailable as error:
if not confirmed_removed_root(client, remote_root, error):
raise RuntimeError(
f"Configured WebDAV root cannot be read safely; existing mirror is preserved: {remote_root or '/'} (HTTP {error.status})"
) from error
removed_roots.append({"path": remote_root, "status": error.status})
print(
f"webdav-placeholder: configured root no longer available and will be removed from the mirror: {remote_root or '/'} (HTTP {error.status})",
file=sys.stderr,
)
continue
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
if remote_root == "":
for child in sorted(local_root.iterdir(), key=lambda item: (item.name.casefold(), item.name)):
child_data = mapping.get(str(child))
if not child_data:
continue
child_fileid = int(child_data.get("fileid", 0))
child_display = str(child_data.get("display_name", "")).strip() or child.name
child_type = "folder" if child.is_dir() else "file"
manifest.append(
f"webdav:{child_fileid}\t{child_type}\t{child_display}\t{source_dir / local_name / child.name}"
)
else:
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
# Der Worker erwartet ein syntaktisch nicht-leeres Connector-Mapping,
# filtert aber selbst ausschließlich kind=file. Wenn alle ausgewählten
# Roots entzogen wurden, hält dieser echte WebDAV-Home-Verzeichniseintrag
# das Mapping gültig, während der Shadowtree bewusst null Bildquellen hat.
if not final_mapping:
final_mapping[source_text] = {
"kind": "folder",
"fileid": int(webdav_home["fileid"]),
"webdav_path": "",
"display_name": str(webdav_home.get("display_name", "")) or args.user,
"control_entry": True,
}
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),
"roots_available": len(args.root) - len(removed_roots),
"roots_removed": len(removed_roots),
"removed_root_details": removed_roots,
"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())

View File

@@ -0,0 +1,248 @@
<?php
if (PHP_SAPI !== 'cli')
{
http_response_code(404);
exit;
}
$piwigo_root = realpath(dirname(__DIR__, 4));
if ($piwigo_root === false)
{
fwrite(STDERR, "Piwigo-Root wurde nicht gefunden.\n");
exit(1);
}
define('PHPWG_ROOT_PATH', rtrim($piwigo_root, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR);
$_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/piwigo-cache-request-by-shadow.php';
$_SERVER['PHP_SELF'] = $_SERVER['SCRIPT_NAME'];
$_SERVER['QUERY_STRING'] = '';
$_SERVER['HTTP_USER_AGENT'] = 'Bratonien-Piwigo-Shadow-Cache-Bridge/0.9.7.1.41';
$_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 (!defined('BRATONIEN_TOOLS_PATH'))
{
fwrite(STDERR, "Bratonien Tools ist nicht aktiv.\n");
exit(1);
}
require_once(BRATONIEN_TOOLS_PATH.'include/nc_connector.inc.php');
require_once(BRATONIEN_TOOLS_PATH.'include/webdav_cache_validation.inc.php');
require_once(BRATONIEN_TOOLS_PATH.'include/webdav_materialize_runtime.inc.php');
function bratonien_tools_shadow_bridge_fail($message, $code=1)
{
fwrite(STDERR, $message."\n");
exit((int)$code);
}
function bratonien_tools_shadow_bridge_i_request($target)
{
$root = PHPWG_ROOT_PATH.PWG_DERIVATIVE_DIR;
$target = str_replace('\\', '/', (string)$target);
$root = str_replace('\\', '/', (string)$root);
if (strpos($target, $root) !== 0) return null;
$relative = ltrim(substr($target, strlen($root)), '/');
if ($relative === '') return null;
return '/i.php?/'.implode('/', array_map('rawurlencode', explode('/', $relative)));
}
function bratonien_tools_shadow_bridge_call_i($request, &$detail=null)
{
$detail = '';
$runner = BRATONIEN_TOOLS_PATH.'runtime/lib/piwigo-derivative-call.php';
if (!is_file($runner)) { $detail = 'Piwigo-Derivataufruf fehlt.'; return false; }
if (!function_exists('exec')) { $detail = 'PHP exec() ist deaktiviert.'; return false; }
$output = array();
$exit = 1;
@exec(escapeshellarg(PHP_BINARY).' '.escapeshellarg($runner).' --request='.escapeshellarg($request).' 2>&1', $output, $exit);
if ($exit !== 0)
{
$detail = 'Piwigo-Aufruf Exit '.$exit;
if ($output) $detail .= ': '.implode(' ', array_slice($output, -3));
return false;
}
return true;
}
function bratonien_tools_shadow_bridge_sync_actual_metadata(array &$row, $source_path)
{
$size = @getimagesize($source_path);
if (!is_array($size) || (int)($size[0] ?? 0) < 1 || (int)($size[1] ?? 0) < 1)
{
bratonien_tools_shadow_bridge_fail('Das temporär eingesetzte Original besitzt keine lesbaren Bildabmessungen.');
}
$width = (int)$size[0];
$height = (int)$size[1];
$rotation_angle = pwg_image::get_rotation_angle($source_path);
$rotation_angle = $rotation_angle === null ? 0 : (int)$rotation_angle;
$rotation = pwg_image::get_rotation_code_from_angle($rotation_angle);
if ($rotation === null) $rotation = 0;
$rotation = (int)$rotation;
if (
(int)($row['width'] ?? 0) === $width
&& (int)($row['height'] ?? 0) === $height
&& isset($row['rotation'])
&& (int)$row['rotation'] === $rotation
)
{
return false;
}
pwg_query(
'UPDATE '.IMAGES_TABLE
.' SET width='.$width.', height='.$height.', rotation='.$rotation
.' WHERE id='.(int)$row['id'].' LIMIT 1'
);
$row['width'] = $width;
$row['height'] = $height;
$row['rotation'] = $rotation;
return true;
}
function bratonien_tools_shadow_bridge_variants(array $row, $stage)
{
$src = new SrcImage($row);
$variants = array();
foreach (ImageStdParams::get_defined_type_map() as $type=>$params)
{
$derivative = new DerivativeImage($params, $src);
if ($derivative->same_as_source()) continue;
$size = $derivative->get_size();
$max_edge = max((int)($size[0] ?? 0), (int)($size[1] ?? 0));
$priority = $max_edge > 0 && $max_edge <= 1920;
if (($stage === 1 && $priority) || ($stage === 2 && !$priority))
{
$variants[] = array('name'=>'standard:'.$type, 'derivative'=>$derivative, 'params'=>$params, 'target'=>$derivative->get_path());
}
}
foreach (ImageStdParams::$custom as $key=>$last_used)
{
$params = bratonien_tools_webdav_materialize_custom_params($key);
if (!$params) continue;
$derivative = new DerivativeImage($params, $src);
if ($derivative->same_as_source()) continue;
$size = $derivative->get_size();
$max_edge = max((int)($size[0] ?? 0), (int)($size[1] ?? 0));
$priority = $max_edge > 0 && $max_edge <= 1920;
if (($stage === 1 && $priority) || ($stage === 2 && !$priority))
{
$variants[] = array('name'=>'custom:'.$key, 'derivative'=>$derivative, 'params'=>$params, 'target'=>$derivative->get_path());
}
}
return $variants;
}
$connection_id = 0;
$shadow_relative = '';
$stage = 0;
foreach ($argv as $arg)
{
if (preg_match('/^--connection-id=(\d+)$/', $arg, $m)) $connection_id = (int)$m[1];
elseif (strpos($arg, '--shadow-relative=') === 0) $shadow_relative = ltrim(substr($arg, strlen('--shadow-relative=')), '/');
elseif (preg_match('/^--stage=([12])$/', $arg, $m)) $stage = (int)$m[1];
}
if ($connection_id < 1 || $shadow_relative === '' || !in_array($stage, array(1,2), true))
{
bratonien_tools_shadow_bridge_fail('Parameter --connection-id, --shadow-relative und --stage=1|2 werden benötigt.', 2);
}
if (strpos($shadow_relative, '..') !== false || strpos($shadow_relative, "\0") !== false)
{
bratonien_tools_shadow_bridge_fail('Unsicherer Shadow-Pfad.', 2);
}
$connection = bratonien_tools_nc_connector_connection($connection_id, false);
if (!$connection || empty($connection['enabled'])) bratonien_tools_shadow_bridge_fail('WebDAV-Verbindung wurde nicht gefunden.');
$config = isset($connection['config']) && is_array($connection['config']) ? $connection['config'] : array();
$gallery_root = rtrim((string)($config['parallel_gallery_root'] ?? ''), '/');
if ($gallery_root === '' || !is_dir($gallery_root)) bratonien_tools_shadow_bridge_fail('Shadow-Tree der Verbindung fehlt.');
$shadow_absolute = $gallery_root.'/'.$shadow_relative;
if (!is_link($shadow_absolute)) bratonien_tools_shadow_bridge_fail('Shadow-Datei ist kein Symlink: '.$shadow_relative);
$shadow_real = realpath($shadow_absolute);
if ($shadow_real === false || !is_file($shadow_real)) bratonien_tools_shadow_bridge_fail('Shadow-Ziel ist nicht lesbar: '.$shadow_relative);
$root = rtrim(str_replace('\\', '/', PHPWG_ROOT_PATH), '/');
$gallery = rtrim(str_replace('\\', '/', $gallery_root), '/');
if (strpos($gallery.'/', $root.'/') !== 0) bratonien_tools_shadow_bridge_fail('Shadow-Tree liegt außerhalb von Piwigo.');
$relative_gallery = ltrim(substr($gallery, strlen($root)), '/');
$db_path = './'.$relative_gallery.'/'.$shadow_relative;
$result = pwg_query("SELECT * FROM ".IMAGES_TABLE." WHERE path='".pwg_db_real_escape_string($db_path)."' LIMIT 2");
$rows = array();
while ($row = pwg_db_fetch_assoc($result)) $rows[] = $row;
if (count($rows) !== 1)
{
bratonien_tools_shadow_bridge_fail('Piwigo kann den Shadow-Pfad nicht eindeutig einem Bild zuordnen: '.$db_path);
}
$row = $rows[0];
$metadata_repaired = bratonien_tools_shadow_bridge_sync_actual_metadata($row, $shadow_real);
$variants = bratonien_tools_shadow_bridge_variants($row, $stage);
$generated = 0;
$already = 0;
$invalid_removed = 0;
foreach ($variants as $variant)
{
$reason = '';
if (bratonien_tools_webdav_derivative_cache_valid($variant['target'], $variant['derivative'], $variant['params'], $reason))
{
$already++;
continue;
}
// Ein vorhandenes, aber geometrisch falsches Derivat darf nicht an i.php
// vorbeikommen. Piwigo entscheidet sonst allein anhand von mtimes und kann
// eine alte Datei trotz korrigierter Breite/Höhe/EXIF-Rotation behalten.
if (is_file($variant['target']))
{
if (!@unlink($variant['target']))
{
bratonien_tools_shadow_bridge_fail($variant['name'].': ungültiges Alt-Derivat konnte nicht entfernt werden ('.$reason.').');
}
$invalid_removed++;
}
$request = bratonien_tools_shadow_bridge_i_request($variant['target']);
if ($request === null) bratonien_tools_shadow_bridge_fail($variant['name'].': ungültiger Piwigo-Derivatpfad.');
$detail = '';
if (!bratonien_tools_shadow_bridge_call_i($request, $detail))
{
bratonien_tools_shadow_bridge_fail($variant['name'].': '.$detail);
}
clearstatcache(true, $variant['target']);
$reason = '';
if (!bratonien_tools_webdav_derivative_cache_valid($variant['target'], $variant['derivative'], $variant['params'], $reason))
{
bratonien_tools_shadow_bridge_fail($variant['name'].': Piwigo hat kein gültiges Derivat erzeugt ('.$reason.').');
}
$generated++;
}
echo json_encode(array(
'ok'=>true,
'connection_id'=>$connection_id,
'shadow_relative'=>$shadow_relative,
'stage'=>$stage,
'piwigo_image_id'=>(int)$row['id'],
'metadata_repaired'=>$metadata_repaired,
'variants'=>count($variants),
'generated'=>$generated,
'already_valid'=>$already,
'invalid_removed'=>$invalid_removed,
), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)."\n";
exit(0);

View File

@@ -1,53 +0,0 @@
<?php
declare(strict_types=1);
if ($argc !== 3) {
fwrite(STDERR, "Usage: piwigo-db-check.php MAP_FILE PIWIGO_ROOT\n");
exit(2);
}
$mapFile = $argv[1];
$piwigoRoot = rtrim($argv[2], '/') . '/';
$databaseConfig = $piwigoRoot . 'local/config/database.inc.php';
if (!is_file($databaseConfig)) {
exit(1);
}
$mapping = json_decode((string) file_get_contents($mapFile), true, 512, JSON_THROW_ON_ERROR);
$expected = [];
foreach ($mapping as $source => $target) {
if (str_starts_with((string) $source, 'share:') && !str_contains((string) $source, '/')) {
$expected[] = basename((string) $target);
}
}
if ($expected === []) {
exit(1);
}
$conf = [];
$prefixeTable = '';
require $databaseConfig;
$database = new mysqli(
(string) $conf['db_host'],
(string) $conf['db_user'],
(string) $conf['db_password'],
(string) $conf['db_base']
);
$database->set_charset('utf8mb4');
$table = $database->real_escape_string((string) $prefixeTable) . 'categories';
$result = $database->query(
'SELECT dir FROM `' . $table . '` WHERE site_id = 1 AND dir IS NOT NULL'
);
$existing = [];
while ($row = $result->fetch_assoc()) {
$existing[(string) $row['dir']] = true;
}
foreach ($expected as $directory) {
if (!isset($existing[$directory])) {
exit(1);
}
}
exit(0);

View File

@@ -1,83 +0,0 @@
#!/usr/bin/perl
use strict;
use warnings;
use JSON::PP qw(decode_json);
use LWP::UserAgent;
use Getopt::Long;
my %opt;
GetOptions(
\%opt,
'base-url=s',
'username=s',
'password-file=s',
) or die "Ungültige Parameter\n";
for my $required (qw(base-url username password-file)) {
die "Parameter --$required fehlt\n" if !defined $opt{$required} || $opt{$required} eq '';
}
open my $password_handle, '<', $opt{'password-file'}
or die "Passwortdatei kann nicht gelesen werden: $!\n";
my $password = <$password_handle>;
close $password_handle;
defined $password or die "Passwortdatei ist leer\n";
chomp $password;
my $ua = LWP::UserAgent->new(timeout => 900);
$ua->agent('Bratonien-NC-Connector/1.0');
$ua->cookie_jar({});
my $login = $ua->post(
$opt{'base-url'}.'/ws.php?format=json',
{
method => 'pwg.session.login',
username => $opt{username},
password => $password,
},
);
die "Piwigo-Anmeldung fehlgeschlagen: ".$login->status_line."\n"
if !$login->is_success;
my $login_result = eval { decode_json($login->decoded_content) };
die "Piwigo-Anmeldung wurde abgelehnt\n"
if !$login_result || ($login_result->{stat} // '') ne 'ok';
my $sync = $ua->post(
$opt{'base-url'}.'/admin.php?page=site_update&site=1',
{
sync => 'files',
display_info => 1,
privacy_level => 0,
sync_meta => 1,
simulate => 0,
'subcats-included' => 1,
bratonien_connector => 1,
submit => 1,
},
);
die "Piwigo-Datenbanksynchronisierung fehlgeschlagen: ".$sync->status_line."\n"
if !$sync->is_success;
my $orphans = $ua->post(
$opt{'base-url'}.'/ws.php?format=json',
{
method => 'bratonien.nc.syncOrphans',
site_id => 1,
simulate => 0,
},
);
die "Piwigo-Orphan-Synchronisierung fehlgeschlagen: ".$orphans->status_line."\n"
if !$orphans->is_success;
my $orphan_result = eval { decode_json($orphans->decoded_content) };
die "Piwigo-Orphan-Synchronisierung wurde abgelehnt\n"
if !$orphan_result || ($orphan_result->{stat} // '') ne 'ok';
my $result = $orphan_result->{result} || {};
my $added = $result->{added_orphans} // 0;
my $deleted = $result->{deleted_orphans} // 0;
print "Piwigo-Datenbanksynchronisierung erfolgreich\n";
print "Piwigo-Orphans synchronisiert: +$added / -$deleted\n";

View File

@@ -0,0 +1,46 @@
<?php
if (PHP_SAPI !== 'cli')
{
http_response_code(404);
exit;
}
$request = '';
foreach ($argv as $arg)
{
if (strpos($arg, '--request=') === 0)
{
$request = substr($arg, strlen('--request='));
}
}
if ($request === '' || strpos($request, '/i.php?/') !== 0)
{
fwrite(STDERR, "Ungültige Piwigo-Derivatanforderung.\n");
exit(2);
}
$piwigo_root = realpath(dirname(__DIR__, 4));
if ($piwigo_root === false || !is_file($piwigo_root.'/i.php'))
{
fwrite(STDERR, "Piwigo i.php wurde nicht gefunden.\n");
exit(3);
}
chdir($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'] = $request;
$_SERVER['SCRIPT_NAME'] = '/i.php';
$_SERVER['PHP_SELF'] = '/i.php';
$_SERVER['QUERY_STRING'] = ltrim((string)parse_url($request, PHP_URL_QUERY), '?');
$_SERVER['HTTP_USER_AGENT'] = 'Bratonien-WebDAV-Warmup-Piwigo-Caller/0.9.7.1.8';
$_SERVER['HTTPS'] = 'off';
// Piwigo selbst erzeugt das Derivat. Der Warmup benötigt den ausgelieferten
// Bild-Body nicht und prüft danach ausschließlich Piwigos Cache-Datei.
ob_start(function ($buffer) { return ''; }, 1);
include $piwigo_root.'/i.php';

View File

@@ -14,19 +14,13 @@ function fail_sync($message)
function http_error_detail($body)
{
$body = trim((string)$body);
if ($body === '')
{
return '';
}
if ($body === '') return '';
$decoded = json_decode($body, true);
if (is_array($decoded))
{
$detail = (string)($decoded['message'] ?? $decoded['err'] ?? '');
if ($detail !== '')
{
return $detail;
}
if ($detail !== '') return $detail;
}
if (function_exists('simplexml_load_string'))
@@ -38,19 +32,12 @@ function http_error_detail($body)
if ($xml !== false)
{
$detail = trim((string)($xml->message ?? $xml->err ?? ''));
if ($detail !== '')
{
return $detail;
}
if ($detail !== '') return $detail;
}
}
$plain = trim(preg_replace('/\s+/', ' ', strip_tags($body)));
if ($plain === '')
{
return '';
}
return mb_substr($plain, 0, 500);
return $plain === '' ? '' : mb_substr($plain, 0, 500);
}
function http_request($url, array $fields, array $headers = array(), $cookie_file = null)
@@ -63,12 +50,9 @@ function http_request($url, array $fields, array $headers = array(), $cookie_fil
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_TIMEOUT => 900,
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_USERAGENT => 'Bratonien-NC-Connector/0.9.3.26',
CURLOPT_USERAGENT => 'Bratonien-NC-Connector-WebDAV',
);
if ($headers)
{
$options[CURLOPT_HTTPHEADER] = $headers;
}
if ($headers) $options[CURLOPT_HTTPHEADER] = $headers;
if ($cookie_file !== null)
{
$options[CURLOPT_COOKIEJAR] = $cookie_file;
@@ -81,42 +65,29 @@ function http_request($url, array $fields, array $headers = array(), $cookie_fil
$http = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($body === false || $errno !== 0)
{
fail_sync('HTTP-Aufruf fehlgeschlagen: '.$error);
}
if ($body === false || $errno !== 0) fail_sync('HTTP-Aufruf fehlgeschlagen: '.$error);
if ($http < 200 || $http >= 300)
{
$detail = http_error_detail((string)$body);
fail_sync('HTTP-Aufruf antwortete mit Status '.$http.($detail !== '' ? ': '.$detail : '.'));
}
return (string)$body;
}
function xml_value_sync(SimpleXMLElement $node)
{
$children = $node->children();
if (count($children) === 0)
{
return (string)$node;
}
if (count($children) === 0) return (string)$node;
$result = array();
foreach ($children as $name => $child)
{
$value = xml_value_sync($child);
if (array_key_exists($name, $result))
{
if (!is_array($result[$name]) || !array_is_list($result[$name]))
{
$result[$name] = array($result[$name]);
}
if (!is_array($result[$name]) || !array_is_list($result[$name])) $result[$name] = array($result[$name]);
$result[$name][] = $value;
}
else
{
$result[$name] = $value;
}
else $result[$name] = $value;
}
return $result;
}
@@ -126,34 +97,22 @@ function decode_ws($body)
$decoded = json_decode((string)$body, true);
if (!is_array($decoded))
{
if (!function_exists('simplexml_load_string'))
{
fail_sync('Piwigo lieferte XML, aber SimpleXML ist nicht verfuegbar.');
}
if (!function_exists('simplexml_load_string')) fail_sync('Piwigo lieferte XML, aber SimpleXML ist nicht verfuegbar.');
$previous = libxml_use_internal_errors(true);
$xml = simplexml_load_string((string)$body);
libxml_clear_errors();
libxml_use_internal_errors($previous);
if ($xml === false || $xml->getName() !== 'rsp')
{
fail_sync('Piwigo lieferte weder gueltiges JSON noch eine gueltige XML-Webservice-Antwort.');
}
if ($xml === false || $xml->getName() !== 'rsp') fail_sync('Piwigo lieferte weder gueltiges JSON noch eine gueltige XML-Webservice-Antwort.');
$decoded = array('stat'=>(string)$xml['stat']);
foreach ($xml->children() as $name => $child)
{
$value = xml_value_sync($child);
if (array_key_exists($name, $decoded))
{
if (!is_array($decoded[$name]) || !array_is_list($decoded[$name]))
{
$decoded[$name] = array($decoded[$name]);
}
if (!is_array($decoded[$name]) || !array_is_list($decoded[$name])) $decoded[$name] = array($decoded[$name]);
$decoded[$name][] = $value;
}
else
{
$decoded[$name] = $value;
}
else $decoded[$name] = $value;
}
}
if (($decoded['stat'] ?? '') !== 'ok')
@@ -161,120 +120,104 @@ function decode_ws($body)
$message = (string)($decoded['message'] ?? $decoded['err'] ?? 'Piwigo-Aufruf wurde abgelehnt.');
fail_sync($message);
}
if (array_key_exists('result', $decoded))
{
return $decoded['result'];
}
if (array_key_exists('result', $decoded)) return $decoded['result'];
unset($decoded['stat']);
return $decoded;
}
function decrypt_blob($blob, $hex_key)
{
if (!preg_match('/^[a-f0-9]{64}$/', (string)$hex_key))
{
fail_sync('Connector-Schluessel ist ungueltig.');
}
if (!preg_match('/^[a-f0-9]{64}$/', (string)$hex_key)) fail_sync('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_sync('Gespeicherte Zugangsdaten haben ein unbekanntes Format.');
}
if (!is_array($payload) || (int)($payload['v'] ?? 0) !== 1) fail_sync('Gespeicherte 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($hex_key), OPENSSL_RAW_DATA, $iv, $tag);
if ($plain === false)
{
fail_sync('Gespeicherte Zugangsdaten konnten nicht entschluesselt werden.');
}
if ($plain === false) fail_sync('Gespeicherte Zugangsdaten konnten nicht entschluesselt werden.');
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')
{
fail_sync('Verbindung #'.$connection_id.' ist keine WebDAV-Verbindung.');
}
$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:'));
$piwigo_root = rtrim((string)($options['piwigo-root'] ?? ''), '/');
$connection_id = (int)($options['connection-id'] ?? 0);
$base_url = rtrim((string)($options['base-url'] ?? 'http://127.0.0.1'), '/');
if ($piwigo_root === '' || $connection_id < 1)
{
fail_sync('Parameter --piwigo-root und --connection-id werden benoetigt.');
}
if (!function_exists('curl_init'))
{
fail_sync('PHP-cURL ist nicht verfuegbar.');
}
if ($piwigo_root === '' || $connection_id < 1) fail_sync('Parameter --piwigo-root und --connection-id werden benoetigt.');
if (!function_exists('curl_init')) fail_sync('PHP-cURL ist nicht verfuegbar.');
$db_config = $piwigo_root.'/local/config/database.inc.php';
if (!is_readable($db_config))
{
fail_sync('Piwigo-Datenbankkonfiguration ist nicht lesbar.');
}
if (!is_readable($db_config)) fail_sync('Piwigo-Datenbankkonfiguration ist nicht lesbar.');
$conf = array();
$prefixeTable = 'piwigo_';
require $db_config;
foreach (array('db_host','db_user','db_password','db_base') as $key)
{
if (!isset($conf[$key]))
{
fail_sync('Piwigo-Datenbankkonfiguration ist unvollstaendig: '.$key);
}
}
foreach (array('db_host','db_user','db_password','db_base') as $key) if (!isset($conf[$key])) fail_sync('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_sync('Piwigo-Datenbank ist nicht erreichbar: '.$db->connect_error);
}
if ($db->connect_errno) fail_sync('Piwigo-Datenbank ist nicht erreichbar: '.$db->connect_error);
$db->set_charset('utf8mb4');
$key_result = $db->query("SELECT value FROM `{$prefixeTable}config` WHERE param='bratonien_nc_connector_secret' LIMIT 1");
if (!$key_result || !$key_result->num_rows)
{
fail_sync('Connector-Schluessel wurde nicht gefunden.');
}
if (!$key_result || !$key_result->num_rows) fail_sync('Connector-Schluessel wurde nicht gefunden.');
$hex_key = (string)$key_result->fetch_assoc()['value'];
$connection_table = $prefixeTable.'bratonien_tools_nc_connections';
$connection_result = $db->query('SELECT config_json, secret_blob FROM `'.$connection_table.'` WHERE id='.$connection_id.' LIMIT 1');
if (!$connection_result || !$connection_result->num_rows) fail_sync('Connector-Verbindung #'.$connection_id.' wurde nicht gefunden.');
$connection_row = $connection_result->fetch_assoc();
$connection_config = json_decode((string)$connection_row['config_json'], true);
if (!is_array($connection_config)) $connection_config = array();
$connection_plain = decrypt_blob((string)$connection_row['secret_blob'], $hex_key);
$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'=>'');
$api_result = $db->query("SELECT value FROM `{$prefixeTable}config` WHERE param='bratonien_nc_piwigo_api' LIMIT 1");
if ($api_result && $api_result->num_rows)
if (!empty($connection_config['api_enabled']))
{
$api_blob = (string)$api_result->fetch_assoc()['value'];
if ($api_blob !== '')
{
$api_plain = decrypt_blob($api_blob, $hex_key);
$api_decoded = json_decode($api_plain, true);
if (is_array($api_decoded))
{
$api['key_id'] = (string)($api_decoded['key_id'] ?? '');
$api['key_secret'] = (string)($api_decoded['key_secret'] ?? '');
}
}
$api['key_id'] = trim((string)($connection_credentials['api_key_id'] ?? ''));
$api['key_secret'] = trim((string)($connection_credentials['api_key_secret'] ?? ''));
}
$connection_table = $prefixeTable.'bratonien_tools_nc_connections';
$connection_result = $db->query('SELECT secret_blob FROM `'.$connection_table.'` WHERE id='.$connection_id.' LIMIT 1');
if (!$connection_result || !$connection_result->num_rows)
{
fail_sync('Connector-Verbindung #'.$connection_id.' wurde nicht gefunden.');
}
$connection_blob = (string)$connection_result->fetch_assoc()['secret_blob'];
$connection_plain = decrypt_blob($connection_blob, $hex_key);
$connection_credentials = json_decode($connection_plain, true);
if (!is_array($connection_credentials))
{
$connection_credentials = array();
}
$fallback_user = (string)($connection_credentials['piwigo_user'] ?? '');
$fallback_user = trim((string)($connection_credentials['piwigo_user'] ?? ''));
$fallback_password = (string)($connection_credentials['piwigo_password'] ?? '');
$api_error = null;
if ($api['key_id'] !== '' && $api['key_secret'] !== '')
{
try
@@ -284,80 +227,42 @@ 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));
$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);
}
catch (Throwable $e)
{
$api_error = $e->getMessage();
fwrite(STDERR, "Piwigo-API nicht nutzbar: ".$api_error."\n");
fwrite(STDERR, "Piwigo-API nicht nutzbar: ".$e->getMessage()."\n");
}
}
else
{
$api_error = 'Keine gespeicherten API-Zugangsdaten.';
fwrite(STDERR, "Piwigo-API nicht nutzbar: ".$api_error."\n");
fwrite(STDERR, "Piwigo-API nicht nutzbar: Fuer diese Verbindung ist keine API konfiguriert.\n");
}
if ($fallback_user === '' || $fallback_password === '')
{
fail_sync('Kein gespeicherter Benutzername/Passwort-Fallback vorhanden.');
}
if ($fallback_user === '' || $fallback_password === '') fail_sync('Kein gespeicherter Benutzername/Passwort-Fallback fuer diese Verbindung vorhanden.');
$cookie_file = tempnam(sys_get_temp_dir(), 'br-nc-sync-');
if ($cookie_file === false)
{
fail_sync('Temporare Piwigo-Sitzung konnte nicht angelegt werden.');
}
if ($cookie_file === false) fail_sync('Temporare Piwigo-Sitzung konnte nicht angelegt werden.');
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
));
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',
array(
'sync'=>'files',
'display_info'=>1,
'privacy_level'=>0,
'sync_meta'=>1,
'simulate'=>0,
'subcats-included'=>1,
'bratonien_connector'=>1,
'submit'=>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));
$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

View 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.8.21',
));
$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);
}

View File

@@ -0,0 +1,26 @@
#!/usr/bin/env bash
set -Eeuo pipefail
STATE_DIR="${1:-}"
shift || true
[[ -n "$STATE_DIR" ]] || { echo "Connector-State-Verzeichnis fehlt." >&2; exit 2; }
[[ $# -gt 0 ]] || { echo "Warmup-Kommando fehlt." >&2; exit 2; }
SYNC_LOCK="$STATE_DIR/webdav-sync.lock"
WAITER_LOCK="$STATE_DIR/webdav-cache-warmup-after-sync.lock"
# Pro Verbindung darf genau ein wartender Cache-Start existieren. Dadurch
# erzeugen wiederholte Klicks im Adminbereich keine Warteschlange aus Workern.
exec 8>"$WAITER_LOCK"
flock -n 8 || exit 0
# Der Connector hält diesen Lock exklusiv. Wir warten blockierend, ohne dabei
# Nextcloud-Dateien oder den Worker-Index anzufassen. Sobald der Connector den
# Lock freigibt, geben wir unseren kurzen Leselock sofort wieder frei und
# starten den normalen Worker. Dessen eigene Guards bleiben damit maßgeblich.
exec 9<>"$SYNC_LOCK"
flock -s 9
flock -u 9
exec "$@"

View File

@@ -0,0 +1,41 @@
#!/usr/bin/env bash
set -Eeuo pipefail
STATE_DIR="${1:-}"
shift || true
[[ -n "$STATE_DIR" ]] || { echo "Connector-State-Verzeichnis fehlt." >&2; exit 2; }
[[ $# -gt 0 ]] || { echo "Warmup-Kommando fehlt." >&2; exit 2; }
PRIORITY_FILE="$STATE_DIR/webdav-cache-warmup-priority-sync"
ATTEMPTS=0
MAX_ATTEMPTS=3600
# Der Dispatcher setzt die Prioritätsmarke vor dem Start. Falls bereits ein
# Warmup läuft, beendet der zusätzliche Worker sich wegen seines Prozess-Locks
# sofort und lässt die Marke unangetastet. Wir probieren deshalb erst dann
# erneut, wenn die Marke noch vorhanden ist. Sobald ein Sync-Worker den Lock
# tatsächlich übernimmt, entfernt er die Marke selbst und arbeitet den neuen
# Bestand ab. Dadurch geht die Sofort-Priorität nicht verloren und es gibt nie
# zwei gleichzeitig arbeitende Warmup-Worker derselben Verbindung.
while [[ -f "$PRIORITY_FILE" ]]; do
ATTEMPTS=$((ATTEMPTS + 1))
if [[ "$ATTEMPTS" -gt "$MAX_ATTEMPTS" ]]; then
echo "Priorisierter WebDAV-Warmup wartet seit zu langer Zeit auf den aktiven Worker." >&2
exit 3
fi
set +e
"$@"
result=$?
set -e
if [[ "$result" -ne 0 ]]; then
exit "$result"
fi
[[ -f "$PRIORITY_FILE" ]] || exit 0
sleep 1
done
exit 0

View File

@@ -12,6 +12,7 @@ from pathlib import Path
ALLOWED = frozenset("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.")
GERMAN = str.maketrans({"ä": "ae", "ö": "oe", "ü": "ue", "Ä": "Ae", "Ö": "Oe", "Ü": "Ue", "ß": "ss", "": "SS"})
SHADOW_DIR_MODE = 0o777
def safe_name(name: str) -> str:
@@ -56,12 +57,7 @@ def load_manifest(path: Path) -> list[dict[str, str]]:
share_id, item_type, display_name, source_path = fields
if item_type not in {"folder", "file"}:
raise ValueError(f"{path}:{line_number}: unsupported item_type {item_type!r}")
entries.append({
"share_id": share_id,
"item_type": item_type,
"display_name": display_name,
"source_path": source_path,
})
entries.append({"share_id": share_id, "item_type": item_type, "display_name": display_name, "source_path": source_path})
return entries
@@ -84,11 +80,15 @@ def preferred_target(source_key: str, raw_name: str, parent_target: Path, old_ma
return safe_name(raw_name)
def ensure_shadow_directory(path: Path) -> None:
path.mkdir(parents=True, exist_ok=True)
path.chmod(SHADOW_DIR_MODE)
def mirror_directory(source: Path, target: Path, source_key: str, target_key: Path, old_map: dict[str, str], new_map: dict[str, str]) -> None:
target.mkdir(parents=True, exist_ok=True)
ensure_shadow_directory(target)
used: set[str] = set()
children = sorted(source.iterdir(), key=lambda item: (item.name.casefold(), item.name))
for child in children:
for child in sorted(source.iterdir(), key=lambda item: (item.name.casefold(), item.name)):
if child.is_symlink():
continue
child_source_key = f"{source_key}/{child.name}"
@@ -103,51 +103,68 @@ def mirror_directory(source: Path, target: Path, source_key: str, target_key: Pa
child_target.symlink_to(child.resolve())
def remove_tree(path: Path) -> None:
if path.is_symlink() or path.is_file():
path.unlink(missing_ok=True)
elif path.exists():
shutil.rmtree(path)
def build(manifest: Path, destination: Path, state_file: Path) -> None:
entries = load_manifest(manifest)
old_map = load_map(state_file)
new_map: dict[str, str] = {}
staging = destination.with_name(f".{destination.name}.next")
previous = destination.with_name(f".{destination.name}.previous")
if staging.exists():
shutil.rmtree(staging)
staging.mkdir(parents=True)
used_roots: set[str] = set()
for entry in sorted(entries, key=lambda item: (item["display_name"].casefold(), item["share_id"])):
source = Path(entry["source_path"])
source_key = f"share:{entry['share_id']}"
preferred = preferred_target(source_key, entry["display_name"], Path("."), old_map)
is_file_share = entry["item_type"] == "file"
root_name = unique_name(preferred, used_roots, is_file_share)
root_key = Path(root_name)
new_map[source_key] = root_key.as_posix()
if is_file_share:
if not source.is_file():
raise FileNotFoundError(f"source is not a readable file: {source}")
(staging / root_name).symlink_to(source.resolve())
continue
if not source.is_dir():
raise FileNotFoundError(f"source is not a readable directory: {source}")
mirror_directory(source, staging / root_name, source_key, root_key, old_map, new_map)
state_staging = state_file.with_suffix(state_file.suffix + ".next")
state_staging.parent.mkdir(parents=True, exist_ok=True)
with state_staging.open("w", encoding="utf-8") as handle:
json.dump(new_map, handle, ensure_ascii=False, indent=2, sort_keys=True)
handle.write("\n")
if previous.exists():
shutil.rmtree(previous)
if destination.exists():
destination.rename(previous)
staging.rename(destination)
state_staging.replace(state_file)
if previous.exists():
shutil.rmtree(previous)
remove_tree(staging)
remove_tree(previous)
if state_staging.exists():
state_staging.unlink()
ensure_shadow_directory(staging)
try:
used_roots: set[str] = set()
for entry in sorted(entries, key=lambda item: (item["display_name"].casefold(), item["share_id"])):
source = Path(entry["source_path"])
source_key = f"share:{entry['share_id']}"
preferred = preferred_target(source_key, entry["display_name"], Path("."), old_map)
is_file_share = entry["item_type"] == "file"
root_name = unique_name(preferred, used_roots, is_file_share)
root_key = Path(root_name)
new_map[source_key] = root_key.as_posix()
if is_file_share:
if not source.is_file():
raise FileNotFoundError(f"source is not a readable file: {source}")
(staging / root_name).symlink_to(source.resolve())
else:
if not source.is_dir():
raise FileNotFoundError(f"source is not a readable directory: {source}")
mirror_directory(source, staging / root_name, source_key, root_key, old_map, new_map)
state_staging.parent.mkdir(parents=True, exist_ok=True)
with state_staging.open("w", encoding="utf-8") as handle:
json.dump(new_map, handle, ensure_ascii=False, indent=2, sort_keys=True)
handle.write("\n")
had_destination = destination.exists()
if had_destination:
destination.rename(previous)
try:
staging.rename(destination)
state_staging.replace(state_file)
except Exception:
remove_tree(destination)
if had_destination and previous.exists():
previous.rename(destination)
raise
remove_tree(previous)
except Exception:
remove_tree(staging)
if state_staging.exists():
state_staging.unlink()
raise
def main() -> int:

View File

@@ -0,0 +1,125 @@
#!/usr/bin/env php
<?php
if (PHP_SAPI !== 'cli')
{
fwrite(STDERR, "CLI only\n");
exit(1);
}
$options = getopt('', array('piwigo-root:', 'connection-id:', 'mapping:'));
$piwigo_root = rtrim((string)($options['piwigo-root'] ?? ''), '/');
$connection_id = (int)($options['connection-id'] ?? 0);
$mapping_file = (string)($options['mapping'] ?? '');
if ($piwigo_root === '' || $connection_id < 1 || $mapping_file === '' || !is_readable($mapping_file))
{
fwrite(STDERR, "Parameter --piwigo-root, --connection-id und --mapping werden benoetigt.\n");
exit(1);
}
$mapping = json_decode((string)file_get_contents($mapping_file), true);
if (!is_array($mapping) || !isset($mapping['files']) || !is_array($mapping['files']))
{
fwrite(STDERR, "WebDAV-Mapping ist ungueltig.\n");
exit(1);
}
$dimensions = array();
$mapped_files = 0;
foreach ($mapping['files'] as $path => $entry)
{
if (!is_array($entry) || (string)($entry['kind'] ?? '') !== 'file') continue;
$mapped_files++;
$width = (int)($entry['width'] ?? 0);
$height = (int)($entry['height'] ?? 0);
if ($width < 1 || $height < 1) continue;
$dimensions[str_replace('\\', '/', (string)$path)] = array($width, $height);
}
if ($mapped_files === 0)
{
echo "WebDAV-Metadaten: keine aktuellen Bildquellen vorhanden.\n";
exit(0);
}
// Nextcloud liefert die Bildabmessungen ueber WebDAV nicht fuer jede Datei.
// Das ist kein Fehler des Connector-Syncs: die Dateien und ihr Shadow Tree
// sind trotzdem gueltig und Piwigo kann die Bildquelle spaeter bei Bedarf
// materialisieren. Vorhandene Abmessungen werden uebernommen, fehlende Werte
// bleiben unangetastet. Nur ein syntaktisch/technisch ungueltiges Mapping ist
// oben weiterhin fatal.
if (!$dimensions)
{
echo 'WebDAV-Metadaten: bilder='.$mapped_files.' aktualisiert=0 ohne_masse='.$mapped_files." (Nextcloud lieferte keine Bildabmessungen; Synchronisierung bleibt gueltig)\n";
exit(0);
}
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/sync-webdav-metadata.php';
$_SERVER['PHP_SELF'] = $_SERVER['SCRIPT_NAME'];
$_SERVER['QUERY_STRING'] = '';
$_SERVER['HTTP_USER_AGENT'] = 'Bratonien-WebDAV-Metadata/0.9.7.1.47';
$_SERVER['HTTPS'] = 'off';
require_once(PHPWG_ROOT_PATH.'include/common.inc.php');
$checked = 0;
$updated = 0;
$missing = 0;
$result = pwg_query('SELECT id, path, width, height FROM '.IMAGES_TABLE.' ORDER BY id');
while ($row = pwg_db_fetch_assoc($result))
{
$path = (string)($row['path'] ?? '');
if ($path === '') continue;
$absolute = $path;
if (strpos($absolute, '/') !== 0)
{
$absolute = PHPWG_ROOT_PATH.ltrim(preg_replace('#^\./#', '', $absolute), '/');
}
$normalized_shadow = str_replace('\\', '/', $absolute);
if (strpos($normalized_shadow, '/nc-webdav-gallery/connection-'.$connection_id.'/') === false) continue;
$checked++;
$resolved = realpath($absolute);
if ($resolved === false)
{
$missing++;
continue;
}
$key = str_replace('\\', '/', $resolved);
if (!isset($dimensions[$key]))
{
$missing++;
continue;
}
list($width, $height) = $dimensions[$key];
if ((int)$row['width'] === $width && (int)$row['height'] === $height) continue;
pwg_query('UPDATE '.IMAGES_TABLE.' SET width='.$width.', height='.$height.' WHERE id='.(int)$row['id']);
$updated++;
}
if ($updated > 0)
{
if (function_exists('update_category')) update_category('all');
if (function_exists('invalidate_user_cache')) invalidate_user_cache(true);
}
echo 'WebDAV-Metadaten: bilder='.$checked.' aktualisiert='.$updated.' ohne_masse='.$missing;
if ($missing > 0)
{
echo ' (fehlende WebDAV-Abmessungen sind nicht fatal)';
}
echo "\n";
exit(0);

View File

@@ -0,0 +1,844 @@
<?php
if (PHP_SAPI !== 'cli')
{
http_response_code(404);
exit;
}
$piwigo_root = realpath(dirname(__DIR__, 4));
if ($piwigo_root === false)
{
fwrite(STDERR, "Piwigo-Root wurde nicht gefunden.\n");
exit(1);
}
define('PHPWG_ROOT_PATH', rtrim($piwigo_root, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR);
$_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/webdav-cache-warmup.php';
$_SERVER['PHP_SELF'] = $_SERVER['SCRIPT_NAME'];
$_SERVER['QUERY_STRING'] = '';
$_SERVER['HTTP_USER_AGENT'] = 'Bratonien-WebDAV-Cache-Worker/0.9.7.1.30';
$_SERVER['HTTPS'] = 'off';
require_once(PHPWG_ROOT_PATH.'include/common.inc.php');
if (!defined('BRATONIEN_TOOLS_PATH'))
{
fwrite(STDERR, "Bratonien Tools ist nicht aktiv.\n");
exit(1);
}
require_once(BRATONIEN_TOOLS_PATH.'include/nc_connector.inc.php');
require_once(BRATONIEN_TOOLS_PATH.'include/webdav_source_index.inc.php');
require_once(BRATONIEN_TOOLS_PATH.'include/webdav_warmup_settings.inc.php');
function bratonien_tools_cache_warmup_log($event, array $fields=array())
{
$parts = array('[BRAT-WORKER]', $event);
foreach ($fields as $key=>$value)
{
if (is_bool($value)) $value = $value ? '1' : '0';
elseif ($value === null) $value = 'NULL';
elseif (is_array($value) || is_object($value)) $value = json_encode($value, JSON_UNESCAPED_SLASHES);
$parts[] = $key.'='.str_replace(array("\r", "\n"), array('\\r', '\\n'), (string)$value);
}
fwrite(STDOUT, implode(' ', $parts)."\n");
}
function bratonien_tools_cache_warmup_status_file($connection_id)
{
return PHPWG_ROOT_PATH.PWG_LOCAL_DIR.'bratonien-webdav-warmup.status-'.(int)$connection_id.'.json';
}
function bratonien_tools_cache_warmup_cancel_file($connection_id)
{
return PHPWG_ROOT_PATH.PWG_LOCAL_DIR.'bratonien-webdav-warmup.cancel-'.(int)$connection_id;
}
function bratonien_tools_cache_warmup_cancel_pending($connection_id)
{
return is_file(bratonien_tools_cache_warmup_cancel_file($connection_id));
}
function bratonien_tools_cache_warmup_priority_file($state_dir)
{
return rtrim((string)$state_dir, '/').'/webdav-cache-warmup-priority-sync';
}
function bratonien_tools_cache_warmup_priority_pending($priority_file)
{
return is_string($priority_file) && $priority_file !== '' && is_file($priority_file);
}
function bratonien_tools_cache_warmup_write_json($file, array $payload)
{
$directory = dirname($file);
if (!is_dir($directory) && !@mkdir($directory, 0775, true) && !is_dir($directory))
{
throw new RuntimeException('Worker-Statusverzeichnis konnte nicht angelegt werden.');
}
$json = json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
if ($json === false) throw new RuntimeException('Worker-Status konnte nicht serialisiert werden.');
$tmp = $file.'.tmp-'.bin2hex(random_bytes(4));
if (@file_put_contents($tmp, $json."\n", LOCK_EX) === false) throw new RuntimeException('Worker-Status konnte nicht geschrieben werden.');
@chmod($tmp, 0664);
if (!@rename($tmp, $file))
{
@unlink($tmp);
throw new RuntimeException('Worker-Status konnte nicht atomar gespeichert werden.');
}
}
function bratonien_tools_cache_warmup_status($connection_id, $state, $message, array $extra=array())
{
bratonien_tools_cache_warmup_write_json(
bratonien_tools_cache_warmup_status_file($connection_id),
array_merge(array(
'state'=>$state,
'message'=>$message,
'connection_id'=>(int)$connection_id,
'updated_at'=>time(),
), $extra)
);
}
function bratonien_tools_cache_warmup_credentials($connection_id)
{
$connection = bratonien_tools_nc_connector_connection((int)$connection_id, true);
if (!$connection || empty($connection['enabled'])) return null;
$plain = bratonien_tools_nc_connector_decrypt_secret((string)($connection['secret_blob'] ?? ''));
$secret = json_decode($plain, true);
if (!is_array($secret)) return null;
$config = isset($connection['config']) && is_array($connection['config']) ? $connection['config'] : array();
$base_url = rtrim((string)($config['nextcloud_url'] ?? ''), '/');
$user = trim((string)($secret['nextcloud_user'] ?? ''));
$password = (string)($secret['nextcloud_password'] ?? '');
$state_dir = rtrim((string)($config['state_dir'] ?? ''), '/');
$gallery_root = rtrim((string)($config['parallel_gallery_root'] ?? ''), '/');
if ($base_url === '' || $user === '' || $password === '' || $state_dir === '' || $gallery_root === '') return null;
return array(
'connection'=>$connection,
'config'=>$config,
'base_url'=>$base_url,
'user'=>$user,
'password'=>$password,
'state_dir'=>$state_dir,
'gallery_root'=>$gallery_root,
);
}
function bratonien_tools_cache_warmup_load_json($file, $label)
{
if (!is_file($file) || !is_readable($file)) throw new RuntimeException($label.' fehlt oder ist nicht lesbar: '.$file);
$raw = @file_get_contents($file);
$data = $raw !== false ? json_decode($raw, true) : null;
if (!is_array($data)) throw new RuntimeException($label.' enthält kein gültiges JSON.');
return $data;
}
function bratonien_tools_cache_warmup_normalize_path($path)
{
return rtrim(str_replace('\\', '/', (string)$path), '/');
}
function bratonien_tools_cache_warmup_scan($connection_id, array $credentials)
{
$state_dir = $credentials['state_dir'];
$gallery_root = $credentials['gallery_root'];
$mapping = bratonien_tools_cache_warmup_load_json($state_dir.'/webdav-map.json', 'WebDAV-Mapping');
$files = isset($mapping['files']) && is_array($mapping['files']) ? $mapping['files'] : array();
if (!$files) throw new RuntimeException('WebDAV-Mapping enthält keine Quellen.');
if (!is_dir($gallery_root)) throw new RuntimeException('Shadow-Tree fehlt: '.$gallery_root);
$by_source = array();
foreach ($files as $path=>$meta)
{
if (!is_array($meta) || (string)($meta['kind'] ?? '') !== 'file') continue;
$normalized = bratonien_tools_cache_warmup_normalize_path($path);
$by_source[$normalized] = $meta;
}
$sources = array();
$seen_targets = array();
$gallery_prefix = bratonien_tools_cache_warmup_normalize_path(realpath($gallery_root) ?: $gallery_root).'/';
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($gallery_root, FilesystemIterator::SKIP_DOTS),
RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($iterator as $item)
{
$shadow_absolute = $item->getPathname();
if (!is_link($shadow_absolute)) continue;
$resolved = realpath($shadow_absolute);
if ($resolved === false || !is_file($resolved)) throw new RuntimeException('Shadow-Link zeigt auf keine lesbare Quelle: '.$shadow_absolute);
$resolved = bratonien_tools_cache_warmup_normalize_path($resolved);
if (!isset($by_source[$resolved])) throw new RuntimeException('Shadow-Link besitzt keinen Eintrag im Connector-Mapping: '.$shadow_absolute);
if (isset($seen_targets[$resolved])) throw new RuntimeException('Sicherheitsabbruch: dieselbe Connector-Quelle ist mehrfach im Shadow-Tree verknüpft: '.$resolved);
$seen_targets[$resolved] = true;
$shadow_normalized = bratonien_tools_cache_warmup_normalize_path($shadow_absolute);
if (strpos($shadow_normalized.'/', $gallery_prefix) !== 0) throw new RuntimeException('Shadow-Datei liegt außerhalb der erwarteten Galerie-Wurzel.');
$shadow_relative = ltrim(substr($shadow_normalized, strlen(rtrim($gallery_prefix, '/'))), '/');
if ($shadow_relative === '') throw new RuntimeException('Leerer relativer Shadow-Pfad erkannt.');
$meta = $by_source[$resolved];
$root_fileid = 0;
if (preg_match('#/root-([0-9]+)/#', $resolved.'/', $m)) $root_fileid = (int)$m[1];
if ($root_fileid < 1) throw new RuntimeException('Connector-Wurzel konnte aus der Placeholder-Quelle nicht bestimmt werden: '.$resolved);
$source = array(
'connection_id'=>(int)$connection_id,
'root_fileid'=>$root_fileid,
'fileid'=>(int)($meta['fileid'] ?? 0),
'webdav_path'=>trim((string)($meta['webdav_path'] ?? ''), '/'),
'content_type'=>(string)($meta['content_type'] ?? ''),
'size'=>(int)($meta['size'] ?? 0),
'etag'=>(string)($meta['etag'] ?? ''),
'width'=>(int)($meta['width'] ?? 0),
'height'=>(int)($meta['height'] ?? 0),
);
if ($source['webdav_path'] === '') throw new RuntimeException('Connector-Mapping enthält für '.$shadow_relative.' keinen WebDAV-Pfad.');
$key = bratonien_tools_webdav_source_index_key($source);
if (isset($sources[$key])) throw new RuntimeException('Doppelte Quellenidentität im Shadow-Tree: '.$key);
$sources[$key] = array(
'index_key'=>$key,
'signature'=>bratonien_tools_webdav_source_index_signature($source),
'source'=>$source,
'source_path'=>$resolved,
'shadow_absolute'=>$shadow_absolute,
'shadow_relative'=>$shadow_relative,
);
}
return array('sources'=>$sources);
}
function bratonien_tools_cache_warmup_select(array $scan, array $index, $mode)
{
if ($mode === 'rebuild') return $scan['sources'];
$selected = array();
foreach ($scan['sources'] as $key=>$item)
{
$entry = isset($index['sources'][$key]) && is_array($index['sources'][$key]) ? $index['sources'][$key] : null;
if ($entry === null || !bratonien_tools_webdav_source_index_is_current($entry, $item['signature'])) $selected[$key] = $item;
}
return $selected;
}
function bratonien_tools_cache_warmup_quote_path($path)
{
$parts = array_values(array_filter(explode('/', trim((string)$path, '/')), 'strlen'));
return implode('/', array_map('rawurlencode', $parts));
}
function bratonien_tools_cache_warmup_download(array $source, array $credentials, $destination, &$detail=null)
{
$detail = '';
$webdav_path = trim((string)($source['webdav_path'] ?? ''), '/');
if ($webdav_path === '') { $detail = 'WebDAV-Pfad fehlt.'; return false; }
$fp = @fopen($destination, 'xb');
if (!$fp) { $detail = 'Temporäre Quelldatei konnte nicht angelegt werden.'; return false; }
$url = $credentials['base_url'].'/remote.php/dav/files/'.rawurlencode($credentials['user']).'/'.bratonien_tools_cache_warmup_quote_path($webdav_path);
$ch = curl_init($url);
curl_setopt_array($ch, array(
CURLOPT_FOLLOWLOCATION=>false,
CURLOPT_CONNECTTIMEOUT=>10,
CURLOPT_TIMEOUT=>300,
CURLOPT_HTTPAUTH=>CURLAUTH_BASIC,
CURLOPT_USERPWD=>$credentials['user'].':'.$credentials['password'],
CURLOPT_RETURNTRANSFER=>false,
CURLOPT_FAILONERROR=>false,
CURLOPT_FILE=>$fp,
CURLOPT_USERAGENT=>'Bratonien-WebDAV-Cache-Worker/0.9.7.1.30',
));
$ok = curl_exec($ch);
$errno = curl_errno($ch);
$error = curl_error($ch);
$http = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
fclose($fp);
if ($ok === false || $errno !== 0 || $http < 200 || $http >= 300)
{
@unlink($destination);
$detail = 'Nextcloud-Download fehlgeschlagen (HTTP '.$http.', cURL '.$errno.($error !== '' ? ': '.$error : '').').';
return false;
}
if (!is_file($destination) || filesize($destination) < 1 || @getimagesize($destination) === false)
{
@unlink($destination);
$detail = 'Geladene Datei ist kein lesbares vollständiges Bild.';
return false;
}
return true;
}
function bratonien_tools_cache_warmup_sync_guard(array $credentials, &$handle=null, &$detail=null)
{
$handle = null;
$detail = '';
$handle = @fopen($credentials['state_dir'].'/webdav-sync.lock', 'c');
if (!$handle) { $detail = 'Connector-Sync-Lock konnte nicht geöffnet werden.'; return false; }
if (!@flock($handle, LOCK_SH | LOCK_NB))
{
fclose($handle);
$handle = null;
$detail = 'Connector-Synchronisierung läuft.';
return false;
}
return true;
}
function bratonien_tools_cache_warmup_source_lock($index_key, &$handle=null)
{
$dir = PHPWG_ROOT_PATH.'upload/bratonien-webdav-materialize';
if (!is_dir($dir) && !@mkdir($dir, 0775, true) && !is_dir($dir)) return false;
$handle = @fopen($dir.'/source-'.sha1((string)$index_key).'.lock', 'c');
if (!$handle) return false;
return @flock($handle, LOCK_EX);
}
function bratonien_tools_cache_warmup_unlock(&$handle)
{
if (is_resource($handle))
{
@flock($handle, LOCK_UN);
fclose($handle);
}
$handle = null;
}
function bratonien_tools_cache_warmup_fresh_source(array $item, array $credentials)
{
$mapping = bratonien_tools_cache_warmup_load_json($credentials['state_dir'].'/webdav-map.json', 'WebDAV-Mapping');
$files = isset($mapping['files']) && is_array($mapping['files']) ? $mapping['files'] : array();
$wanted = bratonien_tools_cache_warmup_normalize_path($item['source_path']);
foreach ($files as $path=>$meta)
{
if (bratonien_tools_cache_warmup_normalize_path($path) !== $wanted || !is_array($meta)) continue;
$source = array(
'connection_id'=>(int)$item['source']['connection_id'],
'root_fileid'=>(int)$item['source']['root_fileid'],
'fileid'=>(int)($meta['fileid'] ?? 0),
'webdav_path'=>trim((string)($meta['webdav_path'] ?? ''), '/'),
'content_type'=>(string)($meta['content_type'] ?? ''),
'size'=>(int)($meta['size'] ?? 0),
'etag'=>(string)($meta['etag'] ?? ''),
'width'=>(int)($meta['width'] ?? 0),
'height'=>(int)($meta['height'] ?? 0),
);
return $source;
}
return null;
}
function bratonien_tools_cache_warmup_restore($source_path, $backup, $staging, $original_size, $original_hash, &$detail=null)
{
$detail = '';
@unlink($staging);
if (is_file($source_path) || is_link($source_path))
{
if (!@unlink($source_path)) { $detail = 'Temporäre Quelle konnte nicht entfernt werden.'; return false; }
}
if (!is_file($backup)) { $detail = 'Placeholder-Backup fehlt.'; return false; }
if (!@rename($backup, $source_path)) { $detail = 'Placeholder konnte nicht restauriert werden.'; return false; }
clearstatcache(true, $source_path);
if (!is_file($source_path)) { $detail = 'Restaurierter Placeholder fehlt.'; return false; }
if ((int)filesize($source_path) !== (int)$original_size) { $detail = 'Restaurierter Placeholder hat eine unerwartete Größe.'; return false; }
$hash = @sha1_file($source_path);
if (!is_string($hash) || !hash_equals($original_hash, $hash)) { $detail = 'Restaurierter Placeholder stimmt nicht mit dem Originalzustand überein.'; return false; }
return true;
}
function bratonien_tools_cache_warmup_call_piwigo(array $item, $stage, &$detail=null)
{
$detail = '';
$bridge = BRATONIEN_TOOLS_PATH.'runtime/lib/piwigo-cache-request-by-shadow.php';
if (!is_file($bridge)) { $detail = 'Piwigo-Shadow-Bridge fehlt.'; return false; }
if (!function_exists('exec')) { $detail = 'PHP exec() ist deaktiviert.'; return false; }
$output = array();
$exit = 1;
$command = escapeshellarg(PHP_BINARY).' '.escapeshellarg($bridge)
.' --connection-id='.(int)$item['source']['connection_id']
.' --shadow-relative='.escapeshellarg($item['shadow_relative'])
.' --stage='.(int)$stage.' 2>&1';
@exec($command, $output, $exit);
if ($exit !== 0)
{
$detail = $output ? implode(' ', array_slice($output, -4)) : 'Piwigo-Shadow-Bridge Exit '.$exit;
return false;
}
$detail = $output ? (string)end($output) : '';
return true;
}
function bratonien_tools_cache_warmup_process(array $item, $temp_file, array $credentials, $stage)
{
$source_lock = null;
if (!bratonien_tools_cache_warmup_source_lock($item['index_key'], $source_lock))
{
return array('ok'=>false, 'defer'=>true, 'message'=>'Quellen-Lock konnte nicht gesetzt werden.');
}
$sync_lock = null;
$detail = '';
if (!bratonien_tools_cache_warmup_sync_guard($credentials, $sync_lock, $detail))
{
bratonien_tools_cache_warmup_unlock($source_lock);
return array('ok'=>false, 'defer'=>true, 'message'=>$detail);
}
$fresh = bratonien_tools_cache_warmup_fresh_source($item, $credentials);
if (!$fresh || bratonien_tools_webdav_source_index_signature($fresh) !== $item['signature'])
{
bratonien_tools_cache_warmup_unlock($sync_lock);
bratonien_tools_cache_warmup_unlock($source_lock);
return array('ok'=>false, 'defer'=>true, 'message'=>'Connector-Mapping hat sich seit dem Batch-Download geändert.');
}
if (!is_link($item['shadow_absolute']) || bratonien_tools_cache_warmup_normalize_path(realpath($item['shadow_absolute']) ?: '') !== bratonien_tools_cache_warmup_normalize_path($item['source_path']))
{
bratonien_tools_cache_warmup_unlock($sync_lock);
bratonien_tools_cache_warmup_unlock($source_lock);
return array('ok'=>false, 'defer'=>true, 'message'=>'Shadow-Tree hat sich seit dem Batch-Download geändert.');
}
$source_path = $item['source_path'];
if (!is_file($source_path) || !is_readable($source_path) || !is_file($temp_file) || @getimagesize($temp_file) === false)
{
bratonien_tools_cache_warmup_unlock($sync_lock);
bratonien_tools_cache_warmup_unlock($source_lock);
return array('ok'=>false, 'message'=>'Placeholder oder Batch-Quelle ist nicht vollständig lesbar.');
}
$placeholder_size = filesize($source_path);
$placeholder_hash = @sha1_file($source_path);
if (!is_string($placeholder_hash))
{
bratonien_tools_cache_warmup_unlock($sync_lock);
bratonien_tools_cache_warmup_unlock($source_lock);
return array('ok'=>false, 'fatal'=>true, 'message'=>'Placeholder konnte vor dem Swap nicht verifiziert werden.');
}
$request_id = substr(bin2hex(random_bytes(8)), 0, 8);
$backup = $source_path.'.bratonien-placeholder-'.$request_id;
$staging = $source_path.'.bratonien-source-'.$request_id;
if (file_exists($backup) || file_exists($staging))
{
bratonien_tools_cache_warmup_unlock($sync_lock);
bratonien_tools_cache_warmup_unlock($source_lock);
return array('ok'=>false, 'fatal'=>true, 'message'=>'Unerwartete Swap-Datei ist bereits vorhanden.');
}
if (!@copy($temp_file, $staging) || @getimagesize($staging) === false)
{
@unlink($staging);
bratonien_tools_cache_warmup_unlock($sync_lock);
bratonien_tools_cache_warmup_unlock($source_lock);
return array('ok'=>false, 'message'=>'Batch-Quelle konnte nicht sicher neben dem Placeholder bereitgestellt werden.');
}
$swapped = false;
try
{
if (!@rename($source_path, $backup)) throw new RuntimeException('Placeholder konnte nicht atomar gesichert werden.');
if (!@rename($staging, $source_path))
{
@rename($backup, $source_path);
throw new RuntimeException('Temporäre Quelle konnte nicht atomar eingesetzt werden.');
}
$swapped = true;
clearstatcache(true, $source_path);
if (@getimagesize($source_path) === false) throw new RuntimeException('Shadow-Quelle enthält nach dem Swap kein lesbares Bild.');
$bridge_detail = '';
if (!bratonien_tools_cache_warmup_call_piwigo($item, $stage, $bridge_detail))
{
throw new RuntimeException('Piwigo-Verarbeitung fehlgeschlagen: '.$bridge_detail);
}
}
catch (Throwable $e)
{
$restore_detail = '';
$restored = $swapped
? bratonien_tools_cache_warmup_restore($source_path, $backup, $staging, $placeholder_size, $placeholder_hash, $restore_detail)
: true;
if (!$swapped) @unlink($staging);
bratonien_tools_cache_warmup_unlock($sync_lock);
bratonien_tools_cache_warmup_unlock($source_lock);
if (!$restored) return array('ok'=>false, 'fatal'=>true, 'message'=>$e->getMessage().' RESTORE FEHLGESCHLAGEN: '.$restore_detail);
return array('ok'=>false, 'message'=>$e->getMessage());
}
$restore_detail = '';
$restored = bratonien_tools_cache_warmup_restore($source_path, $backup, $staging, $placeholder_size, $placeholder_hash, $restore_detail);
bratonien_tools_cache_warmup_unlock($sync_lock);
bratonien_tools_cache_warmup_unlock($source_lock);
if (!$restored) return array('ok'=>false, 'fatal'=>true, 'message'=>'RESTORE FEHLGESCHLAGEN: '.$restore_detail);
return array('ok'=>true, 'message'=>'Piwigo hat den Shadow-Pfad verarbeitet.');
}
function bratonien_tools_cache_warmup_stage_pending(array $selected, array $index, $stage)
{
$pending = array();
$field = $stage === 1 ? 'stage1_signature' : 'stage2_signature';
foreach ($selected as $key=>$item)
{
$entry = isset($index['sources'][$key]) && is_array($index['sources'][$key]) ? $index['sources'][$key] : array();
if (!isset($entry[$field]) || !hash_equals((string)$entry[$field], $item['signature'])) $pending[$key] = $item;
}
return $pending;
}
function bratonien_tools_cache_warmup_stage_completed_count(array $selected, array $index, $stage)
{
return count($selected) - count(bratonien_tools_cache_warmup_stage_pending($selected, $index, $stage));
}
function bratonien_tools_cache_warmup_run_stage($connection_id, $stage, array $selected, array &$index, array $credentials, $batch_size, $priority_file='')
{
$pending = bratonien_tools_cache_warmup_stage_pending($selected, $index, $stage);
if (!$pending) return array('failed'=>0, 'deferred'=>0, 'waiting'=>false, 'preempted'=>false, 'cancelled'=>false, 'completed'=>0);
if (bratonien_tools_cache_warmup_cancel_pending($connection_id))
{
return array('failed'=>0, 'deferred'=>0, 'waiting'=>false, 'preempted'=>false, 'cancelled'=>true, 'completed'=>0);
}
if ($stage === 2 && bratonien_tools_cache_warmup_priority_pending($priority_file))
{
return array('failed'=>0, 'deferred'=>0, 'waiting'=>false, 'preempted'=>true, 'cancelled'=>false, 'completed'=>0);
}
$temp_root = PHPWG_ROOT_PATH.'upload/bratonien-webdav-warmup';
if (!is_dir($temp_root) && !@mkdir($temp_root, 0775, true) && !is_dir($temp_root)) throw new RuntimeException('Worker-Temp-Verzeichnis konnte nicht angelegt werden.');
$failed = 0;
$deferred = 0;
$completed = 0;
$batch_number = 0;
foreach (array_chunk(array_keys($pending), max(1, (int)$batch_size)) as $keys)
{
// Harte Batch-Grenze: Sobald ein Abbruchsignal existiert, darf dieser
// Batch gar nicht mehr begonnen und damit auch kein weiteres Original
// aus Nextcloud geladen werden.
if (bratonien_tools_cache_warmup_cancel_pending($connection_id))
{
return array('failed'=>$failed, 'deferred'=>$deferred, 'waiting'=>false, 'preempted'=>false, 'cancelled'=>true, 'completed'=>$completed);
}
if ($stage === 2 && bratonien_tools_cache_warmup_priority_pending($priority_file))
{
return array('failed'=>$failed, 'deferred'=>$deferred, 'waiting'=>false, 'preempted'=>true, 'cancelled'=>false, 'completed'=>$completed);
}
// Der Connector-Lock wird VOR jedem Download geprueft und fuer den
// kompletten Batch gemeinsam gehalten. Ist der Connector aktiv, werden
// exakt null Bilder dieses Batches geladen.
$batch_sync_lock = null;
$batch_sync_detail = '';
if (!bratonien_tools_cache_warmup_sync_guard($credentials, $batch_sync_lock, $batch_sync_detail))
{
bratonien_tools_cache_warmup_status($connection_id, 'waiting', 'Connector-Synchronisierung läuft. Der nächste Batch startet erst danach; es wurden für diesen Batch keine Nextcloud-Originale geladen.', array(
'stage'=>$stage,
'batch'=>$batch_number + 1,
'selected_total'=>count($selected),
'stage_completed'=>$completed,
'deferred_by_connector'=>true,
));
return array('failed'=>$failed, 'deferred'=>$deferred, 'waiting'=>true, 'preempted'=>false, 'cancelled'=>false, 'completed'=>$completed);
}
$batch_number++;
$dir = $temp_root.'/connection-'.(int)$connection_id.'-stage'.$stage.'-'.date('YmdHis').'-'.bin2hex(random_bytes(4));
if (!@mkdir($dir, 0775, true) && !is_dir($dir))
{
bratonien_tools_cache_warmup_unlock($batch_sync_lock);
throw new RuntimeException('Worker-Batch-Verzeichnis konnte nicht angelegt werden.');
}
$downloads = array();
foreach ($keys as $key)
{
$file = $dir.'/'.sha1($key).'.img';
$detail = '';
if (bratonien_tools_cache_warmup_download($pending[$key]['source'], $credentials, $file, $detail)) $downloads[$key] = $file;
else
{
$failed++;
bratonien_tools_cache_warmup_log('download_failed', array('stage'=>$stage, 'source'=>$key, 'detail'=>$detail));
}
}
$cancel_requested = bratonien_tools_cache_warmup_cancel_pending($connection_id);
bratonien_tools_cache_warmup_status(
$connection_id,
$cancel_requested ? 'cancelling' : 'running',
$cancel_requested
? 'Abbruch angefordert. Der bereits geladene aktuelle Batch wird vollständig beendet; danach ist Schluss.'
: 'Piwigo verarbeitet WebDAV-Quellen aus dem Worker-Index.',
array(
'stage'=>$stage,
'batch'=>$batch_number,
'batch_requested'=>count($keys),
'batch_downloaded'=>count($downloads),
'selected_total'=>count($selected),
'stage_completed'=>$completed,
'cancel_requested'=>$cancel_requested,
)
);
foreach ($downloads as $key=>$file)
{
$result = bratonien_tools_cache_warmup_process($pending[$key], $file, $credentials, $stage);
bratonien_tools_cache_warmup_log('source', array('stage'=>$stage, 'source'=>$key, 'ok'=>!empty($result['ok']), 'defer'=>!empty($result['defer']), 'message'=>(string)($result['message'] ?? '')));
if (!empty($result['fatal']))
{
foreach ($downloads as $cleanup) @unlink($cleanup);
@rmdir($dir);
bratonien_tools_cache_warmup_unlock($batch_sync_lock);
throw new RuntimeException('Sicherheitsabbruch bei '.$key.': '.(string)$result['message']);
}
if (empty($result['ok']))
{
// Temporäre Sperren oder parallel belegte Quellen sind kein Fehler.
// Der Index bleibt offen und der nächste Lauf versucht nur diese
// Quelle erneut.
if (!empty($result['defer'])) $deferred++;
else $failed++;
continue;
}
$item = $pending[$key];
$existing = isset($index['sources'][$key]) && is_array($index['sources'][$key]) ? $index['sources'][$key] : array();
$metadata = bratonien_tools_webdav_source_index_metadata($item['source'], $item['shadow_relative']);
$index['sources'][$key] = array_merge($existing, $metadata);
$index['sources'][$key][$stage === 1 ? 'stage1_signature' : 'stage2_signature'] = $item['signature'];
bratonien_tools_webdav_source_index_save($credentials['state_dir'], $connection_id, $index);
$completed++;
}
foreach ($downloads as $file) @unlink($file);
@rmdir($dir);
bratonien_tools_cache_warmup_unlock($batch_sync_lock);
if (bratonien_tools_cache_warmup_cancel_pending($connection_id))
{
return array('failed'=>$failed, 'deferred'=>$deferred, 'waiting'=>false, 'preempted'=>false, 'cancelled'=>true, 'completed'=>$completed);
}
if ($stage === 2 && bratonien_tools_cache_warmup_priority_pending($priority_file))
{
return array('failed'=>$failed, 'deferred'=>$deferred, 'waiting'=>false, 'preempted'=>true, 'cancelled'=>false, 'completed'=>$completed);
}
}
return array('failed'=>$failed, 'deferred'=>$deferred, 'waiting'=>false, 'preempted'=>false, 'cancelled'=>false, 'completed'=>$completed);
}
function bratonien_tools_cache_warmup_run($connection_id, $mode)
{
$settings = bratonien_tools_get_webdav_warmup_settings();
if (!in_array($mode, array('manual','rebuild'), true) && empty($settings['enabled'])) return 0;
$credentials = bratonien_tools_cache_warmup_credentials($connection_id);
if (!$credentials) throw new RuntimeException('WebDAV-Verbindung, Runtime-Pfade oder Zugangsdaten konnten nicht geladen werden.');
$state_dir = $credentials['state_dir'];
if (!is_dir($state_dir) && !@mkdir($state_dir, 0750, true) && !is_dir($state_dir)) throw new RuntimeException('Connector-State-Verzeichnis konnte nicht angelegt werden.');
$priority_file = bratonien_tools_cache_warmup_priority_file($state_dir);
$process_lock = @fopen($state_dir.'/webdav-cache-warmup.lock', 'c');
if (!$process_lock || !@flock($process_lock, LOCK_EX | LOCK_NB))
{
if (is_resource($process_lock)) fclose($process_lock);
bratonien_tools_cache_warmup_log('already_running', array('connection_id'=>$connection_id));
return 0;
}
try
{
if ($mode === 'sync' && is_file($priority_file)) @unlink($priority_file);
$index = bratonien_tools_webdav_source_index_load($state_dir, $connection_id);
$index_created = false;
if ($index === null)
{
$index = bratonien_tools_webdav_source_index_empty($connection_id);
$index_created = true;
}
if ($mode === 'periodic')
{
$last = (int)($index['last_periodic_at'] ?? 0);
$interval = max(1, (int)$settings['periodic_hours']) * 3600;
if ($last > 0 && time() - $last < $interval) return 0;
}
$scan = bratonien_tools_cache_warmup_scan($connection_id, $credentials);
$removed = bratonien_tools_webdav_source_index_prune($index, array_keys($scan['sources']));
$selected = bratonien_tools_cache_warmup_select($scan, $index, $mode);
bratonien_tools_cache_warmup_status($connection_id, 'scan', 'Worker-Index wurde ausschließlich mit dem aktuellen Shadow-Tree abgeglichen.', array(
'mode'=>$mode,
'shadow_sources'=>count($scan['sources']),
'selected'=>count($selected),
'removed_from_index'=>$removed,
'index_created'=>$index_created,
));
if (!$selected)
{
if ($mode === 'periodic' || $mode === 'manual') $index['last_periodic_at'] = time();
bratonien_tools_webdav_source_index_save($state_dir, $connection_id, $index);
@unlink(bratonien_tools_cache_warmup_cancel_file($connection_id));
bratonien_tools_cache_warmup_status($connection_id, 'complete', 'Keine neuen oder geänderten Shadow-Quellen gefunden.', array('mode'=>$mode, 'shadow_sources'=>count($scan['sources'])));
return 0;
}
if ($mode === 'rebuild')
{
foreach ($selected as $key=>$item)
{
if (!isset($index['sources'][$key]) || !is_array($index['sources'][$key])) $index['sources'][$key] = array();
unset($index['sources'][$key]['stage1_signature'], $index['sources'][$key]['stage2_signature']);
}
}
$stage1 = bratonien_tools_cache_warmup_run_stage($connection_id, 1, $selected, $index, $credentials, $settings['batch_size'], $priority_file);
if (!empty($stage1['cancelled']))
{
bratonien_tools_webdav_source_index_save($state_dir, $connection_id, $index);
@unlink(bratonien_tools_cache_warmup_cancel_file($connection_id));
bratonien_tools_cache_warmup_status($connection_id, 'cancelled', 'Cache-Aufbau nach dem vollständig abgeschlossenen aktuellen Batch beendet.', array(
'mode'=>$mode,
'shadow_sources'=>count($scan['sources']),
'selected'=>count($selected),
'stage1_completed'=>bratonien_tools_cache_warmup_stage_completed_count($selected, $index, 1),
'stage2_completed'=>bratonien_tools_cache_warmup_stage_completed_count($selected, $index, 2),
'stage1_failed'=>(int)$stage1['failed'],
'stage1_deferred'=>(int)$stage1['deferred'],
'stage2_failed'=>0,
'stage2_deferred'=>0,
));
return 0;
}
if (!empty($stage1['waiting']))
{
bratonien_tools_webdav_source_index_save($state_dir, $connection_id, $index);
return 0;
}
$stage2_candidates = array();
foreach ($selected as $key=>$item)
{
$entry = isset($index['sources'][$key]) && is_array($index['sources'][$key]) ? $index['sources'][$key] : array();
if (isset($entry['stage1_signature']) && hash_equals((string)$entry['stage1_signature'], $item['signature'])) $stage2_candidates[$key] = $item;
}
$stage2 = bratonien_tools_cache_warmup_run_stage($connection_id, 2, $stage2_candidates, $index, $credentials, $settings['batch_size'], $priority_file);
if (!empty($stage2['cancelled']))
{
bratonien_tools_webdav_source_index_save($state_dir, $connection_id, $index);
@unlink(bratonien_tools_cache_warmup_cancel_file($connection_id));
bratonien_tools_cache_warmup_status($connection_id, 'cancelled', 'Cache-Aufbau nach dem vollständig abgeschlossenen aktuellen Batch beendet.', array(
'mode'=>$mode,
'shadow_sources'=>count($scan['sources']),
'selected'=>count($selected),
'stage1_completed'=>bratonien_tools_cache_warmup_stage_completed_count($selected, $index, 1),
'stage2_completed'=>bratonien_tools_cache_warmup_stage_completed_count($selected, $index, 2),
'stage1_failed'=>(int)$stage1['failed'],
'stage1_deferred'=>(int)$stage1['deferred'],
'stage2_failed'=>(int)$stage2['failed'],
'stage2_deferred'=>(int)$stage2['deferred'],
));
return 0;
}
if (!empty($stage2['waiting']))
{
bratonien_tools_webdav_source_index_save($state_dir, $connection_id, $index);
return 0;
}
if (!empty($stage2['preempted']))
{
bratonien_tools_webdav_source_index_save($state_dir, $connection_id, $index);
bratonien_tools_cache_warmup_status($connection_id, 'preempted', 'Stufe 2 wurde nach einem vollständigen Batch für neue Connector-Inhalte freigegeben.', array(
'mode'=>$mode,
'selected'=>count($selected),
'stage1_completed'=>bratonien_tools_cache_warmup_stage_completed_count($selected, $index, 1),
'stage2_completed'=>bratonien_tools_cache_warmup_stage_completed_count($selected, $index, 2),
'stage1_failed'=>(int)$stage1['failed'],
'stage1_deferred'=>(int)$stage1['deferred'],
'stage2_failed'=>(int)$stage2['failed'],
'stage2_deferred'=>(int)$stage2['deferred'],
));
return 0;
}
if ($mode === 'periodic' || $mode === 'manual') $index['last_periodic_at'] = time();
bratonien_tools_webdav_source_index_save($state_dir, $connection_id, $index);
@unlink(bratonien_tools_cache_warmup_cancel_file($connection_id));
$failed = (int)$stage1['failed'] + (int)$stage2['failed'];
$deferred = (int)$stage1['deferred'] + (int)$stage2['deferred'];
if ($failed > 0 || $deferred > 0)
{
bratonien_tools_cache_warmup_status($connection_id, 'partial', 'Worker-Lauf beendet; einzelne Quellen bleiben offen und werden beim nächsten Lauf erneut versucht. Der übrige Bestand wurde weiterverarbeitet.', array(
'mode'=>$mode,
'shadow_sources'=>count($scan['sources']),
'selected'=>count($selected),
'stage1_completed'=>bratonien_tools_cache_warmup_stage_completed_count($selected, $index, 1),
'stage2_completed'=>bratonien_tools_cache_warmup_stage_completed_count($selected, $index, 2),
'stage1_failed'=>(int)$stage1['failed'],
'stage1_deferred'=>(int)$stage1['deferred'],
'stage2_failed'=>(int)$stage2['failed'],
'stage2_deferred'=>(int)$stage2['deferred'],
));
return 0;
}
bratonien_tools_cache_warmup_status($connection_id, 'complete', $mode === 'rebuild' ? 'Piwigo hat den vollständigen Shadow-Bestand für den Cache-Rebuild verarbeitet.' : 'Worker-Lauf vollständig beendet.', array(
'mode'=>$mode,
'shadow_sources'=>count($scan['sources']),
'selected'=>count($selected),
'stage1_completed'=>bratonien_tools_cache_warmup_stage_completed_count($selected, $index, 1),
'stage2_completed'=>bratonien_tools_cache_warmup_stage_completed_count($selected, $index, 2),
'stage1_failed'=>0,
'stage1_deferred'=>0,
'stage2_failed'=>0,
'stage2_deferred'=>0,
));
return 0;
}
finally
{
@flock($process_lock, LOCK_UN);
fclose($process_lock);
}
}
$connection_id = 0;
$mode = 'periodic';
foreach ($argv as $arg)
{
if (preg_match('/^--connection-id=(\d+)$/', $arg, $m)) $connection_id = (int)$m[1];
elseif (preg_match('/^--mode=(sync|periodic|manual|rebuild)$/', $arg, $m)) $mode = $m[1];
}
if ($connection_id < 1)
{
fwrite(STDERR, "--connection-id fehlt oder ist ungültig.\n");
exit(1);
}
try
{
exit(bratonien_tools_cache_warmup_run($connection_id, $mode));
}
catch (Throwable $e)
{
try { bratonien_tools_cache_warmup_status($connection_id, 'fatal', $e->getMessage()); } catch (Throwable $ignored) {}
fwrite(STDERR, '[BRAT-WORKER] fatal '.$e->getMessage()."\n");
exit(1);
}

View File

@@ -0,0 +1,180 @@
#!/usr/bin/env php
<?php
if (PHP_SAPI !== 'cli')
{
fwrite(STDERR, "CLI only\n");
exit(1);
}
$connection_id = 0;
foreach ($argv as $arg)
{
if (preg_match('/^--connection-id=(\d+)$/', $arg, $m)) $connection_id = (int)$m[1];
}
if ($connection_id < 1)
{
fwrite(STDERR, "--connection-id fehlt oder ist ungueltig.\n");
exit(2);
}
$piwigo_root = realpath(dirname(__DIR__, 4));
if ($piwigo_root === false)
{
fwrite(STDERR, "Piwigo-Root wurde nicht gefunden.\n");
exit(3);
}
define('PHPWG_ROOT_PATH', rtrim($piwigo_root, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR);
$_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/webdav-scan-diagnostic.php';
$_SERVER['PHP_SELF'] = $_SERVER['SCRIPT_NAME'];
$_SERVER['QUERY_STRING'] = '';
$_SERVER['HTTP_USER_AGENT'] = 'Bratonien-WebDAV-Scan-Diagnostic/0.9.7.1.21';
$_SERVER['HTTPS'] = 'off';
try
{
require_once(PHPWG_ROOT_PATH.'include/common.inc.php');
if (!defined('BRATONIEN_TOOLS_PATH')) throw new RuntimeException('Bratonien Tools ist nicht aktiv.');
require_once(BRATONIEN_TOOLS_PATH.'include/nc_connector.inc.php');
$connection = bratonien_tools_nc_connector_connection($connection_id, true);
if (!$connection || empty($connection['enabled'])) throw new RuntimeException('WebDAV-Verbindung wurde nicht gefunden oder ist deaktiviert.');
if (!bratonien_tools_nc_connector_is_webdav($connection)) throw new RuntimeException('Verbindung ist keine WebDAV-Placeholder-Verbindung.');
$config = isset($connection['config']) && is_array($connection['config']) ? $connection['config'] : array();
$state_dir = rtrim((string)($config['state_dir'] ?? ''), '/');
$gallery_root = rtrim((string)($config['parallel_gallery_root'] ?? ''), '/');
if ($state_dir === '') throw new RuntimeException('Connector-State-Verzeichnis fehlt.');
if ($gallery_root === '') throw new RuntimeException('Shadow-Tree-Pfad fehlt in der Connector-Konfiguration.');
$lock_file = $state_dir.'/webdav-cache-warmup.lock';
$worker_lock_state = 'open_failed';
$worker_lock_detail = '';
$lock_handle = @fopen($lock_file, 'c');
if (is_resource($lock_handle))
{
if (@flock($lock_handle, LOCK_EX | LOCK_NB))
{
$worker_lock_state = 'free';
@flock($lock_handle, LOCK_UN);
}
else
{
$worker_lock_state = 'busy';
$worker_lock_detail = 'Ein anderer Prozess haelt den WebDAV-Worker-Lock.';
}
fclose($lock_handle);
}
else
{
$worker_lock_detail = 'Worker-Lock-Datei konnte nicht geoeffnet werden.';
}
$mapping_file = $state_dir.'/webdav-map.json';
if (!is_file($mapping_file) || !is_readable($mapping_file)) throw new RuntimeException('WebDAV-Mapping fehlt oder ist nicht lesbar: '.$mapping_file);
$mapping = json_decode((string)file_get_contents($mapping_file), true);
if (!is_array($mapping) || !isset($mapping['files']) || !is_array($mapping['files'])) throw new RuntimeException('WebDAV-Mapping ist ungueltig.');
if (!is_dir($gallery_root)) throw new RuntimeException('Shadow-Tree fehlt: '.$gallery_root);
$normalize = static function ($path) {
return rtrim(str_replace('\\', '/', (string)$path), '/');
};
$mapped_files = array();
foreach ($mapping['files'] as $path=>$meta)
{
if (!is_array($meta) || (string)($meta['kind'] ?? '') !== 'file') continue;
$mapped_files[$normalize($path)] = $meta;
}
$shadow_links = 0;
$matched = 0;
$broken = 0;
$unmapped = 0;
$duplicates = 0;
$seen = array();
$examples = array();
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($gallery_root, FilesystemIterator::SKIP_DOTS),
RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($iterator as $item)
{
$shadow = $item->getPathname();
if (!is_link($shadow)) continue;
$shadow_links++;
$resolved = realpath($shadow);
if ($resolved === false || !is_file($resolved))
{
$broken++;
if (count($examples) < 8) $examples[] = array('state'=>'broken','shadow'=>$shadow);
continue;
}
$resolved = $normalize($resolved);
if (!isset($mapped_files[$resolved]))
{
$unmapped++;
if (count($examples) < 8) $examples[] = array('state'=>'unmapped','shadow'=>$shadow,'target'=>$resolved);
continue;
}
if (isset($seen[$resolved]))
{
$duplicates++;
if (count($examples) < 8) $examples[] = array('state'=>'duplicate','shadow'=>$shadow,'target'=>$resolved);
continue;
}
$seen[$resolved] = true;
$matched++;
if (count($examples) < 8)
{
$meta = $mapped_files[$resolved];
$examples[] = array(
'state'=>'matched',
'shadow'=>$shadow,
'target'=>$resolved,
'fileid'=>(int)($meta['fileid'] ?? 0),
'webdav_path'=>(string)($meta['webdav_path'] ?? ''),
'etag'=>(string)($meta['etag'] ?? ''),
);
}
}
$scan_ok = ($shadow_links > 0 && $matched === $shadow_links && $broken === 0 && $unmapped === 0 && $duplicates === 0);
$payload = array(
'ok'=>$scan_ok && $worker_lock_state !== 'open_failed',
'scan_ok'=>$scan_ok,
'connection_id'=>$connection_id,
'state_dir'=>$state_dir,
'gallery_root'=>$gallery_root,
'mapping_file'=>$mapping_file,
'worker_lock_file'=>$lock_file,
'worker_lock_state'=>$worker_lock_state,
'worker_lock_detail'=>$worker_lock_detail,
'mapping_files'=>count($mapped_files),
'shadow_links'=>$shadow_links,
'matched'=>$matched,
'broken'=>$broken,
'unmapped'=>$unmapped,
'duplicates'=>$duplicates,
'examples'=>$examples,
);
echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT)."\n";
exit($payload['ok'] ? 0 : 4);
}
catch (Throwable $e)
{
echo json_encode(array(
'ok'=>false,
'connection_id'=>$connection_id,
'fatal'=>$e->getMessage(),
), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT)."\n";
exit(1);
}

View File

@@ -0,0 +1,112 @@
<?php
if (PHP_SAPI !== 'cli')
{
http_response_code(404);
exit;
}
$piwigo_root = realpath(dirname(__DIR__, 4));
if ($piwigo_root === false)
{
fwrite(STDERR, "Piwigo-Root wurde nicht gefunden.\n");
exit(1);
}
define('PHPWG_ROOT_PATH', rtrim($piwigo_root, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR);
$_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/webdav-warmup-audit.php';
$_SERVER['PHP_SELF'] = $_SERVER['SCRIPT_NAME'];
$_SERVER['QUERY_STRING'] = '';
$_SERVER['HTTP_USER_AGENT'] = 'Bratonien-WebDAV-Warmup-Audit/0.9.7.1.8';
$_SERVER['HTTPS'] = 'off';
require_once(PHPWG_ROOT_PATH.'include/common.inc.php');
if (!defined('BRATONIEN_TOOLS_PATH'))
{
fwrite(STDERR, "Bratonien Tools ist nicht aktiv.\n");
exit(1);
}
require_once(BRATONIEN_TOOLS_PATH.'include/webdav_materialize_runtime.inc.php');
$total = 0;
$connector = 0;
$errors = array();
$warnings = array();
$resolved_to_ids = array();
$result = pwg_query('SELECT id, path FROM '.IMAGES_TABLE.' ORDER BY id');
while ($row = pwg_db_fetch_assoc($result))
{
$total++;
$image_id = (int)$row['id'];
$info = bratonien_tools_webdav_materialize_source_info($image_id);
if (!$info) continue;
$connector++;
$logical = (string)$row['path'];
if ($logical === '')
{
$errors[] = 'Bild #'.$image_id.': Piwigo-Pfad ist leer.';
continue;
}
if (strpos($logical, '/') !== 0)
{
$logical = PHPWG_ROOT_PATH.ltrim(preg_replace('#^\./#', '', $logical), '/');
}
$resolved = realpath($logical);
if ($resolved === false || !is_file($resolved))
{
$errors[] = 'Bild #'.$image_id.': Piwigo-Pfad kann nicht auf eine Datei aufgelöst werden: '.$logical;
continue;
}
$normalized = str_replace('\\', '/', $resolved);
$expected = '/nc-webdav-source/connection-'.(int)$info['connection_id'].'/root-'.(int)$info['root_fileid'].'/';
if (strpos($normalized, $expected) === false)
{
$errors[] = 'Bild #'.$image_id.': realpath liegt nicht in der erwarteten Connector-Wurzel: '.$normalized;
}
$webdav_path = trim((string)($info['webdav_path'] ?? ''), '/');
if ($webdav_path === '')
{
$errors[] = 'Bild #'.$image_id.': WebDAV-Pfad fehlt.';
}
if ((int)($info['connection_id'] ?? 0) < 1 || (int)($info['root_fileid'] ?? 0) < 1)
{
$errors[] = 'Bild #'.$image_id.': Verbindung oder Root-fileid ist ungültig.';
}
if ((int)($info['fileid'] ?? 0) < 1)
{
$warnings[] = 'Bild #'.$image_id.': Nextcloud-fileid fehlt; Original-Fallback bleibt möglich.';
}
if (!isset($resolved_to_ids[$normalized])) $resolved_to_ids[$normalized] = array();
$resolved_to_ids[$normalized][] = $image_id;
}
foreach ($resolved_to_ids as $path => $ids)
{
if (count($ids) > 1)
{
$warnings[] = 'Mehrere Piwigo-Bild-IDs zeigen auf dieselbe physische Connector-Quelle: '.implode(',', $ids).' -> '.$path;
}
}
printf("WebDAV-Warmup-Pfadaudit\n");
printf("Piwigo-Bilder gesamt: %d\n", $total);
printf("Connector-Bilder: %d\n", $connector);
printf("Fehler: %d\n", count($errors));
printf("Warnungen: %d\n", count($warnings));
foreach ($errors as $error) fwrite(STDERR, "ERROR: ".$error."\n");
foreach ($warnings as $warning) fwrite(STDOUT, "WARN: ".$warning."\n");
exit($errors ? 2 : 0);

View File

@@ -1,17 +0,0 @@
CREATE OR REPLACE VIEW piwigo_showcase_sources AS
SELECT
s.id AS share_id,
s.file_target AS display_name,
st.id AS storage_id,
f.path AS source_path,
s.accepted,
s.permissions,
s.item_type AS item_type
FROM oc_share AS s
JOIN oc_filecache AS f ON f.fileid = s.file_source
JOIN oc_storages AS st ON st.numeric_id = f.storage
WHERE lower(s.share_with) = 'showcase'
AND s.item_type IN ('folder', 'file')
AND s.accepted = 1;
GRANT SELECT ON piwigo_showcase_sources TO piwigo_reader;

View File

@@ -0,0 +1,324 @@
<?php
if (PHP_SAPI !== 'cli')
{
http_response_code(404);
exit;
}
$piwigo_root = realpath(dirname(__DIR__, 3));
if ($piwigo_root === false)
{
fwrite(STDERR, "Piwigo-Root wurde nicht gefunden.\n");
exit(1);
}
define('PHPWG_ROOT_PATH', rtrim($piwigo_root, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR);
$_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/piwigo-presentation-refresh.php';
$_SERVER['PHP_SELF'] = $_SERVER['SCRIPT_NAME'];
$_SERVER['QUERY_STRING'] = '';
$_SERVER['HTTP_USER_AGENT'] = 'Bratonien-Presentation-Refresh/0.9.7.1.41';
$_SERVER['HTTPS'] = 'off';
require_once(PHPWG_ROOT_PATH.'include/common.inc.php');
require_once(PHPWG_ROOT_PATH.'include/derivative.inc.php');
if (!defined('BRATONIEN_TOOLS_PATH'))
{
fwrite(STDERR, "Bratonien Tools ist nicht aktiv.\n");
exit(1);
}
require_once(BRATONIEN_TOOLS_PATH.'include/presentation_refresh.inc.php');
require_once(BRATONIEN_TOOLS_PATH.'include/watermark_runtime.inc.php');
require_once(BRATONIEN_TOOLS_PATH.'include/webdav_materialize_runtime.inc.php');
function bratonien_tools_presentation_worker_log($event, array $data=array())
{
$parts = array('[BRAT-PRESENTATION]', $event);
foreach ($data as $key=>$value)
{
if (is_array($value) || is_object($value)) $value = json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$parts[] = $key.'='.str_replace(array("\r", "\n"), array('\\r', '\\n'), (string)$value);
}
fwrite(STDOUT, implode(' ', $parts)."\n");
}
function bratonien_tools_presentation_worker_categories(array $requested, $all)
{
$requested = array_fill_keys(array_map('intval', $requested), true);
$categories = array();
$result = pwg_query('SELECT id, uppercats FROM '.CATEGORIES_TABLE.' ORDER BY id');
while ($row = pwg_db_fetch_assoc($result))
{
$id = (int)$row['id'];
if ($id < 1) continue;
if ($all)
{
$categories[$id] = $id;
continue;
}
$uppercats = array_filter(array_map('intval', explode(',', (string)$row['uppercats'])));
foreach ($uppercats as $ancestor)
{
if (isset($requested[$ancestor]))
{
$categories[$id] = $id;
break;
}
}
}
ksort($categories, SORT_NUMERIC);
return array_values($categories);
}
function bratonien_tools_presentation_worker_variants(SrcImage $src)
{
$variants = array();
foreach (ImageStdParams::get_defined_type_map() as $type=>$params)
{
$variants['standard:'.$type] = new DerivativeImage($params, $src);
}
foreach (ImageStdParams::$custom as $key=>$last_used)
{
$params = bratonien_tools_webdav_materialize_custom_params($key);
if ($params) $variants['custom:'.$key] = new DerivativeImage($params, $src);
}
return $variants;
}
function bratonien_tools_presentation_worker_call_watermark($url, &$detail=null)
{
$detail = '';
$url = html_entity_decode((string)$url, ENT_QUOTES | ENT_HTML5, 'UTF-8');
$path = (string)parse_url($url, PHP_URL_PATH);
$query = (string)parse_url($url, PHP_URL_QUERY);
$endpoint = '/plugins/'.trim(BRATONIEN_TOOLS_ID, '/').'/watermark.php';
if ($path === '' || substr($path, -strlen($endpoint)) !== $endpoint)
{
if (strpos($path, '/bratonien-watermark/') !== false)
{
$detail = 'Bereits vorhanden.';
return true;
}
$detail = 'Kein Bratonien-Wasserzeichenaufruf erforderlich.';
return true;
}
if ($query === '')
{
$detail = 'Wasserzeichen-URL enthält keine Parameter.';
return false;
}
if (!function_exists('exec'))
{
$detail = 'PHP exec() ist deaktiviert.';
return false;
}
$runner = BRATONIEN_TOOLS_PATH.'runtime/lib/bratonien-watermark-call.php';
if (!is_file($runner))
{
$detail = 'Lokaler Wasserzeichen-Aufrufer fehlt.';
return false;
}
$command = escapeshellarg(PHP_BINARY).' '.escapeshellarg($runner)
.' --query='.escapeshellarg($query).' > /dev/null 2>&1';
$output = array();
$exit = 1;
@exec($command, $output, $exit);
if ($exit !== 0)
{
$detail = 'Wasserzeichen-Aufrufer Exit '.$exit.'.';
return false;
}
$detail = 'Wasserzeichen-Vorschau bereit.';
return true;
}
function bratonien_tools_presentation_worker_process(array $category_ids)
{
global $page;
if (!$category_ids) return array('images'=>0, 'profiles'=>0, 'variants'=>0, 'generated'=>0, 'missing_base'=>0, 'errors'=>0);
$category_lookup = array_fill_keys($category_ids, true);
$ids_sql = implode(',', array_map('intval', $category_ids));
$image_categories = array();
$result = pwg_query('SELECT image_id, category_id FROM '.IMAGE_CATEGORY_TABLE.' WHERE category_id IN ('.$ids_sql.') ORDER BY image_id, category_id');
while ($row = pwg_db_fetch_assoc($result))
{
$image_id = (int)$row['image_id'];
$category_id = (int)$row['category_id'];
if ($image_id > 0 && isset($category_lookup[$category_id])) $image_categories[$image_id][] = $category_id;
}
if (!$image_categories) return array('images'=>0, 'profiles'=>0, 'variants'=>0, 'generated'=>0, 'missing_base'=>0, 'errors'=>0);
$stats = array('images'=>0, 'profiles'=>0, 'variants'=>0, 'generated'=>0, 'missing_base'=>0, 'errors'=>0);
$image_ids = array_keys($image_categories);
foreach (array_chunk($image_ids, 500) as $chunk)
{
$rows = pwg_query('SELECT * FROM '.IMAGES_TABLE.' WHERE id IN ('.implode(',', array_map('intval', $chunk)).') ORDER BY id');
while ($row = pwg_db_fetch_assoc($rows))
{
$image_id = (int)$row['id'];
$stats['images']++;
$profile_contexts = array();
foreach ($image_categories[$image_id] ?? array() as $category_id)
{
$rule = bratonien_tools_runtime_effective_rule($category_id);
if ((string)($rule['mode'] ?? '') !== 'profile' || empty($rule['profile_id'])) continue;
$profile_id = (int)$rule['profile_id'];
if ($profile_id < 1 || isset($profile_contexts[$profile_id])) continue;
$profile = bratonien_tools_runtime_get_profile($profile_id);
if (!$profile || empty($profile['active']) || !bratonien_tools_profile_watermark_path($profile)) continue;
$profile_contexts[$profile_id] = $category_id;
}
if (!$profile_contexts) continue;
try
{
$src = new SrcImage($row);
$variants = bratonien_tools_presentation_worker_variants($src);
}
catch (Throwable $e)
{
$stats['errors']++;
bratonien_tools_presentation_worker_log('image_error', array('image_id'=>$image_id, 'message'=>$e->getMessage()));
continue;
}
foreach ($profile_contexts as $profile_id=>$category_id)
{
$stats['profiles']++;
$page['category'] = array('id'=>(int)$category_id);
foreach ($variants as $variant_name=>$derivative)
{
try
{
if ($derivative->same_as_source()) continue;
$stats['variants']++;
$target = $derivative->get_path();
if ($target === '' || !is_file($target) || !is_readable($target))
{
$stats['missing_base']++;
continue;
}
$detail = '';
if (!bratonien_tools_presentation_worker_call_watermark($derivative->get_url(), $detail))
{
$stats['errors']++;
bratonien_tools_presentation_worker_log('variant_error', array(
'image_id'=>$image_id,
'category_id'=>$category_id,
'profile_id'=>$profile_id,
'variant'=>$variant_name,
'message'=>$detail,
));
continue;
}
$stats['generated']++;
}
catch (Throwable $e)
{
$stats['errors']++;
bratonien_tools_presentation_worker_log('variant_error', array(
'image_id'=>$image_id,
'category_id'=>$category_id,
'profile_id'=>$profile_id,
'variant'=>$variant_name,
'message'=>$e->getMessage(),
));
}
}
}
}
}
unset($page['category']);
return $stats;
}
try
{
$queue_dir = bratonien_tools_presentation_refresh_queue_dir();
if (!is_dir($queue_dir)) exit(0);
$lock_path = $queue_dir.'/.worker.lock';
$lock = @fopen($lock_path, 'c');
if (!$lock) throw new RuntimeException('Presentation-Worker-Lock konnte nicht geöffnet werden.');
if (!@flock($lock, LOCK_EX)) throw new RuntimeException('Presentation-Worker-Lock konnte nicht gesetzt werden.');
try
{
while (true)
{
$request_files = glob($queue_dir.'/*.json') ?: array();
sort($request_files, SORT_STRING);
if (!$request_files) break;
$all = false;
$requested = array();
$valid_files = array();
$reasons = array();
foreach ($request_files as $file)
{
$data = json_decode((string)@file_get_contents($file), true);
if (!is_array($data))
{
bratonien_tools_presentation_worker_log('invalid_request', array('file'=>basename($file)));
@unlink($file);
continue;
}
$valid_files[] = $file;
if (!empty($data['all'])) $all = true;
foreach ((array)($data['categories'] ?? array()) as $category_id)
{
$category_id = (int)$category_id;
if ($category_id > 0) $requested[$category_id] = $category_id;
}
if (!empty($data['reason'])) $reasons[] = (string)$data['reason'];
}
if (!$valid_files) continue;
$categories = bratonien_tools_presentation_worker_categories(array_values($requested), $all);
$stats = bratonien_tools_presentation_worker_process($categories);
bratonien_tools_presentation_worker_log('complete', array(
'all'=>$all,
'requested'=>count($requested),
'categories'=>count($categories),
'reasons'=>array_values(array_unique($reasons)),
'images'=>$stats['images'],
'profiles'=>$stats['profiles'],
'variants'=>$stats['variants'],
'prepared'=>$stats['generated'],
'missing_base'=>$stats['missing_base'],
'errors'=>$stats['errors'],
));
foreach ($valid_files as $file) @unlink($file);
}
}
finally
{
@flock($lock, LOCK_UN);
fclose($lock);
}
exit(0);
}
catch (Throwable $e)
{
fwrite(STDERR, '[BRAT-PRESENTATION] fatal '.$e->getMessage()."\n");
exit(1);
}

View File

@@ -0,0 +1,258 @@
#!/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);
if (!is_string($iv) || !is_string($tag) || !is_string($cipher)) fail_webdav_reconcile('Connector-Zugangsdaten sind unvollstaendig.');
$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));
}
function webdav_set_runtime_dir_permissions($dir)
{
if (!is_dir($dir)) return false;
if (!@chgrp($dir, 'www-data')) return false;
return @chmod($dir, 0750);
}
$pluginRoot = dirname(__DIR__);
$piwigoRoot = dirname($pluginRoot, 2);
$dbConfig = $piwigoRoot.'/local/config/database.inc.php';
$configDir = '/etc/bratonien-tools/nc-connector';
$stateBase = '/var/lib/bratonien-tools';
$stateRoot = $stateBase.'/nc-connector';
$publicSourceRoot = rtrim($piwigoRoot, '/').'/_data/bratonien-tools/nc-webdav-source';
$publicGalleryRoot = rtrim($piwigoRoot, '/').'/_data/bratonien-tools/nc-webdav-gallery';
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}` WHERE adapter='remote' ORDER BY id DESC");
if (!$rows) fail_webdav_reconcile('WebDAV-Verbindungen konnten nicht gelesen werden: '.$db->error);
foreach (array($configDir, $stateRoot, $publicSourceRoot, $publicGalleryRoot) as $dir)
{
if (!is_dir($dir) && !mkdir($dir, $dir === $configDir ? 0700 : 0750, true)) fail_webdav_reconcile('Runtime-Verzeichnis konnte nicht angelegt werden: '.$dir);
}
@chmod($configDir, 0700);
if (!webdav_set_runtime_dir_permissions($stateBase)) fail_webdav_reconcile('Runtime-State-Basis konnte nicht fuer den Webserver freigegeben werden.');
if (!webdav_set_runtime_dir_permissions($stateRoot)) fail_webdav_reconcile('Runtime-State-Verzeichnis konnte nicht fuer den Webserver freigegeben werden.');
@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)($config['source_mode'] ?? '') !== 'webdav-placeholder') 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($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.');
if (!webdav_set_runtime_dir_permissions($stateDir)) fail_webdav_reconcile('State-Verzeichnis konnte nicht fuer den Webserver freigegeben werden.');
$galleryRoot = rtrim((string)($config['parallel_gallery_root'] ?? ''), '/');
$expectedGalleryRoot = $publicGalleryRoot.'/connection-'.$id;
if ($galleryRoot === '' || strpos($galleryRoot, $publicGalleryRoot.'/') !== 0) $galleryRoot = $expectedGalleryRoot;
if (!is_dir($galleryRoot) && !mkdir($galleryRoot, 0755, true)) fail_webdav_reconcile('WebDAV-Galeriebereich konnte nicht angelegt werden.');
@chmod($galleryRoot, 0755);
$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 ($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);
unset($config['parallel_test']);
$config['state_dir'] = $stateDir;
$config['status_file'] = $statusFile;
$config['parallel_gallery_root'] = $galleryRoot;
$config['source_fingerprint'] = $fingerprint;
$config['runtime'] = array(
'mode'=>'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)) fail_webdav_reconcile('WebDAV-Runtime-Konfiguration konnte nicht serialisiert werden.');
$escaped = $db->real_escape_string($json);
if (!$db->query("UPDATE `{$table}` SET enabled=1, config_json='{$escaped}' WHERE id={$id} AND adapter='remote' LIMIT 1"))
{
fail_webdav_reconcile('WebDAV-Runtime-Status konnte nicht gespeichert werden: '.$db->error);
}
}
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);
}

View 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);
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/repair-webdav-orphans.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');
try
{
$relativePrefix = './_data/bratonien-tools/nc-webdav-gallery/connection-';
$absolutePrefix = rtrim(PHPWG_ROOT_PATH, '/').'/_data/bratonien-tools/nc-webdav-gallery/connection-';
$relativeLength = strlen($relativePrefix);
$absoluteLength = strlen($absolutePrefix);
$query = "SELECT id,path FROM ".IMAGES_TABLE.
" WHERE LEFT(path,".$relativeLength.")='".pwg_db_real_escape_string($relativePrefix)."'".
" OR LEFT(path,".$absoluteLength.")='".pwg_db_real_escape_string($absolutePrefix)."'";
$result = pwg_query($query);
$checked = 0;
$staleIds = array();
while ($row = pwg_db_fetch_assoc($result))
{
$id = (int)$row['id'];
$storedPath = (string)$row['path'];
if ($id < 1 || $storedPath === '') continue;
if (strpos($storedPath, $relativePrefix) === 0)
{
$filesystemPath = rtrim(PHPWG_ROOT_PATH, '/').'/'.ltrim(substr($storedPath, 2), '/');
}
elseif (strpos($storedPath, $absolutePrefix) === 0)
{
$filesystemPath = $storedPath;
}
else
{
continue;
}
$checked++;
if (!is_file($filesystemPath))
{
$staleIds[] = $id;
}
}
$staleIds = array_values(array_unique(array_map('intval', $staleIds)));
if ($staleIds)
{
// Die Shadow-Quelle existiert nicht mehr. Der Bilddatensatz ist damit
// unabhängig von eventuellen virtuellen Album-Verknüpfungen ungültig.
// delete_elements(..., false) entfernt Piwigos Datensatz und Derivate,
// fasst aber keine bereits verschwundene Quelldatei an.
delete_elements($staleIds, false);
invalidate_user_cache(true);
}
echo 'NC WebDAV laufende Bereinigung: geprueft='.$checked.' entfernte_verwaiste_bilder='.count($staleIds)."\n";
exit(0);
}
catch (Throwable $e)
{
fwrite(STDERR, 'NC WebDAV laufende Bereinigung: '.$e->getMessage()."\n");
exit(1);
}

View File

@@ -4,19 +4,57 @@ set -Eeuo pipefail
CONFIG_DIR="/etc/bratonien-tools/nc-connector"
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
shopt -s nullglob
configs=("$CONFIG_DIR"/connection-*.conf)
if [[ ${#configs[@]} -eq 0 ]]; then
echo "Keine aktiven NC-Connector-Verbindungen konfiguriert."
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/repair-webdav-orphans.php"; then
echo "NC Connector: verwaiste WebDAV-Bilddatensaetze konnten nicht repariert 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
webdav_configs=("$CONFIG_DIR"/webdav-connection-*.conf)
if [[ ${#webdav_configs[@]} -eq 0 ]]; then
echo "Keine WebDAV-Connector-Verbindungen konfiguriert."
exit 0
fi
result=0
for config in "${configs[@]}"; do
echo "NC Connector: $(basename "$config")"
if ! env PIWIGO_CONFIG="$config" bash "$SCRIPT_DIR/sync.sh"; then
for config in "${webdav_configs[@]}"; do
name="$(basename "$config")"
echo "NC Connector WebDAV: $name"
state_dir="$(PIWIGO_CONFIG="$config" bash -c 'source "$PIWIGO_CONFIG"; printf "%s" "${STATE_DIR:-}"')"
change_file="${state_dir%/}/webdav-sync-content-changed"
if env PIWIGO_CONFIG="$config" bash "$SCRIPT_DIR/sync-webdav.sh"; then
# Nur ein tatsaechlich geaenderter Connector-Bestand darf einen
# laufenden Cache-Rebuild priorisiert unterbrechen. Ein erfolgreicher
# Sync ohne Aenderung ist kein neuer Inhalt.
if [[ -f "$change_file" && -f "$SCRIPT_DIR/webdav-warmup-dispatch.php" && "$name" =~ ^webdav-connection-([0-9]+)\.conf$ ]]; then
connection_id="${BASH_REMATCH[1]}"
php "$SCRIPT_DIR/webdav-warmup-dispatch.php" --mode=sync --connection-id="$connection_id" || result=1
rm -f -- "$change_file"
else
echo "NC Connector WebDAV: keine Inhaltsaenderung, kein priorisierter Warmup erforderlich."
fi
else
result=1
fi
done
# Einzelne neue/geänderte Bilder in bereits bekannten Alben werden weiterhin
# über die periodische Eingangsprüfung behandelt. Der Dispatcher startet die
# eigentliche Prüfung erst, wenn das konfigurierte Intervall fällig ist.
if [[ "$result" -eq 0 && -f "$SCRIPT_DIR/webdav-warmup-dispatch.php" ]]; then
php "$SCRIPT_DIR/webdav-warmup-dispatch.php" --mode=periodic || result=1
fi
exit "$result"

263
runtime/sync-webdav.sh Normal file
View File

@@ -0,0 +1,263 @@
#!/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"
WORKER_LOCK_FILE="$STATE_DIR/webdav-cache-warmup.lock"
CHANGE_FILE="$STATE_DIR/webdav-sync-content-changed"
PRIORITY_FILE="$STATE_DIR/webdav-cache-warmup-priority-sync"
mkdir -p -- "$STATE_DIR"
chgrp www-data -- "$STATE_DIR"
chmod 0750 -- "$STATE_DIR"
# Das Connector-State-Verzeichnis bleibt fuer www-data bewusst nicht
# beschreibbar. Die beiden gemeinsam verwendeten Lock-Dateien werden deshalb
# vom privilegierten Connector explizit angelegt und gruppenschreibbar gemacht.
touch -- "$LOCK_FILE" "$WORKER_LOCK_FILE"
chgrp www-data -- "$LOCK_FILE" "$WORKER_LOCK_FILE"
chmod 0660 -- "$LOCK_FILE" "$WORKER_LOCK_FILE"
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-Synchronisierung fehlgeschlagen" "Exit-Code: $code; Zeile: $line; Befehl: $command"
exit "$code"
}
trap 'failure $? "$BASH_COMMAND" "$LINENO"' ERR
write_status running "WebDAV-Synchronisierung läuft"
ROOT_ARGS=()
while IFS= read -r line; do
[[ -z "$line" || "$line" == \#* ]] && continue
[[ "$line" == *$'\t'* ]] || continue
path="${line%%$'\t'*}"
ROOT_ARGS+=(--root "$path")
done < "$WEBDAV_ROOTS_FILE"
[[ ${#ROOT_ARGS[@]} -gt 0 ]] || { write_status error "Keine WebDAV-Wurzeln konfiguriert"; exit 1; }
OLD_MAPPING_HASH=""
if [[ -r "$WEBDAV_MAPPING_FILE" ]]; then
OLD_MAPPING_HASH="$(sha256sum -- "$WEBDAV_MAPPING_FILE" | awk '{print $1}')"
fi
# Der Scanner liefert die eigentliche Fehlerursache auf stderr. Diese Ausgabe
# darf nicht vom allgemeinen ERR-Trap verschluckt werden, weil im Admin sonst
# nur die aufgerufene Python-Befehlszeile statt der Ursache sichtbar ist.
PLACEHOLDER_OUTPUT=""
PLACEHOLDER_EXIT=0
trap - ERR
if PLACEHOLDER_OUTPUT="$(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" 2>&1)"; then
PLACEHOLDER_EXIT=0
else
PLACEHOLDER_EXIT=$?
fi
trap 'failure $? "$BASH_COMMAND" "$LINENO"' ERR
[[ -z "$PLACEHOLDER_OUTPUT" ]] || printf '%s\n' "$PLACEHOLDER_OUTPUT"
if [[ "$PLACEHOLDER_EXIT" -ne 0 ]]; then
DETAIL="Exit-Code: $PLACEHOLDER_EXIT"
if [[ -n "$PLACEHOLDER_OUTPUT" ]]; then
DETAIL+="; Ausgabe: $(printf '%s\n' "$PLACEHOLDER_OUTPUT" | compact_output)"
fi
write_status error "Nextcloud-WebDAV konnte nicht eingelesen werden" "$DETAIL"
exit "$PLACEHOLDER_EXIT"
fi
find "$WEBDAV_SOURCE_DIR" -type d -exec chgrp www-data -- {} +
find "$WEBDAV_SOURCE_DIR" -type d -exec chmod 0775 -- {} +
find "$WEBDAV_SOURCE_DIR" -type f -exec chgrp www-data -- {} +
find "$WEBDAV_SOURCE_DIR" -type f -exec chmod 0664 -- {} +
chgrp www-data -- "$WEBDAV_MAPPING_FILE"
chmod 0640 -- "$WEBDAV_MAPPING_FILE"
NEW_MAPPING_HASH="$(sha256sum -- "$WEBDAV_MAPPING_FILE" | awk '{print $1}')"
if [[ -z "$OLD_MAPPING_HASH" || "$OLD_MAPPING_HASH" != "$NEW_MAPPING_HASH" ]]; then
printf '%s\n' "$NEW_MAPPING_HASH" > "$CHANGE_FILE"
chmod 0640 -- "$CHANGE_FILE"
else
rm -f -- "$CHANGE_FILE"
# Eine alte Prioritaetsmarke darf einen laufenden Rebuild nicht abbrechen,
# wenn der gerade abgeschlossene Connector-Sync keinerlei Aenderung
# festgestellt hat.
rm -f -- "$PRIORITY_FILE"
fi
python3 "$SCRIPT_DIR/lib/shadow_tree.py" \
--manifest "$MANIFEST" \
--destination "$GALLERY_ROOT" \
--state "$SHADOW_MAP_FILE"
trap - ERR
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
CLEANUP_OUTPUT=""
CLEANUP_EXIT=0
if CLEANUP_OUTPUT="$(php "$SCRIPT_DIR/repair-webdav-orphans.php" 2>&1)"; then
CLEANUP_EXIT=0
else
CLEANUP_EXIT=$?
fi
[[ -z "$CLEANUP_OUTPUT" ]] || printf '%s\n' "$CLEANUP_OUTPUT"
if [[ "$CLEANUP_EXIT" -ne 0 ]]; then
DETAIL="Exit-Code: $CLEANUP_EXIT"
if [[ -n "$CLEANUP_OUTPUT" ]]; then
DETAIL+="; Ausgabe: $(printf '%s\n' "$CLEANUP_OUTPUT" | compact_output)"
fi
write_status error "Verwaiste Piwigo-Bilder entfernter WebDAV-Quellen konnten nicht bereinigt werden" "$DETAIL"
exit "$CLEANUP_EXIT"
fi
METADATA_OUTPUT=""
METADATA_EXIT=0
if METADATA_OUTPUT="$(php "$SCRIPT_DIR/lib/sync-webdav-metadata.php" \
--piwigo-root="$PIWIGO_ROOT" \
--connection-id="$CONNECTION_ID" \
--mapping="$WEBDAV_MAPPING_FILE" 2>&1)"; then
METADATA_EXIT=0
else
METADATA_EXIT=$?
fi
[[ -z "$METADATA_OUTPUT" ]] || printf '%s\n' "$METADATA_OUTPUT"
if [[ "$METADATA_EXIT" -ne 0 ]]; then
DETAIL="Exit-Code: $METADATA_EXIT"
if [[ -n "$METADATA_OUTPUT" ]]; then
DETAIL+="; Ausgabe: $(printf '%s\n' "$METADATA_OUTPUT" | compact_output)"
fi
write_status error "Piwigo-Bildabmessungen konnten nicht mit den WebDAV-Metadaten abgeglichen werden" "$DETAIL"
exit "$METADATA_EXIT"
fi
if grep -q 'Piwigo-Synchronisierung per API erfolgreich' <<<"$PIWIGO_OUTPUT"; then
write_status ok \
"WebDAV eingelesen und Piwigo synchronisiert" \
"" \
"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 und Piwigo über Fallback synchronisiert" \
"" \
"fallback" \
"not_used" \
"API war nicht nutzbar" \
"ok" \
"Benutzername/Passwort-Fallback erfolgreich"
else
write_status ok "WebDAV eingelesen und Piwigo synchronisiert"
fi
else
write_status ok "WebDAV eingelesen; Registrierung erfolgt über den bestehenden produktiven Piwigo-Sync"
fi

View File

@@ -1,211 +0,0 @@
#!/usr/bin/env bash
set -Eeuo pipefail
CONFIG_FILE="${PIWIGO_CONFIG:-/etc/bratonien-tools/nc-connector/connection-1.conf}"
[[ -r "$CONFIG_FILE" ]] || { echo "Konfiguration fehlt: $CONFIG_FILE" >&2; exit 1; }
PIWIGO_SYNC_OVERRIDE_VALUE="${PIWIGO_SYNC_OVERRIDE-}"
# shellcheck source=/dev/null
source "$CONFIG_FILE"
NC_ACTIVITY_VIEW="${NC_ACTIVITY_VIEW:-piwigo_showcase_activity}"
NC_DB_VIEW="${NC_DB_VIEW:-piwigo_showcase_sources}"
if [[ -n "$PIWIGO_SYNC_OVERRIDE_VALUE" ]]; then
case "$PIWIGO_SYNC_OVERRIDE_VALUE" in
0|1) PIWIGO_SYNC_ENABLED="$PIWIGO_SYNC_OVERRIDE_VALUE" ;;
*) echo "PIWIGO_SYNC_OVERRIDE muss 0 oder 1 sein." >&2; exit 1 ;;
esac
fi
install -d -m 0750 "$STATE_DIR"
MANIFEST="$STATE_DIR/manifest.tsv"
MAP_FILE="$STATE_DIR/name-map.json"
LOCK_FILE="$STATE_DIR/sync.lock"
ACTIVITY_STATE="$STATE_DIR/activity.json"
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
CONNECTION_ID="${CONNECTION_ID:-}"
if [[ -z "$CONNECTION_ID" ]]; then
CONFIG_BASENAME="$(basename -- "$CONFIG_FILE")"
if [[ "$CONFIG_BASENAME" =~ ^connection-([0-9]+)\.conf$ ]]; then
CONNECTION_ID="${BASH_REMATCH[1]}"
else
echo "Connector-ID konnte nicht aus $CONFIG_FILE ermittelt werden." >&2
exit 1
fi
fi
PUBLIC_STATUS_DIR="${PIWIGO_ROOT%/}/_data/bratonien-tools/nc-connector-status"
PUBLIC_STATUS_FILE="$PUBLIC_STATUS_DIR/connection-$CONNECTION_ID.json"
install -d -m 0755 "${PIWIGO_ROOT%/}/_data/bratonien-tools" "$PUBLIC_STATUS_DIR"
exec 9>"$LOCK_FILE"
flock -n 9 || exit 0
AUTH_MODE=""
API_STATE="not_run"
API_MESSAGE=""
FALLBACK_STATE="not_run"
FALLBACK_MESSAGE=""
ERROR_DETAIL=""
write_status() {
local state="$1" message="$2"
local error_detail="$ERROR_DETAIL"
if [[ "$state" != "error" ]]; then
error_detail=""
fi
python3 - "$STATUS_FILE" "$PUBLIC_STATUS_FILE" "$state" "$message" "$AUTH_MODE" "$API_STATE" "$API_MESSAGE" "$FALLBACK_STATE" "$FALLBACK_MESSAGE" "$error_detail" <<'PY'
import json, os, sys, tempfile, time
(path, public_path, state, message, auth_mode, api_state, api_message,
fallback_state, fallback_message, error_detail) = 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": error_detail,
}
def write_json(target):
os.makedirs(os.path.dirname(target), exist_ok=True)
fd, temporary = tempfile.mkstemp(dir=os.path.dirname(target))
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)
write_json(path)
write_json(public_path)
PY
}
failure() {
[[ -n "$ERROR_DETAIL" ]] || ERROR_DETAIL="Synchronisierung wurde durch einen technischen Fehler abgebrochen."
write_status error "Synchronisierung fehlgeschlagen"
}
trap failure ERR
NEEDS_LOCAL_REPAIR=0
if [[ ! -s "$MAP_FILE" ]]; then
NEEDS_LOCAL_REPAIR=1
else
set +e
python3 - "$MAP_FILE" "$GALLERY_ROOT" <<'PY'
import json
import sys
from pathlib import Path
mapping = json.loads(Path(sys.argv[1]).read_text(encoding="utf-8"))
gallery = Path(sys.argv[2])
roots = [
target for source, target in mapping.items()
if source.startswith("share:") and "/" not in source
]
raise SystemExit(0 if roots and all((gallery / target).is_dir() for target in roots) else 1)
PY
ROOTS_INTACT=$?
set -e
[[ "$ROOTS_INTACT" == "0" ]] || NEEDS_LOCAL_REPAIR=1
fi
if [[ "$NEEDS_LOCAL_REPAIR" == "0" && "${PIWIGO_SYNC_ENABLED:-0}" == "1" ]]; then
set +e
php "$SCRIPT_DIR/lib/piwigo-db-check.php" "$MAP_FILE" "$PIWIGO_ROOT"
PIWIGO_ALBUMS_INTACT=$?
set -e
[[ "$PIWIGO_ALBUMS_INTACT" == "0" ]] || NEEDS_LOCAL_REPAIR=1
fi
if [[ "$NEEDS_LOCAL_REPAIR" == "1" ]]; then
GATE_RESULT=0
else
if python3 "$SCRIPT_DIR/lib/activity_gate.py" check \
--state "$ACTIVITY_STATE" --host "$NC_DB_HOST" --port "$NC_DB_PORT" \
--database "$NC_DB_NAME" --user "$NC_DB_USER" --password-file "$NC_DB_PASSWORD_FILE" \
--view "$NC_ACTIVITY_VIEW" --source-view "$NC_DB_VIEW" \
--quiet "$QUIET_SECONDS" --max-wait "$MAX_WAIT_SECONDS" --full-after "$FULL_SYNC_SECONDS"; then
GATE_RESULT=0
else
GATE_RESULT=$?
fi
fi
if [[ "$GATE_RESULT" == "3" ]]; then
trap - ERR
write_status ok "Keine Änderungen gefunden"
exit 0
fi
[[ "$GATE_RESULT" == "0" ]] || { ERROR_DETAIL="Activity-Gate fehlgeschlagen (Exit-Code $GATE_RESULT)."; exit "$GATE_RESULT"; }
python3 "$SCRIPT_DIR/lib/build_manifest.py" \
--host "$NC_DB_HOST" --port "$NC_DB_PORT" --database "$NC_DB_NAME" --user "$NC_DB_USER" \
--password-file "$NC_DB_PASSWORD_FILE" --view "$NC_DB_VIEW" \
--storage-config "$STORAGE_CONFIG" --output "$MANIFEST"
python3 "$SCRIPT_DIR/lib/shadow_tree.py" \
--manifest "$MANIFEST" --destination "$GALLERY_ROOT" --state "$MAP_FILE"
if [[ "${PIWIGO_SYNC_ENABLED:-0}" == "1" ]]; then
set +e
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)"
PIWIGO_EXIT=$?
set -e
printf '%s\n' "$PIWIGO_OUTPUT"
if grep -q 'Piwigo-Synchronisierung per API erfolgreich' <<<"$PIWIGO_OUTPUT"; then
AUTH_MODE="api"
API_STATE="ok"
API_MESSAGE="API-Synchronisierung erfolgreich"
FALLBACK_STATE="not_needed"
FALLBACK_MESSAGE="Fallback wurde nicht benötigt"
else
API_LINE="$(grep -m1 '^Piwigo-API nicht nutzbar:' <<<"$PIWIGO_OUTPUT" || true)"
if [[ -n "$API_LINE" ]]; then
API_STATE="error"
API_MESSAGE="${API_LINE#Piwigo-API nicht nutzbar: }"
else
API_STATE="error"
API_MESSAGE="API-Synchronisierung war nicht erfolgreich"
fi
if grep -q 'Piwigo-Datenbanksynchronisierung per Benutzername/Passwort-Fallback erfolgreich' <<<"$PIWIGO_OUTPUT"; then
AUTH_MODE="fallback"
FALLBACK_STATE="ok"
FALLBACK_MESSAGE="Benutzername/Passwort-Fallback erfolgreich"
elif [[ "$PIWIGO_EXIT" -ne 0 ]]; then
AUTH_MODE="failed"
FALLBACK_STATE="error"
FALLBACK_MESSAGE="$(tail -n 1 <<<"$PIWIGO_OUTPUT")"
fi
fi
if [[ "$PIWIGO_EXIT" -ne 0 ]]; then
ERROR_DETAIL="$(tail -n 3 <<<"$PIWIGO_OUTPUT" | tr '\n' ' ' | sed 's/[[:space:]]\+/ /g; s/[[:space:]]$//')"
trap - ERR
write_status error "Synchronisierung fehlgeschlagen"
exit "$PIWIGO_EXIT"
fi
fi
python3 "$SCRIPT_DIR/lib/activity_gate.py" commit \
--state "$ACTIVITY_STATE" --host "$NC_DB_HOST" --port "$NC_DB_PORT" \
--database "$NC_DB_NAME" --user "$NC_DB_USER" --password-file "$NC_DB_PASSWORD_FILE" \
--view "$NC_ACTIVITY_VIEW" --source-view "$NC_DB_VIEW"
trap - ERR
if [[ "$AUTH_MODE" == "fallback" ]]; then
write_status warning "Synchronisierung erfolgreich über Fallback; API war nicht nutzbar"
elif [[ "$AUTH_MODE" == "api" ]]; then
write_status ok "Synchronisierung erfolgreich über API"
else
write_status ok "Synchronisierung erfolgreich"
fi

View File

@@ -0,0 +1,421 @@
<?php
if (PHP_SAPI !== 'cli')
{
http_response_code(404);
exit;
}
$piwigo_root = realpath(dirname(__DIR__, 3));
if ($piwigo_root === false)
{
fwrite(STDERR, "Piwigo-Root wurde nicht gefunden.\n");
exit(1);
}
define('PHPWG_ROOT_PATH', rtrim($piwigo_root, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR);
$_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/webdav-warmup-dispatch.php';
$_SERVER['PHP_SELF'] = $_SERVER['SCRIPT_NAME'];
$_SERVER['QUERY_STRING'] = '';
$_SERVER['HTTP_USER_AGENT'] = 'Bratonien-WebDAV-Worker-Dispatcher/0.9.7.1.50';
$_SERVER['HTTPS'] = 'off';
require_once(PHPWG_ROOT_PATH.'include/common.inc.php');
if (!defined('BRATONIEN_TOOLS_PATH'))
{
fwrite(STDERR, "Bratonien Tools ist nicht aktiv.\n");
exit(1);
}
require_once(BRATONIEN_TOOLS_PATH.'include/nc_connector.inc.php');
require_once(BRATONIEN_TOOLS_PATH.'include/webdav_warmup_settings.inc.php');
function bratonien_tools_webdav_dispatch_existing_status($connection_id)
{
if (!function_exists('bratonien_tools_webdav_warmup_status_file_for_connection')) return null;
$file = bratonien_tools_webdav_warmup_status_file_for_connection($connection_id);
if (!is_file($file) || !is_readable($file)) return null;
$raw = @file_get_contents($file);
$data = $raw !== false ? json_decode($raw, true) : null;
return is_array($data) ? $data : null;
}
function bratonien_tools_webdav_dispatch_failure_lines(array $output)
{
$failures = array();
foreach ($output as $line)
{
$line = trim((string)$line);
if ($line === '') continue;
if (
strpos($line, 'download_failed') !== false
|| strpos($line, ' ok=0 ') !== false
|| strpos($line, '[BRAT-WORKER] fatal ') !== false
|| stripos($line, 'RESTORE FEHLGESCHLAGEN') !== false
)
{
$failures[] = $line;
if (count($failures) >= 8) break;
}
}
return $failures;
}
function bratonien_tools_webdav_dispatch_only_connector_deferrals(array $output)
{
$seen = false;
foreach ($output as $line)
{
$line = trim((string)$line);
if ($line === '') continue;
if (strpos($line, '[BRAT-WORKER] fatal ') !== false || strpos($line, 'download_failed') !== false || stripos($line, 'RESTORE FEHLGESCHLAGEN') !== false)
{
return false;
}
if (strpos($line, ' ok=0 ') !== false)
{
$seen = true;
if (strpos($line, 'message=Connector-Synchronisierung läuft.') === false && strpos($line, 'message=Connector-Mapping hat sich seit dem Batch-Download geändert.') === false && strpos($line, 'message=Shadow-Tree hat sich seit dem Batch-Download geändert.') === false)
{
return false;
}
}
}
return $seen;
}
function bratonien_tools_webdav_dispatch_connector_service_active()
{
if (!function_exists('exec') || !is_executable('/usr/bin/systemctl')) return false;
$output = array();
$exit = 1;
@exec('/usr/bin/systemctl is-active --quiet bratonien-nc-connector.service 2>/dev/null', $output, $exit);
return $exit === 0;
}
function bratonien_tools_webdav_dispatch_reset_orphan_sync_lock($state_dir)
{
$path = rtrim((string)$state_dir, '/').'/webdav-sync.lock';
if (!is_file($path)) return true;
$lock = @fopen($path, 'c');
if (!$lock) return false;
if (@flock($lock, LOCK_SH | LOCK_NB))
{
@flock($lock, LOCK_UN);
fclose($lock);
return true;
}
fclose($lock);
// Der Produktions-Connector darf ausschließlich über den systemd-Dienst
// laufen. Ist dieser nicht aktiv, ist ein weiterhin exklusiv belegter Lock
// kein gültiger Connector-Zustand. Den alten Inode hängen wir aus und legen
// eine frische Lockdatei an, damit ein verwaister Altprozess den Cache nicht
// dauerhaft blockiert. Ein späterer echter Connector benutzt automatisch die
// neue Datei.
if (bratonien_tools_webdav_dispatch_connector_service_active()) return false;
$orphan = $path.'.orphan-'.date('YmdHis').'-'.getmypid();
if (!@rename($path, $orphan)) return false;
$fresh = @fopen($path, 'c');
if (!$fresh)
{
@rename($orphan, $path);
return false;
}
@chmod($path, 0660);
fclose($fresh);
@file_put_contents(PHPWG_ROOT_PATH.PWG_LOCAL_DIR.'bratonien-webdav-warmup.log', '[BRAT-WORKER] orphan_sync_lock_reset old='.basename($orphan)."\n", FILE_APPEND | LOCK_EX);
return true;
}
function bratonien_tools_webdav_dispatch_connector_busy($state_dir)
{
$path = rtrim((string)$state_dir, '/').'/webdav-sync.lock';
$lock = @fopen($path, 'c');
if (!$lock) return false;
if (@flock($lock, LOCK_SH | LOCK_NB))
{
@flock($lock, LOCK_UN);
fclose($lock);
return false;
}
fclose($lock);
if (bratonien_tools_webdav_dispatch_connector_service_active()) return true;
// Genau der hier beobachtete Fehlerfall: Lock belegt, aber kein Connector-
// Dienst aktiv. Nicht als "Connector läuft" darstellen, sondern den
// verwaisten Lockzustand reparieren und den Cache normal starten lassen.
if (bratonien_tools_webdav_dispatch_reset_orphan_sync_lock($state_dir)) return false;
// Konnte der ungültige Lockzustand nicht sicher repariert werden, wird nicht
// behauptet, dass ein Connector läuft. Der Worker erhält stattdessen einen
// echten Fehler und kann den Zustand sichtbar machen.
throw new RuntimeException('WebDAV-Sync-Lock ist belegt, obwohl der Connector-Dienst nicht aktiv ist, und konnte nicht sicher zurückgesetzt werden.');
}
function bratonien_tools_webdav_dispatch_schedule_after_sync($waiter, $state_dir, $worker_command, $log, &$pid=null)
{
$pid = 0;
$deferred = escapeshellarg('/bin/bash').' '.escapeshellarg($waiter).' '.escapeshellarg($state_dir).' '.$worker_command;
$command = 'nohup '.$deferred.' >> '.escapeshellarg($log).' 2>&1 < /dev/null & echo $!';
$output = array();
$exit = 1;
@exec($command, $output, $exit);
$pid = isset($output[0]) ? (int)$output[0] : 0;
return $exit === 0 && $pid > 0;
}
$mode = 'periodic';
$wait = false;
$connection_filter = 0;
foreach ($argv as $arg)
{
if (preg_match('/^--mode=(sync|periodic|manual|rebuild)$/', $arg, $m)) $mode = $m[1];
elseif (preg_match('/^--connection-id=(\d+)$/', $arg, $m)) $connection_filter = (int)$m[1];
elseif ($arg === '--wait') $wait = true;
}
$settings = bratonien_tools_get_webdav_warmup_settings();
if (!in_array($mode, array('manual','rebuild'), true) && empty($settings['enabled']))
{
fwrite(STDOUT, "WebDAV-Worker ist deaktiviert.\n");
exit(0);
}
if (!function_exists('exec'))
{
fwrite(STDERR, "PHP exec() ist deaktiviert; Worker kann nicht gestartet werden.\n");
exit(1);
}
$worker = realpath(BRATONIEN_TOOLS_PATH.'runtime/lib/webdav-cache-warmup.php');
$priority_waiter = realpath(BRATONIEN_TOOLS_PATH.'runtime/lib/run-webdav-priority-wait.sh');
$after_sync_waiter = realpath(BRATONIEN_TOOLS_PATH.'runtime/lib/run-webdav-after-sync.sh');
if (!$worker || !is_file($worker))
{
fwrite(STDERR, "WebDAV-Worker wurde nicht gefunden.\n");
exit(1);
}
if (!$priority_waiter || !is_file($priority_waiter))
{
fwrite(STDERR, "WebDAV-Prioritäts-Warter wurde nicht gefunden.\n");
exit(1);
}
if (!$after_sync_waiter || !is_file($after_sync_waiter))
{
fwrite(STDERR, "WebDAV-Connector-Warter wurde nicht gefunden.\n");
exit(1);
}
$log = PHPWG_ROOT_PATH.PWG_LOCAL_DIR.'bratonien-webdav-warmup.log';
$result = 0;
$started = 0;
$matched = 0;
$run_inline = $wait || in_array($mode, array('manual','rebuild'), true);
foreach (bratonien_tools_nc_connector_connections() as $connection)
{
if (empty($connection['enabled']) || !bratonien_tools_nc_connector_is_webdav($connection)) continue;
$connection_id = (int)$connection['id'];
if ($connection_id < 1) continue;
if ($connection_filter > 0 && $connection_id !== $connection_filter) continue;
$matched++;
$config = isset($connection['config']) && is_array($connection['config']) ? $connection['config'] : array();
$state_dir = rtrim((string)($config['state_dir'] ?? ''), '/');
if ($state_dir === '')
{
fwrite(STDERR, "Worker für Verbindung #{$connection_id} übersprungen: Connector-State-Verzeichnis fehlt.\n");
$result = 1;
continue;
}
$worker_command = escapeshellarg(PHP_BINARY).' '.escapeshellarg($worker)
.' --connection-id='.$connection_id
.' --mode='.escapeshellarg($mode);
try
{
$connector_busy = $mode !== 'sync' && bratonien_tools_webdav_dispatch_connector_busy($state_dir);
}
catch (Throwable $e)
{
if (function_exists('bratonien_tools_webdav_warmup_write_status'))
{
bratonien_tools_webdav_warmup_write_status($connection_id, 'error', $e->getMessage(), array('mode'=>$mode, 'deferred_by_connector'=>false));
}
fwrite(STDERR, $e->getMessage()."\n");
$result = 1;
continue;
}
if ($mode === 'sync')
{
if (!is_dir($state_dir) && !@mkdir($state_dir, 0750, true) && !is_dir($state_dir))
{
fwrite(STDERR, "Worker-Priorität für Verbindung #{$connection_id} konnte nicht signalisiert werden: State-Verzeichnis fehlt.\n");
$result = 1;
continue;
}
$priority_file = $state_dir.'/webdav-cache-warmup-priority-sync';
$priority_payload = json_encode(array(
'connection_id'=>$connection_id,
'requested_at'=>time(),
'reason'=>'connector-sync-complete',
), JSON_UNESCAPED_SLASHES);
if (!is_string($priority_payload) || @file_put_contents($priority_file, $priority_payload."\n", LOCK_EX) === false)
{
fwrite(STDERR, "Worker-Priorität für Verbindung #{$connection_id} konnte nicht geschrieben werden.\n");
$result = 1;
continue;
}
@chmod($priority_file, 0664);
}
elseif ($connector_busy)
{
$resume_pid = 0;
$scheduled = bratonien_tools_webdav_dispatch_schedule_after_sync($after_sync_waiter, $state_dir, $worker_command, $log, $resume_pid);
if (function_exists('bratonien_tools_webdav_warmup_write_status'))
{
bratonien_tools_webdav_warmup_write_status(
$connection_id,
$scheduled ? 'waiting' : 'error',
$scheduled
? 'Connector-Synchronisierung läuft. Der Cache-Worker ist vorgemerkt und startet automatisch unmittelbar danach; es werden vorher keine Nextcloud-Originale geladen.'
: 'Connector-Synchronisierung läuft, aber der automatische Cache-Fortsetzungsauftrag konnte nicht gestartet werden.',
array('mode'=>$mode, 'deferred_by_connector'=>true, 'resume_scheduled'=>$scheduled, 'resume_pid'=>$resume_pid)
);
}
if (!$scheduled)
{
fwrite(STDERR, "Wartender WebDAV-Worker für Verbindung #{$connection_id} konnte nicht gestartet werden.\n");
$result = 1;
continue;
}
$started++;
fwrite(STDOUT, "WebDAV-Worker für Verbindung #{$connection_id} wartet auf den Connector-Sync und startet danach automatisch (PID {$resume_pid}).\n");
continue;
}
$base = $mode === 'sync'
? escapeshellarg('/bin/bash').' '.escapeshellarg($priority_waiter).' '.escapeshellarg($state_dir).' '.$worker_command
: $worker_command;
if ($run_inline)
{
$output = array();
$exit = 1;
@exec($base.' 2>&1', $output, $exit);
foreach ($output as $line)
{
fwrite(STDOUT, $line."\n");
@file_put_contents($log, $line."\n", FILE_APPEND | LOCK_EX);
}
if ($exit !== 0)
{
$deferred = bratonien_tools_webdav_dispatch_only_connector_deferrals($output);
if ($deferred)
{
$resume_pid = 0;
$scheduled = bratonien_tools_webdav_dispatch_schedule_after_sync($after_sync_waiter, $state_dir, $worker_command, $log, $resume_pid);
if (function_exists('bratonien_tools_webdav_warmup_write_status'))
{
$existing = bratonien_tools_webdav_dispatch_existing_status($connection_id);
$extra = is_array($existing) ? $existing : array();
unset($extra['state'], $extra['message'], $extra['connection_id'], $extra['updated_at']);
$extra['worker_exit_code'] = (int)$exit;
$extra['deferred_by_connector'] = true;
$extra['resume_scheduled'] = $scheduled;
$extra['resume_pid'] = $resume_pid;
bratonien_tools_webdav_warmup_write_status(
$connection_id,
$scheduled ? 'waiting' : 'error',
$scheduled
? 'Connector-Synchronisierung hat während des Batches Vorrang erhalten. Der bisherige Indexstand bleibt erhalten; der Cache-Worker ist zur automatischen Fortsetzung vorgemerkt.'
: 'Connector-Synchronisierung hat während des Batches Vorrang erhalten, aber die automatische Fortsetzung konnte nicht vorgemerkt werden.',
$extra
);
}
if (!$scheduled) $result = 1;
else $started++;
continue;
}
$result = $exit;
if (function_exists('bratonien_tools_webdav_warmup_write_status'))
{
$existing = bratonien_tools_webdav_dispatch_existing_status($connection_id);
$failures = bratonien_tools_webdav_dispatch_failure_lines($output);
$terminal = is_array($existing) && in_array((string)($existing['state'] ?? ''), array('error','fatal','preempted','cancelled'), true);
if ($terminal)
{
$message = trim((string)($existing['message'] ?? 'WebDAV-Worker wurde mit Fehlern beendet.'));
if ($failures)
{
$message .= ' Fehlerbeispiele: '.implode(' | ', $failures);
}
$extra = $existing;
unset($extra['state'], $extra['message'], $extra['connection_id'], $extra['updated_at']);
$extra['worker_exit_code'] = (int)$exit;
$extra['dispatcher_preserved_worker_status'] = true;
if ($failures) $extra['failure_examples'] = $failures;
bratonien_tools_webdav_warmup_write_status(
$connection_id,
(string)$existing['state'],
$message,
$extra
);
}
else
{
$detail = $failures
? implode(' | ', $failures)
: ($output ? implode(' ', array_slice($output, -8)) : 'keine Worker-Ausgabe');
bratonien_tools_webdav_warmup_write_status(
$connection_id,
'error',
'WebDAV-Worker Exit '.(int)$exit.'. Ursache: '.$detail,
array('mode'=>$mode, 'worker_exit_code'=>(int)$exit, 'failure_examples'=>$failures)
);
}
}
}
else
{
$started++;
}
}
else
{
$command = 'nohup '.$base.' >> '.escapeshellarg($log).' 2>&1 < /dev/null & echo $!';
$output = array();
$exit = 1;
@exec($command, $output, $exit);
$pid = isset($output[0]) ? (int)$output[0] : 0;
if ($exit !== 0 || $pid <= 0)
{
fwrite(STDERR, "Worker für Verbindung #{$connection_id} konnte nicht gestartet werden.\n");
$result = 1;
continue;
}
$started++;
fwrite(STDOUT, "WebDAV-Worker {$mode} für Verbindung #{$connection_id} gestartet (PID {$pid}).\n");
}
}
if ($connection_filter > 0 && $matched === 0)
{
fwrite(STDERR, "WebDAV-Verbindung #{$connection_filter} wurde nicht als aktive Connector-Verbindung gefunden.\n");
exit(1);
}
if (!$run_inline) fwrite(STDOUT, "Gestartete WebDAV-Worker: {$started}.\n");
exit($result);

View File

@@ -11,9 +11,7 @@
.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} }
</style>
<div id="bratonien-tabs-anchor"></div>
<script>
(function () {
'use strict';
@@ -22,119 +20,133 @@
{ id:'wasserzeichen', label:'Wasserzeichen', sections:['uebersicht','wasserzeichen','regeln'] },
{ id:'auswahl-download', label:'Fotoauswahl & Downloads' },
{ id:'freigaben', label:'Geschützte Freigaben' },
{ id:'qr-upload', label:'QR-Upload' },
{ id:'nc-connector', label:'NC Connector' },
{ id:'bilddateien', label:'Bilddateien & Pfade' },
{ id:'wartung', label:'Wartung / Cache' },
{ id:'system', label:'System & Updates' }
];
var panels = [];
definitions.forEach(function (d) {
var ids=d.sections||[d.id], elements=[];
var panels=[];
definitions.forEach(function(d){
var ids=d.sections||[d.id],elements=[];
ids.forEach(function(id){var el=document.getElementById(id);if(el){el.classList.add('bratonien-tab-panel');elements.push(el);}});
if (!elements.length) return;
panels.push({definition:d,elements:elements});
});
if (!panels.length) return;
var anchor = document.getElementById('bratonien-tabs-anchor');
if (!anchor) return;
var tabs = document.createElement('div');
tabs.className = 'bratonien-tabs';
tabs.setAttribute('role','tablist');
tabs.setAttribute('aria-label','Bratonien Tools Bereiche');
panels.forEach(function (item) {
var b = document.createElement('button');
b.type='button';
b.className='bratonien-tab';
b.id='bratonien-tab-'+item.definition.id;
b.dataset.tab=item.definition.id;
b.setAttribute('role','tab');
b.textContent=item.definition.label;
tabs.appendChild(b);
item.elements.forEach(function(el){el.setAttribute('role','tabpanel');el.setAttribute('aria-labelledby',b.id);});
if(elements.length)panels.push({definition:d,elements:elements});
});
if(!panels.length)return;
var anchor=document.getElementById('bratonien-tabs-anchor');if(!anchor)return;
var tabs=document.createElement('div');tabs.className='bratonien-tabs';tabs.setAttribute('role','tablist');tabs.setAttribute('aria-label','Bratonien Tools Bereiche');
panels.forEach(function(item){var b=document.createElement('button');b.type='button';b.className='bratonien-tab';b.id='bratonien-tab-'+item.definition.id;b.dataset.tab=item.definition.id;b.setAttribute('role','tab');b.textContent=item.definition.label;tabs.appendChild(b);item.elements.forEach(function(el){el.setAttribute('role','tabpanel');el.setAttribute('aria-labelledby',b.id);});});
anchor.replaceWith(tabs);
function activate(id, remember) {
var valid=false;
panels.forEach(function (item) {
var active=item.definition.id===id;
item.elements.forEach(function(el){el.hidden=!active;});
var b=tabs.querySelector('[data-tab="'+item.definition.id+'"]');
if (b) {
b.classList.toggle('is-active',active);
b.setAttribute('aria-selected',active?'true':'false');
b.tabIndex=active?0:-1;
}
if (active) valid=true;
});
if (!valid) return activate(panels[0].definition.id,remember);
if (remember!==false) { try { localStorage.setItem('bratonien-tools-active-tab',id); } catch(e) {} }
}
tabs.addEventListener('click',function(e){ var b=e.target.closest('.bratonien-tab'); if(b) activate(b.dataset.tab); });
tabs.addEventListener('keydown',function(e){
if(e.key!=='ArrowLeft'&&e.key!=='ArrowRight') return;
var buttons=[].slice.call(tabs.querySelectorAll('.bratonien-tab'));
var i=buttons.indexOf(document.activeElement); if(i<0) return;
e.preventDefault(); i += e.key==='ArrowRight'?1:-1; if(i>=buttons.length)i=0; if(i<0)i=buttons.length-1;
buttons[i].focus(); activate(buttons[i].dataset.tab);
});
var initial='';
var hash=location.hash?location.hash.slice(1):'';
panels.forEach(function(item){if(item.definition.id===hash||(item.definition.sections||[]).indexOf(hash)!==-1)initial=item.definition.id;});
if(!initial){ try { initial=localStorage.getItem('bratonien-tools-active-tab')||''; } catch(e){} }
if(!panels.some(function(i){return i.definition.id===initial})) initial=panels[0].definition.id;
activate(initial,false);
function activate(id,remember){var valid=false;panels.forEach(function(item){var active=item.definition.id===id;item.elements.forEach(function(el){el.hidden=!active;});var b=tabs.querySelector('[data-tab="'+item.definition.id+'"]');if(b){b.classList.toggle('is-active',active);b.setAttribute('aria-selected',active?'true':'false');b.tabIndex=active?0:-1;}if(active)valid=true;});if(!valid)return activate(panels[0].definition.id,remember);if(remember!==false){try{localStorage.setItem('bratonien-tools-active-tab',id);}catch(e){}}}
tabs.addEventListener('click',function(e){var b=e.target.closest('.bratonien-tab');if(b)activate(b.dataset.tab);});
tabs.addEventListener('keydown',function(e){if(e.key!=='ArrowLeft'&&e.key!=='ArrowRight')return;var buttons=[].slice.call(tabs.querySelectorAll('.bratonien-tab'));var i=buttons.indexOf(document.activeElement);if(i<0)return;e.preventDefault();i+=e.key==='ArrowRight'?1:-1;if(i>=buttons.length)i=0;if(i<0)i=buttons.length-1;buttons[i].focus();activate(buttons[i].dataset.tab);});
var initial='',hash=location.hash?location.hash.slice(1):'';panels.forEach(function(item){if(item.definition.id===hash||(item.definition.sections||[]).indexOf(hash)!==-1)initial=item.definition.id;});if(!initial){try{initial=localStorage.getItem('bratonien-tools-active-tab')||'';}catch(e){}}if(!panels.some(function(i){return i.definition.id===initial;}))initial=panels[0].definition.id;activate(initial,false);
}
function initNCConnectorPolling() {
var section=document.getElementById('nc-connector');
if(!section) return;
var lastSeen=null;
function initNCWizardLifecycle(){
var section=document.getElementById('nc-connector');if(!section)return;
var dialog=document.getElementById('bratonien-nc-wizard-dialog');
var openButton=document.getElementById('bratonien-nc-wizard-open');
var closeButton=document.getElementById('bratonien-nc-wizard-close');
var storageKey='bratonienNcWizardOpen';
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 showWizard(){
setOpen(true);
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'));
var body=new URLSearchParams();body.set('pwg_token',pwgToken);body.set('bratonien_tool','nc_connector_wizard_reset');
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);
resetServer().catch(function(){}).finally(function(){resetBusy=false;if(dialog){if(typeof dialog.close==='function'&&dialog.open)dialog.close();else dialog.removeAttribute('open');}});
}
if(openButton){
openButton.addEventListener('click',function(event){
event.preventDefault();event.stopImmediatePropagation();showWizard();
},true);
}
if(closeButton){
closeButton.addEventListener('click',function(event){event.preventDefault();event.stopImmediatePropagation();closeAfterReset();},true);
}
if(dialog){
dialog.addEventListener('cancel',function(event){event.preventDefault();event.stopImmediatePropagation();closeAfterReset();},true);
dialog.addEventListener('click',function(event){if(event.target===dialog){event.preventDefault();event.stopImmediatePropagation();closeAfterReset();}},true);
// Every wizard POST explicitly preserves the open state before the
// browser leaves the page. Validation errors therefore return to the
// same wizard step instead of closing/resetting the dialog.
[].slice.call(dialog.querySelectorAll('form[data-bratonien-wizard-form]')).forEach(function(form){
form.addEventListener('submit',function(){setOpen(true);},true);
});
try{if(sessionStorage.getItem(storageKey)==='1')showWizard();}catch(e){}
}
}
function initNCConnectorPolling(){
var section=document.getElementById('nc-connector');if(!section)return;
var endpoint='plugins/bratonien_tools/nc-connector-status.php';
var pollTimer=null;
function poll() {
fetch(endpoint+'?_='+Date.now(),{credentials:'same-origin',cache:'no-store'})
.then(function(response){if(!response.ok) throw new Error('HTTP '+response.status); return response.json();})
.then(function(data){
var timestamp=parseInt(data.timestamp||0,10);
if(!timestamp) return;
function valueNodeForLabel(labelText){
var labels=[].slice.call(section.querySelectorAll('.bratonien-label'));
for(var i=0;i<labels.length;i++){
if((labels[i].textContent||'').trim()===labelText){
var node=labels[i].nextElementSibling;
return node&&node.tagName==='STRONG'?node:null;
}
}
return null;
}
if(lastSeen===null) {
lastSeen=timestamp;
var resultVisible=section.textContent.indexOf('Letztes Ergebnis:')!==-1;
if(!resultVisible && data.message) {
var reloadKey='bratonien-nc-status-reload-'+timestamp;
try {
if(sessionStorage.getItem(reloadKey)!=='1') {
sessionStorage.setItem(reloadKey,'1');
window.location.reload();
}
} catch(e) {}
}
return;
}
function lastResultValueNode(){
var notes=[].slice.call(section.querySelectorAll('.bratonien-base-note'));
for(var i=0;i<notes.length;i++){
var text=(notes[i].textContent||'').trim();
if(text.indexOf('Letztes Ergebnis:')===0){
return notes[i].querySelector('strong');
}
}
return null;
}
if(timestamp>lastSeen) {
lastSeen=timestamp;
window.location.reload();
}
})
var lastRunNode=valueNodeForLabel('Letzter Lauf');
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',headers:{'Accept':'application/json'}})
.then(function(response){if(!response.ok)throw new Error('HTTP '+response.status);return response.json();})
.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();
initNCConnectorPolling();
}
if(document.readyState==='loading') document.addEventListener('DOMContentLoaded',initAll); else initAll();
function initAll(){initBratonienTabs();initNCWizardLifecycle();initNCConnectorPolling();}
if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',initAll);else initAll();
})();
</script>
{/literal}

View File

@@ -0,0 +1,198 @@
{literal}
<style>
.bratonien-qr-stock-head{display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;margin-bottom:14px}
.bratonien-qr-stock-head h4{margin:0}
.bratonien-qr-legend{display:flex;gap:14px;align-items:center;flex-wrap:wrap;margin:0 0 16px}
.bratonien-qr-legend-item{display:inline-flex;gap:7px;align-items:center}
.bratonien-qr-legend-box{width:18px;height:18px;border-radius:4px;border:1px solid}
.bratonien-qr-legend-box.is-present{background:rgba(62,170,94,.28);border-color:#58c878}
.bratonien-qr-legend-box.is-missing{background:rgba(205,72,72,.25);border-color:#db6d6d}
.bratonien-qr-year{padding:14px 0;border-top:1px solid rgba(255,255,255,.10)}
.bratonien-qr-year:first-of-type{border-top:0;padding-top:0}
.bratonien-qr-year-head{display:flex;align-items:center;gap:12px;flex-wrap:wrap;margin-bottom:10px}
.bratonien-qr-year-head strong{font-size:1.05rem}
.bratonien-qr-year-count{opacity:.78}
.bratonien-qr-year-download{margin-left:auto}
.bratonien-qr-slots{display:grid;grid-template-columns:repeat(auto-fill,minmax(42px,1fr));gap:6px}
.bratonien-qr-slot{min-height:38px;display:flex;align-items:center;justify-content:center;border:1px solid;border-radius:5px;font-weight:700;text-decoration:none!important}
.bratonien-qr-slot.is-present{background:rgba(62,170,94,.28);border-color:#58c878;color:#dff7e6}
.bratonien-qr-slot.is-present:hover{background:rgba(62,170,94,.42);color:#fff}
.bratonien-qr-slot.is-missing{background:rgba(205,72,72,.25);border-color:#db6d6d;color:#ffdede}
@media(max-width:760px){.bratonien-qr-year-download{margin-left:0}.bratonien-qr-slots{grid-template-columns:repeat(auto-fill,minmax(38px,1fr))}}
</style>
{/literal}
<section class="bratonien-section" id="qr-upload">
<h3>QR-Upload</h3>
<p class="bratonien-section__intro">Aktivierbares Uploadformular für nummerierte QR-Codes und persönliche Freundschaftscodes.</p>
<div class="bratonien-grid">
<div class="bratonien-card">
<h4>Formular</h4>
<form method="post">
<input type="hidden" name="pwg_token" value="{$PWG_TOKEN|escape:html}">
<input type="hidden" name="bratonien_tool" value="customer_qr_settings">
<label style="display:flex;gap:10px;align-items:center;margin:0 0 14px">
<input type="checkbox" name="customer_qr_enabled" value="1" {if $CUSTOMER_QR.enabled}checked{/if}>
<strong>QR-Upload aktivieren</strong>
</label>
<button class="buttonLike" type="submit">Einstellung speichern</button>
</form>
<p class="bratonien-base-note" style="margin-top:14px">Ist das Formular deaktiviert, verschwindet der Menüpunkt und die Uploadseite nimmt keine Dateien an.</p>
</div>
<div class="bratonien-card">
<h4>Formular-Adresse</h4>
<div class="bratonien-form-grid">
<span class="bratonien-label">Status</span><strong>{if $CUSTOMER_QR.enabled}Aktiv{else}Deaktiviert{/if}</strong>
<span class="bratonien-label">Jahre</span><strong>{$CUSTOMER_QR.year_min}{$CUSTOMER_QR.year_max}</strong>
<span class="bratonien-label">Standardjahr</span><strong>{$CUSTOMER_QR.default_year}</strong>
<span class="bratonien-label">Server-Batchlimit</span><strong>{$CUSTOMER_QR.max_files} Dateien</strong>
<span class="bratonien-label">Freundschaftscodes</span><strong>{$CUSTOMER_QR.friendship_codes.total}</strong>
</div>
<p style="margin-top:14px;overflow-wrap:anywhere"><a href="{$CUSTOMER_QR.url|escape:html}" target="_blank" rel="noopener">{$CUSTOMER_QR.url|escape:html}</a></p>
</div>
<div class="bratonien-card">
<h4>Vorgesehene QR-Codes</h4>
<div class="bratonien-form-grid">
{foreach from=$CUSTOMER_QR.years item=qr_year}
<span class="bratonien-label">{$qr_year.year}</span>
<strong>{$qr_year.used} / {$qr_year.capacity} belegt · {$qr_year.remaining} frei</strong>
{/foreach}
</div>
<p class="bratonien-base-note">2023: Nummern 1100 · 2024: 150 · 2025 und 2026: jeweils 130. Weitere Jahre werden erst mit dem jeweiligen Jahresupdate ergänzt.</p>
</div>
<div class="bratonien-card">
<h4>Belegte QR-Code-Nummern</h4>
<div class="bratonien-form-grid">
<span class="bratonien-label">Gesamt</span><strong>{$CUSTOMER_QR.total}</strong>
<span class="bratonien-label">Im Standardjahr {$CUSTOMER_QR.default_year}</span><strong>{$CUSTOMER_QR.current_year_total} / {$CUSTOMER_QR.current_year_capacity}</strong>
</div>
<p class="bratonien-base-note">Eine QR-Code-Nummer ist pro Jahr eindeutig. Wird ein Upload gelöscht, ist die Nummer für dieses Jahr wieder frei.</p>
</div>
</div>
<div class="bratonien-card" style="margin-top:18px">
<div class="bratonien-qr-stock-head">
<h4>QR-Code-Bestand</h4>
{if $CUSTOMER_QR.batch_download_available and $CUSTOMER_QR.total > 0}
<a class="buttonLike" href="{$CUSTOMER_QR.batch_download_url|escape:html}">Alle QR-Codes als ZIP herunterladen</a>
{/if}
</div>
<div class="bratonien-qr-legend">
<span class="bratonien-qr-legend-item"><span class="bratonien-qr-legend-box is-present"></span>Vorhanden</span>
<span class="bratonien-qr-legend-item"><span class="bratonien-qr-legend-box is-missing"></span>Fehlt</span>
</div>
{foreach from=$CUSTOMER_QR.years item=qr_year}
<div class="bratonien-qr-year">
<div class="bratonien-qr-year-head">
<strong>{$qr_year.year}</strong>
<span class="bratonien-qr-year-count">{$qr_year.used} / {$qr_year.capacity} vorhanden · {$qr_year.remaining} fehlen</span>
{if $CUSTOMER_QR.batch_download_available and $qr_year.used > 0}
<a class="buttonLike bratonien-qr-year-download" href="{$qr_year.batch_download_url|escape:html}">{$qr_year.year} als ZIP</a>
{/if}
</div>
<div class="bratonien-qr-slots" aria-label="QR-Code-Bestand {$qr_year.year}">
{foreach from=$qr_year.slots item=qr_slot}
{if $qr_slot.present}
<a class="bratonien-qr-slot is-present" href="{$qr_slot.preview_url|escape:html}" target="_blank" rel="noopener" title="QR-Code #{$qr_slot.number} vorhanden Vorschau öffnen">{$qr_slot.number}</a>
{else}
<span class="bratonien-qr-slot is-missing" title="QR-Code #{$qr_slot.number} fehlt">{$qr_slot.number}</span>
{/if}
{/foreach}
</div>
</div>
{/foreach}
{if not $CUSTOMER_QR.batch_download_available}
<p class="bratonien-base-note" style="margin-top:14px">Batch-Download ist erst verfügbar, wenn die PHP-Erweiterung ZipArchive auf dem Server aktiv ist.</p>
{/if}
</div>
<div class="bratonien-card" style="margin-top:18px;overflow-x:auto">
<h4>QR-Codes verwalten</h4>
{if $CUSTOMER_QR.total > 0}
<table style="width:100%;border-collapse:collapse;min-width:820px">
<thead>
<tr>
<th style="text-align:left;padding:9px 8px;border-bottom:1px solid rgba(255,255,255,.14)">Jahr</th>
<th style="text-align:left;padding:9px 8px;border-bottom:1px solid rgba(255,255,255,.14)">QR-Nr.</th>
<th style="text-align:left;padding:9px 8px;border-bottom:1px solid rgba(255,255,255,.14)">Datei</th>
<th style="text-align:left;padding:9px 8px;border-bottom:1px solid rgba(255,255,255,.14)">Größe</th>
<th style="text-align:left;padding:9px 8px;border-bottom:1px solid rgba(255,255,255,.14)">Upload</th>
<th style="text-align:right;padding:9px 8px;border-bottom:1px solid rgba(255,255,255,.14)">Aktionen</th>
</tr>
</thead>
<tbody>
{foreach from=$CUSTOMER_QR.uploads item=qr_upload}
<tr>
<td style="padding:9px 8px;border-bottom:1px solid rgba(255,255,255,.08)"><strong>{$qr_upload.year}</strong></td>
<td style="padding:9px 8px;border-bottom:1px solid rgba(255,255,255,.08)"><strong>#{$qr_upload.number|escape:html}</strong></td>
<td style="padding:9px 8px;border-bottom:1px solid rgba(255,255,255,.08);max-width:300px;overflow-wrap:anywhere">{$qr_upload.original_name|escape:html}</td>
<td style="padding:9px 8px;border-bottom:1px solid rgba(255,255,255,.08)">{$qr_upload.file_size_label|escape:html}</td>
<td style="padding:9px 8px;border-bottom:1px solid rgba(255,255,255,.08)">{$qr_upload.created|escape:html}</td>
<td style="padding:9px 8px;border-bottom:1px solid rgba(255,255,255,.08);text-align:right;white-space:nowrap">
<a class="buttonLike" href="{$qr_upload.preview_url|escape:html}" target="_blank" rel="noopener" style="display:inline-block;margin-right:6px">Vorschau</a>
<a class="buttonLike" href="{$qr_upload.preview_url|escape:html}&amp;download=1" style="display:inline-block;margin-right:6px">Herunterladen</a>
<form method="post" style="display:inline" onsubmit="return confirm('Diesen QR-Upload wirklich löschen? Die QR-Nummer wird danach wieder frei.');">
<input type="hidden" name="pwg_token" value="{$PWG_TOKEN|escape:html}">
<input type="hidden" name="bratonien_tool" value="customer_qr_delete">
<input type="hidden" name="customer_qr_id" value="{$qr_upload.id}">
<button class="buttonLike" type="submit">Löschen</button>
</form>
</td>
</tr>
{/foreach}
</tbody>
</table>
{else}
<p class="bratonien-base-note">Noch keine QR-Codes hochgeladen.</p>
{/if}
</div>
<div class="bratonien-card" style="margin-top:18px;overflow-x:auto">
<h4>Persönliche Freundschaftscodes</h4>
{if $CUSTOMER_QR.friendship_codes.total > 0}
<table style="width:100%;border-collapse:collapse;min-width:760px">
<thead>
<tr>
<th style="text-align:left;padding:9px 8px;border-bottom:1px solid rgba(255,255,255,.14)">Name</th>
<th style="text-align:left;padding:9px 8px;border-bottom:1px solid rgba(255,255,255,.14)">Datei</th>
<th style="text-align:left;padding:9px 8px;border-bottom:1px solid rgba(255,255,255,.14)">Größe</th>
<th style="text-align:left;padding:9px 8px;border-bottom:1px solid rgba(255,255,255,.14)">Upload</th>
<th style="text-align:right;padding:9px 8px;border-bottom:1px solid rgba(255,255,255,.14)">Aktionen</th>
</tr>
</thead>
<tbody>
{foreach from=$CUSTOMER_QR.friendship_codes.uploads item=friendship}
<tr>
<td style="padding:9px 8px;border-bottom:1px solid rgba(255,255,255,.08)"><strong>{$friendship.name|escape:html}</strong></td>
<td style="padding:9px 8px;border-bottom:1px solid rgba(255,255,255,.08);max-width:300px;overflow-wrap:anywhere">{$friendship.original_name|escape:html}</td>
<td style="padding:9px 8px;border-bottom:1px solid rgba(255,255,255,.08)">{$friendship.file_size_label|escape:html}</td>
<td style="padding:9px 8px;border-bottom:1px solid rgba(255,255,255,.08)">{$friendship.created|escape:html}</td>
<td style="padding:9px 8px;border-bottom:1px solid rgba(255,255,255,.08);text-align:right;white-space:nowrap">
<a class="buttonLike" href="{$friendship.preview_url|escape:html}" target="_blank" rel="noopener" style="display:inline-block;margin-right:6px">Vorschau</a>
<a class="buttonLike" href="{$friendship.download_url|escape:html}" style="display:inline-block;margin-right:6px">Herunterladen</a>
<form method="post" style="display:inline" onsubmit="return confirm('Diesen Freundschaftscode wirklich löschen?');">
<input type="hidden" name="pwg_token" value="{$PWG_TOKEN|escape:html}">
<input type="hidden" name="bratonien_tool" value="friendship_code_delete">
<input type="hidden" name="friendship_code_id" value="{$friendship.id}">
<button class="buttonLike" type="submit">Löschen</button>
</form>
</td>
</tr>
{/foreach}
</tbody>
</table>
{else}
<p class="bratonien-base-note">Noch keine persönlichen Freundschaftscodes hochgeladen.</p>
{/if}
</div>
</section>

View File

@@ -1,265 +1,241 @@
<section class="bratonien-section" id="nc-connector">
<h3>NC Connector</h3>
<p class="bratonien-section__intro">Bratonien Tools verwaltet die Nextcloud-Anbindung und den regelmäßigen Piwigo-Abgleich.</p>
<p class="bratonien-section__intro">Verbindet Nextcloud per WebDAV mit Piwigo und hält die ausgewählten Bilder automatisch aktuell.</p>
{assign var=nc_system_available value=isset($NC_CONNECTOR.system)}
<div class="bratonien-grid">
<div class="bratonien-card">
<h4>Connector-Status</h4>
<h4>Status</h4>
<div class="bratonien-form-grid">
<span class="bratonien-label">Phase</span><strong>{$NC_CONNECTOR.phase|escape:html}</strong>
<span class="bratonien-label">Connector-Verbindungen</span><strong>{$NC_CONNECTOR.connection_count|escape:html}</strong>
<span class="bratonien-label">Timer aktiv</span><strong>{if $nc_system_available && $NC_CONNECTOR.system.timer_active}Ja{else}Nein{/if}</strong>
<span class="bratonien-label">Timer aktiviert</span><strong>{if $nc_system_available && $NC_CONNECTOR.system.timer_enabled}Ja{else}Nein{/if}</strong>
<span class="bratonien-label">Letzter Lauf</span><strong>{if $nc_system_available}{$NC_CONNECTOR.system.last_run_label|escape:html}{else}Nicht verfügbar{/if}</strong>
<span class="bratonien-label">Nächster Lauf</span><strong>{if $nc_system_available}{$NC_CONNECTOR.system.next_run_label|escape:html}{else}Nicht verfügbar{/if}</strong>
<span class="bratonien-label">WebDAV-Verbindungen</span><strong>{$NC_CONNECTOR.connection_count|escape:html}</strong>
<span class="bratonien-label">Automatischer Abgleich</span><strong>{if $nc_system_available && $NC_CONNECTOR.system.timer_active && $NC_CONNECTOR.system.timer_enabled}Aktiv{else}Nicht aktiv{/if}</strong>
<span class="bratonien-label">Letzter Lauf</span><strong data-nc-last-run>{if $nc_system_available}{$NC_CONNECTOR.system.last_run_label|escape:html}{else}Nicht verfügbar{/if}</strong>
<span class="bratonien-label">Nächster Lauf</span><strong data-nc-next-run>{if $nc_system_available}{$NC_CONNECTOR.system.next_run_label|escape:html}{else}Nicht verfügbar{/if}</strong>
</div>
{if $nc_system_available && $NC_CONNECTOR.system.last_run_message}
<p class="bratonien-base-note">Letztes Ergebnis: <strong>{$NC_CONNECTOR.system.last_run_message|escape:html}</strong></p>
{/if}
{if $nc_system_available && $NC_CONNECTOR.system.last_run_api_state == 'error'}
<p class="bratonien-main-cache__warning"><strong>API:</strong> {$NC_CONNECTOR.system.last_run_api_message|escape:html}</p>
{/if}
{if $nc_system_available && $NC_CONNECTOR.system.last_run_fallback_state == 'ok'}
<p class="bratonien-base-note"><strong>Fallback:</strong> erfolgreich übernommen.</p>
{elseif $nc_system_available && $NC_CONNECTOR.system.last_run_fallback_state == 'error'}
<p class="bratonien-main-cache__warning"><strong>Fallback:</strong> {$NC_CONNECTOR.system.last_run_fallback_message|escape:html}</p>
{/if}
{if $nc_system_available && $NC_CONNECTOR.system.last_run_error_detail}
<p class="bratonien-main-cache__warning"><strong>Fehler:</strong> {$NC_CONNECTOR.system.last_run_error_detail|escape:html}</p>
{/if}
{if $nc_system_available && $NC_CONNECTOR.system.last_run_message}<p class="bratonien-base-note">Letztes Ergebnis: <strong>{$NC_CONNECTOR.system.last_run_message|escape:html}</strong></p>{/if}
<form method="post" class="bratonien-actions" style="margin-top:.75rem">
<input type="hidden" name="pwg_token" value="{$PWG_TOKEN|escape:html}">
<button class="buttonLike" type="submit" name="bratonien_tool" value="nc_connector_run_now"{if $NC_CONNECTOR.connection_count < 1} disabled{/if}>Jetzt abrufen</button>
</form>
{if $nc_system_available && $NC_CONNECTOR.system.last_run_api_state == 'error'}<p class="bratonien-main-cache__warning"><strong>API:</strong> {$NC_CONNECTOR.system.last_run_api_message|escape:html}</p>{/if}
{if $nc_system_available && $NC_CONNECTOR.system.last_run_fallback_state == 'error'}<p class="bratonien-main-cache__warning"><strong>Fallback:</strong> {$NC_CONNECTOR.system.last_run_fallback_message|escape:html}</p>{/if}
{if $nc_system_available && $NC_CONNECTOR.system.last_run_error_detail}<details><summary>Technische Fehlerdetails</summary><p class="bratonien-main-cache__warning">{$NC_CONNECTOR.system.last_run_error_detail|escape:html}</p></details>{/if}
</div>
<div class="bratonien-card">
<h4>Runtime</h4>
<p class="bratonien-base-note">Neue Verbindungen verwenden direkt die Plugin-Runtime und einen eigenen State unter <code>/var/lib/bratonien-tools/nc-connector/connection-ID</code>.</p>
{if $nc_system_available && !$NC_CONNECTOR.system.legacy_runtime_exists && !$NC_CONNECTOR.system.legacy_config_exists && !$NC_CONNECTOR.system.legacy_service_exists && !$NC_CONNECTOR.system.legacy_timer_exists}
<p class="bratonien-base-note">Legacy-Bestand: <strong>vollständig entfernt</strong>.</p>
{/if}
</div>
<div class="bratonien-card" style="grid-column:1/-1">
<h4>Piwigo API bevorzugter Sync-Zugang</h4>
<p class="bratonien-base-note">Der NC Connector versucht bei jedem produktiven Lauf zuerst die Piwigo-API. Ein erfolgreich geprüfter API-Key wird verschlüsselt gespeichert. Die produktive API-Synchronisierung ist ausdrücklich an die im Plugin freigegebene Piwigo-Version gebunden. Ist diese Version nicht freigegeben oder die API nicht nutzbar, darf nur der Benutzername/Passwort-Fallback übernehmen.</p>
<form method="post">
<input type="hidden" name="pwg_token" value="{$PWG_TOKEN|escape:html}">
<div class="bratonien-form-grid">
<label class="bratonien-label" for="nc_piwigo_api_key_id">API-Schlüssel-ID</label>
<input id="nc_piwigo_api_key_id" name="nc_piwigo_api_key_id" type="text" autocomplete="off" placeholder="pkid-..." required>
<label class="bratonien-label" for="nc_piwigo_api_key_secret">API-Geheimnis</label>
<input id="nc_piwigo_api_key_secret" name="nc_piwigo_api_key_secret" type="password" autocomplete="off" required>
</div>
<div class="bratonien-actions">
<button class="buttonLike" type="submit" name="bratonien_tool" value="nc_connector_piwigo_api_test">API prüfen und speichern</button>
<button class="buttonLike bratonien-delete-button" type="submit" name="bratonien_tool" value="nc_connector_piwigo_api_delete" formnovalidate onclick="return confirm('Gespeicherte Piwigo-API-Zugangsdaten wirklich löschen?');">Gespeicherte API löschen</button>
</div>
</form>
{if isset($NC_CONNECTOR.piwigo_api_test) && $NC_CONNECTOR.piwigo_api_test}
<hr>
<h5>Prüfergebnis</h5>
<div class="bratonien-form-grid">
<span class="bratonien-label">Benutzer</span><strong>{$NC_CONNECTOR.piwigo_api_test.username|escape:html}</strong>
<span class="bratonien-label">Piwigo-Status</span><strong>{$NC_CONNECTOR.piwigo_api_test.status|escape:html}</strong>
<span class="bratonien-label">Administrator/Webmaster</span><strong>{if $NC_CONNECTOR.piwigo_api_test.admin}Ja{else}Nein{/if}</strong>
<span class="bratonien-label">Sichtbare API-Methoden</span><strong>{$NC_CONNECTOR.piwigo_api_test.method_count|escape:html}</strong>
<span class="bratonien-label">Bratonien-Sync-API</span><strong>{if $NC_CONNECTOR.piwigo_api_test.sync_api_detected}Bereit{else}Nicht bereit{/if}</strong>
</div>
<p class="bratonien-base-note"><strong>Bewertung:</strong> {$NC_CONNECTOR.piwigo_api_test.conclusion|escape:html}</p>
{/if}
</div>
<div class="bratonien-card" style="grid-column:1/-1">
<h4>Benutzername/Passwort-Fallback</h4>
<p class="bratonien-base-note">Dieser Zugang wird nur verwendet, wenn die bevorzugte API nicht genutzt werden kann. Zugangsdaten können einmalig für einen manuellen Fallback verwendet, verschlüsselt dauerhaft hinterlegt oder vollständig gelöscht werden.</p>
{if $NC_CONNECTOR.connection_count > 0}
<form method="post">
<input type="hidden" name="pwg_token" value="{$PWG_TOKEN|escape:html}">
<div class="bratonien-form-grid">
<label class="bratonien-label" for="nc_fallback_connection">Verbindung</label>
<select id="nc_fallback_connection" name="connection_id" required>
{foreach from=$NC_CONNECTOR.connections item=connection}
<option value="{$connection.id|escape:html}">{$connection.name|escape:html}</option>
{/foreach}
</select>
<label class="bratonien-label" for="nc_fallback_user">Piwigo-Benutzer</label>
<input id="nc_fallback_user" name="nc_fallback_user" type="text" autocomplete="username">
<label class="bratonien-label" for="nc_fallback_password">Piwigo-Passwort</label>
<input id="nc_fallback_password" name="nc_fallback_password" type="password" autocomplete="current-password">
</div>
<div class="bratonien-actions">
<button class="buttonLike" type="submit" name="bratonien_tool" value="nc_connector_fallback_once">Einmalig verwenden</button>
<button class="buttonLike" type="submit" name="bratonien_tool" value="nc_connector_fallback_save">Fest speichern</button>
<button class="buttonLike bratonien-delete-button" type="submit" name="bratonien_tool" value="nc_connector_fallback_delete" formnovalidate onclick="return confirm('Gespeicherten Benutzername/Passwort-Fallback wirklich löschen?');">Gespeicherten Fallback löschen</button>
</div>
</form>
{else}
<p class="bratonien-base-note">Noch keine Connector-Verbindung vorhanden.</p>
{/if}
</div>
<div class="bratonien-card" style="grid-column:1/-1">
<h4>Neue lokale Verbindung</h4>
<form method="post">
<input type="hidden" name="pwg_token" value="{$PWG_TOKEN|escape:html}">
<div class="bratonien-form-grid">
<label class="bratonien-label" for="nc_name">Name</label><input id="nc_name" name="nc_name" type="text" required>
<label class="bratonien-label" for="nc_host">PostgreSQL-Host</label><input id="nc_host" name="nc_host" type="text" required>
<label class="bratonien-label" for="nc_port">PostgreSQL-Port</label><input id="nc_port" name="nc_port" type="number" min="1" max="65535" value="5432" required>
<label class="bratonien-label" for="nc_database">Datenbank</label><input id="nc_database" name="nc_database" type="text" value="nextcloud" required>
<label class="bratonien-label" for="nc_user">Reader-Benutzer</label><input id="nc_user" name="nc_user" type="text" required>
<label class="bratonien-label" for="nc_db_password">Reader-Passwort</label><input id="nc_db_password" name="nc_db_password" type="password" autocomplete="new-password" required>
<label class="bratonien-label" for="nc_source_view">Source-View</label><input id="nc_source_view" name="nc_source_view" type="text" value="piwigo_showcase_sources" required>
<label class="bratonien-label" for="nc_activity_view">Activity-View</label><input id="nc_activity_view" name="nc_activity_view" type="text" value="piwigo_showcase_activity" required>
<label class="bratonien-label" for="nc_gallery_root">Piwigo-Galeriepfad</label><input id="nc_gallery_root" name="nc_gallery_root" type="text" placeholder="/var/www/piwigo/galleries/nextcloud" required>
<label class="bratonien-label" for="nc_piwigo_user">Piwigo-Fallback-Benutzer</label><input id="nc_piwigo_user" name="nc_piwigo_user" type="text" required>
<label class="bratonien-label" for="nc_piwigo_password">Piwigo-Fallback-Passwort</label><input id="nc_piwigo_password" name="nc_piwigo_password" type="password" autocomplete="new-password" required>
<label class="bratonien-label" for="nc_quiet_seconds">Ruhezeit</label><input id="nc_quiet_seconds" name="nc_quiet_seconds" type="number" min="0" value="120">
<label class="bratonien-label" for="nc_max_wait_seconds">Maximale Wartezeit</label><input id="nc_max_wait_seconds" name="nc_max_wait_seconds" type="number" min="60" value="900">
<label class="bratonien-label" for="nc_full_sync_seconds">Vollprüfung nach</label><input id="nc_full_sync_seconds" name="nc_full_sync_seconds" type="number" min="300" value="86400">
</div>
<p><label for="nc_storages"><strong>Storage-Zuordnungen</strong></label></p>
<p class="bratonien-base-note">Eine Zeile pro Storage: <code>storage_id | source_prefix | /lokaler/mount</code></p>
<textarea id="nc_storages" name="nc_storages" rows="4" style="width:100%" required></textarea>
<p><button class="buttonLike" type="submit" name="bratonien_tool" value="nc_connector_create_local">Verbindung anlegen</button></p>
</form>
</div>
<div class="bratonien-card" style="grid-column:1/-1">
<h4>Connector-Verbindungen</h4>
{if $NC_CONNECTOR.connection_count > 0}
<table class="table2">
<thead>
<tr>
<th>Name</th>
<th>Adapter</th>
<th>Host</th>
<th>Quelle</th>
<th>Storages</th>
<th>Status</th>
<th>Aktion</th>
</tr>
</thead>
<tbody>
{foreach from=$NC_CONNECTOR.connections item=connection}
<tr>
<td>{$connection.name|escape:html}</td>
<td>{$connection.adapter|escape:html}</td>
<td>{if $connection.host}{$connection.host|escape:html}{else}{/if}</td>
<td>{if $connection.source_view}{$connection.source_view|escape:html}{else}{/if}</td>
<td>{$connection.storage_count|escape:html}</td>
<td>{$connection.takeover_state|escape:html}{if $connection.enabled} · aktiv{/if}</td>
<td>
{if $connection.takeover_state == 'active'}
<code>php /var/www/piwigo/plugins/bratonien_tools/nc-connector-disable.php {$connection.id|escape:html}</code>
{elseif $connection.takeover_state == 'verified' && isset($connection.config.origin) && $connection.config.origin == 'native'}
<code>php /var/www/piwigo/plugins/bratonien_tools/nc-connector-install.php {$connection.id|escape:html}</code>
<form method="post" class="bratonien-actions">
<input type="hidden" name="pwg_token" value="{$PWG_TOKEN|escape:html}">
<input type="hidden" name="connection_id" value="{$connection.id|escape:html}">
<button class="buttonLike" type="submit" name="bratonien_tool" value="nc_connector_verify">Erneut prüfen</button>
</form>
{elseif $connection.takeover_state == 'ready'}
<form method="post" class="bratonien-actions">
<input type="hidden" name="pwg_token" value="{$PWG_TOKEN|escape:html}">
<input type="hidden" name="connection_id" value="{$connection.id|escape:html}">
<button class="buttonLike" type="submit" name="bratonien_tool" value="nc_connector_cancel_takeover">Vorbereitung zurücknehmen</button>
</form>
{elseif $connection.takeover_state == 'verified' && !$connection.enabled}
<form method="post" class="bratonien-actions">
<input type="hidden" name="pwg_token" value="{$PWG_TOKEN|escape:html}">
<input type="hidden" name="connection_id" value="{$connection.id|escape:html}">
<button class="buttonLike" type="submit" name="bratonien_tool" value="nc_connector_prepare_takeover">Übergabe vorbereiten</button>
</form>
{elseif $connection.adapter == 'local' && !$connection.enabled}
<form method="post" class="bratonien-actions">
<input type="hidden" name="pwg_token" value="{$PWG_TOKEN|escape:html}">
<input type="hidden" name="connection_id" value="{$connection.id|escape:html}">
<button class="buttonLike" type="submit" name="bratonien_tool" value="nc_connector_verify">Verbindung prüfen</button>
</form>
<form method="post" class="bratonien-actions">
<input type="hidden" name="pwg_token" value="{$PWG_TOKEN|escape:html}">
<input type="hidden" name="connection_id" value="{$connection.id|escape:html}">
<button class="buttonLike" type="submit" name="bratonien_tool" value="nc_connector_delete">Löschen</button>
</form>
{else}
{/if}
</td>
</tr>
{if $connection.verification_checks|@count > 0}
<tr>
<td colspan="7">
<strong>Letzte Verifikation{if $connection.verified_at} · {$connection.verified_at|escape:html}{/if}</strong>
<ul>
{foreach from=$connection.verification_checks item=check}
<li>{if $check.ok}{else}{/if} <strong>{$check.name|escape:html}:</strong> {$check.detail|escape:html}</li>
{/foreach}
</ul>
{if $connection.takeover_state == 'active'}
<p class="bratonien-base-note"><strong>Connector aktiv.</strong> State: <code>{$connection.config.state_dir|escape:html}</code></p>
{elseif $connection.takeover_state == 'verified' && isset($connection.config.origin) && $connection.config.origin == 'native'}
<p class="bratonien-base-note">Verifiziert. Der angezeigte Root-Befehl richtet Runtime-Konfiguration, State-Verzeichnis und gemeinsamen systemd-Timer ein und führt vor der Aktivierung einen Testlauf aus.</p>
{/if}
</td>
</tr>
{/if}
{if isset($connection.last_sync) && $connection.last_sync.timestamp > 0}
<tr>
<td colspan="7">
<strong>Letzter Sync · {$connection.last_sync.label|escape:html}</strong>
<p class="bratonien-base-note"><strong>Ergebnis:</strong> {$connection.last_sync.message|escape:html}</p>
{if $connection.last_sync.api_state == 'ok'}
<p class="bratonien-base-note"><strong>API:</strong> erfolgreich</p>
{elseif $connection.last_sync.api_state == 'error'}
<p class="bratonien-main-cache__warning"><strong>API fehlgeschlagen:</strong> {$connection.last_sync.api_message|escape:html}</p>
{/if}
{if $connection.last_sync.fallback_state == 'ok'}
<p class="bratonien-base-note"><strong>Fallback:</strong> erfolgreich</p>
{elseif $connection.last_sync.fallback_state == 'error'}
<p class="bratonien-main-cache__warning"><strong>Fallback fehlgeschlagen:</strong> {$connection.last_sync.fallback_message|escape:html}</p>
{/if}
{if $connection.last_sync.error_detail}
<p class="bratonien-main-cache__warning"><strong>Technischer Fehler:</strong> {$connection.last_sync.error_detail|escape:html}</p>
{/if}
</td>
</tr>
{/if}
{/foreach}
</tbody>
</table>
{else}
<p>Noch keine Verbindung in der Connector-Verwaltung.</p>
{/if}
</div>
<div class="bratonien-card">
<h4>Sync-Zustand</h4>
<div class="bratonien-form-grid">
<span class="bratonien-label">Connector-Timer</span><strong>{if $nc_system_available && $NC_CONNECTOR.system.timer_active}Aktiv{else}Nicht aktiv{/if}</strong>
<span class="bratonien-label">Letzter Lauf</span><strong>{if $nc_system_available}{$NC_CONNECTOR.system.last_run_label|escape:html}{else}Nicht verfügbar{/if}</strong>
<span class="bratonien-label">Nächster Lauf</span><strong>{if $nc_system_available}{$NC_CONNECTOR.system.next_run_label|escape:html}{else}Nicht verfügbar{/if}</strong>
<h4>Neue Verbindung</h4>
<p class="bratonien-base-note">Nextcloud wird ausschließlich per WebDAV angebunden.</p>
<div class="bratonien-actions">
<button class="buttonLike" type="button" id="bratonien-nc-wizard-open">WebDAV-Verbindung anlegen</button>
</div>
{if $nc_system_available && $NC_CONNECTOR.system.last_run_message}
<p class="bratonien-base-note"><strong>Ergebnis:</strong> {$NC_CONNECTOR.system.last_run_message|escape:html}</p>
{/if}
{if $nc_system_available && $NC_CONNECTOR.system.last_run_api_state == 'error'}
<p class="bratonien-main-cache__warning"><strong>API fehlgeschlagen:</strong> {$NC_CONNECTOR.system.last_run_api_message|escape:html}</p>
{/if}
{if $nc_system_available && $NC_CONNECTOR.system.last_run_fallback_state == 'ok'}
<p class="bratonien-base-note"><strong>Fallback:</strong> erfolgreich</p>
{elseif $nc_system_available && $NC_CONNECTOR.system.last_run_fallback_state == 'error'}
<p class="bratonien-main-cache__warning"><strong>Fallback fehlgeschlagen:</strong> {$NC_CONNECTOR.system.last_run_fallback_message|escape:html}</p>
{/if}
{if $nc_system_available && $NC_CONNECTOR.system.last_run_error_detail}
<p class="bratonien-main-cache__warning"><strong>Technischer Fehler:</strong> {$NC_CONNECTOR.system.last_run_error_detail|escape:html}</p>
{/if}
</div>
<div class="bratonien-card">
<h4>Neuinstallation</h4>
<p class="bratonien-base-note">Eine frische Installation benötigt keinen Legacy-Sync. Ablauf: Verbindung anlegen → prüfen → Root-Aktivierung ausführen. Danach arbeitet ausschließlich die Plugin-Runtime.</p>
</div>
</div>
<dialog id="bratonien-nc-wizard-dialog" style="width:min(980px,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)">
<div style="padding:1.25rem 1.5rem">
<div style="display:flex;align-items:center;justify-content:space-between;gap:1rem;margin-bottom:1rem">
<div>
<h4 style="margin:0">Neue WebDAV-Verbindung</h4>
<p class="bratonien-base-note" style="margin:.35rem 0 0"><strong>
{if $NC_CONNECTOR.wizard.step == 1}Anmeldung
{elseif $NC_CONNECTOR.wizard.step == 2 && $NC_CONNECTOR.wizard.technical_stage == 'mounts'}Verzeichnisse auswählen
{elseif $NC_CONNECTOR.wizard.step == 2 && $NC_CONNECTOR.wizard.technical_complete}Verbindung benennen
{elseif $NC_CONNECTOR.wizard.step == 3}Piwigo-API
{elseif $NC_CONNECTOR.wizard.step == 4}Abschluss
{else}Einrichtung{/if}
</strong></p>
</div>
<button class="buttonLike" type="button" id="bratonien-nc-wizard-close">Schließen</button>
</div>
{if $NC_CONNECTOR.wizard.step == 1}
<p class="bratonien-base-note">Adresse und Nextcloud-Zugang genügen. Der Assistent prüft HTTP/HTTPS und anschließend den WebDAV-Zugriff des angemeldeten Benutzers.</p>
<form method="post" data-bratonien-wizard-form>
<input type="hidden" name="pwg_token" value="{$PWG_TOKEN|escape:html}">
<div class="bratonien-form-grid">
<label class="bratonien-label" for="nc_wizard_host">Nextcloud-Adresse</label>
<input id="nc_wizard_host" name="nc_wizard_host" type="text" placeholder="cloud.example.de" value="{$NC_CONNECTOR.wizard.host_input|escape:html}" required>
<label class="bratonien-label" for="nc_wizard_user">Benutzer</label>
<input id="nc_wizard_user" name="nc_wizard_user" type="text" autocomplete="username" value="{$NC_CONNECTOR.wizard.username|escape:html}" required>
<label class="bratonien-label" for="nc_wizard_password">Passwort</label>
<input id="nc_wizard_password" name="nc_wizard_password" type="password" autocomplete="current-password" value="{$NC_CONNECTOR.wizard._password|escape:html}" required>
</div>
<p><button class="buttonLike" type="submit" name="bratonien_tool" value="nc_connector_wizard_scan">Verbinden und scannen</button></p>
</form>
{elseif $NC_CONNECTOR.wizard.step == 2}
<p class="bratonien-base-note"><strong>Nextcloud wurde gefunden.</strong> Angezeigt werden ausschließlich Verzeichnisse des angemeldeten Nextcloud-Benutzers.</p>
<div class="bratonien-form-grid">
<span class="bratonien-label">Adresse</span><strong>{$NC_CONNECTOR.wizard.base_url|escape:html}</strong>
<span class="bratonien-label">Version</span><strong>{if $NC_CONNECTOR.wizard.version}{$NC_CONNECTOR.wizard.version|escape:html}{else}Nicht gemeldet{/if}</strong>
<span class="bratonien-label">Angemeldet als</span><strong>{$NC_CONNECTOR.wizard.username|escape:html}{if $NC_CONNECTOR.wizard.display_name} · {$NC_CONNECTOR.wizard.display_name|escape:html}{/if}</strong>
</div>
{if $NC_CONNECTOR.wizard.technical_stage == 'mounts' && $NC_CONNECTOR.wizard.directory_selection_ready}
<hr>
<h5>Verzeichnisse auswählen</h5>
<div class="bratonien-form-grid">
<span class="bratonien-label">Ausgewählt</span>
<div>
{if $NC_CONNECTOR.wizard.directory_selected|@count > 0}
{foreach from=$NC_CONNECTOR.wizard.directory_selected item=selected_path}
<form method="post" class="bratonien-actions" style="margin:.25rem 0" data-bratonien-wizard-form>
<input type="hidden" name="pwg_token" value="{$PWG_TOKEN|escape:html}">
<input type="hidden" name="nc_wizard_directory_remove" value="{$selected_path|escape:html}">
<strong style="flex:1">{if $selected_path}{$selected_path|escape:html}{else}Stammverzeichnis{/if}</strong>
<button class="buttonLike" type="submit" name="bratonien_tool" value="nc_connector_wizard_directory_remove">Entfernen</button>
</form>
{/foreach}
{else}
<span class="bratonien-base-note">Noch kein Verzeichnis ausgewählt.</span>
{/if}
</div>
<span class="bratonien-label">Aktueller Ordner</span><strong>/{if $NC_CONNECTOR.wizard.directory_path}{$NC_CONNECTOR.wizard.directory_path|escape:html}{/if}</strong>
</div>
<div class="bratonien-actions" style="margin:.75rem 0">
<form method="post" data-bratonien-wizard-form>
<input type="hidden" name="pwg_token" value="{$PWG_TOKEN|escape:html}">
<button class="buttonLike" type="submit" name="bratonien_tool" value="nc_connector_wizard_directory_add">Diesen Ordner hinzufügen</button>
</form>
{if $NC_CONNECTOR.wizard.directory_path}
<form method="post" data-bratonien-wizard-form>
<input type="hidden" name="pwg_token" value="{$PWG_TOKEN|escape:html}">
<input type="hidden" name="nc_wizard_directory_path" value="{$NC_CONNECTOR.wizard.directory_parent|escape:html}">
<button class="buttonLike" type="submit" name="bratonien_tool" value="nc_connector_wizard_directory_browse">Eine Ebene hoch</button>
</form>
{/if}
</div>
<div style="margin:.75rem 0">
{if $NC_CONNECTOR.wizard.directory_children|@count > 0}
{foreach from=$NC_CONNECTOR.wizard.directory_children item=directory_name key=directory_path}
<form method="post" style="margin:.3rem 0" data-bratonien-wizard-form>
<input type="hidden" name="pwg_token" value="{$PWG_TOKEN|escape:html}">
<input type="hidden" name="nc_wizard_directory_path" value="{$directory_path|escape:html}">
<button class="buttonLike" style="width:100%;text-align:left" type="submit" name="bratonien_tool" value="nc_connector_wizard_directory_browse">📁 {$directory_name|escape:html}</button>
</form>
{/foreach}
{else}
<p class="bratonien-base-note">Keine Unterordner vorhanden.</p>
{/if}
</div>
<form method="post" data-bratonien-wizard-form>
<input type="hidden" name="pwg_token" value="{$PWG_TOKEN|escape:html}">
<p><button class="buttonLike" type="submit" name="bratonien_tool" value="nc_connector_wizard_save_mounts">Verzeichnisse übernehmen</button></p>
</form>
{elseif $NC_CONNECTOR.wizard.technical_complete}
<hr>
<h5>Verbindung benennen</h5>
<form method="post" data-bratonien-wizard-form>
<input type="hidden" name="pwg_token" value="{$PWG_TOKEN|escape:html}">
<div class="bratonien-form-grid">
<label class="bratonien-label" for="nc_wizard_connection_name">Name der Verbindung</label><input id="nc_wizard_connection_name" name="nc_wizard_connection_name" type="text" value="{$NC_CONNECTOR.wizard.connection_name|escape:html}" required>
<span class="bratonien-label">Nextcloud-Benutzer</span><strong>{$NC_CONNECTOR.wizard.username|escape:html}</strong>
</div>
<p><button class="buttonLike" type="submit" name="bratonien_tool" value="nc_connector_wizard_select_user">Weiter</button></p>
</form>
{/if}
<div class="bratonien-actions" style="margin-top:1rem">
<form method="post" data-bratonien-wizard-form><input type="hidden" name="pwg_token" value="{$PWG_TOKEN|escape:html}"><button class="buttonLike" type="submit" name="bratonien_tool" value="nc_connector_wizard_back">Zurück</button></form>
<form method="post" data-bratonien-wizard-form><input type="hidden" name="pwg_token" value="{$PWG_TOKEN|escape:html}"><button class="buttonLike" type="submit" name="bratonien_tool" value="nc_connector_wizard_reset" data-bratonien-wizard-end>Neu beginnen</button></form>
</div>
{elseif $NC_CONNECTOR.wizard.step == 3}
<p class="bratonien-base-note"><strong>WebDAV ist vorbereitet.</strong> Jetzt wird der Piwigo-Zugang dieser Verbindung geprüft.</p>
{if $NC_CONNECTOR.wizard.api_error}<p class="bratonien-main-cache__warning"><strong>API-Test fehlgeschlagen:</strong> {$NC_CONNECTOR.wizard.api_error|escape:html}</p>{/if}
<form method="post" data-bratonien-wizard-form>
<input type="hidden" name="pwg_token" value="{$PWG_TOKEN|escape:html}">
<div class="bratonien-form-grid">
<label class="bratonien-label" for="nc_wizard_api_key_id">API-Schlüssel-ID</label><input id="nc_wizard_api_key_id" name="nc_wizard_api_key_id" type="text" autocomplete="off" value="{$NC_CONNECTOR.wizard._api_key_id|escape:html}">
<label class="bratonien-label" for="nc_wizard_api_key_secret">API-Geheimnis</label><input id="nc_wizard_api_key_secret" name="nc_wizard_api_key_secret" type="password" autocomplete="off" value="{$NC_CONNECTOR.wizard._api_key_secret|escape:html}">
</div>
<div class="bratonien-actions"><button class="buttonLike" type="submit" name="bratonien_tool" value="nc_connector_wizard_api_test">API testen</button><button class="buttonLike" type="submit" name="bratonien_tool" value="nc_connector_wizard_api_skip" formnovalidate>Überspringen</button></div>
</form>
<form method="post" style="margin-top:1rem" data-bratonien-wizard-form><input type="hidden" name="pwg_token" value="{$PWG_TOKEN|escape:html}"><button class="buttonLike" type="submit" name="bratonien_tool" value="nc_connector_wizard_back">Zurück</button></form>
{elseif $NC_CONNECTOR.wizard.step == 4}
<p class="bratonien-base-note"><strong>Fast fertig.</strong> Erst der letzte Button legt die WebDAV-Verbindung an.</p>
<div class="bratonien-form-grid">
<span class="bratonien-label">Verbindung</span><strong>{$NC_CONNECTOR.wizard.connection_name|escape:html}</strong>
<span class="bratonien-label">Nextcloud</span><strong>{$NC_CONNECTOR.wizard.base_url|escape:html}</strong>
<span class="bratonien-label">Nextcloud-Benutzer</span><strong>{$NC_CONNECTOR.wizard.username|escape:html}</strong>
<span class="bratonien-label">Piwigo-API</span><strong>{if $NC_CONNECTOR.wizard.api_status == 'ok'}Erfolgreich geprüft{else}Übersprungen{/if}</strong>
</div>
<hr>
<h5>Fallback</h5>
{if $NC_CONNECTOR.wizard.api_status == 'ok'}<p class="bratonien-base-note">Optional. Wird nur verwendet, falls die API später nicht verfügbar ist.</p>{else}<p class="bratonien-main-cache__warning">Ohne API ist ein Fallback-Zugang erforderlich.</p>{/if}
<form method="post" data-bratonien-wizard-form>
<input type="hidden" name="pwg_token" value="{$PWG_TOKEN|escape:html}">
<div class="bratonien-form-grid">
<label class="bratonien-label" for="nc_wizard_fallback_user">Piwigo-Benutzer</label><input id="nc_wizard_fallback_user" name="nc_wizard_fallback_user" type="text" autocomplete="username" value="{$NC_CONNECTOR.wizard._fallback_user|escape:html}"{if $NC_CONNECTOR.wizard.api_status != 'ok'} required{/if}>
<label class="bratonien-label" for="nc_wizard_fallback_password">Piwigo-Passwort</label><input id="nc_wizard_fallback_password" name="nc_wizard_fallback_password" type="password" autocomplete="current-password" value="{$NC_CONNECTOR.wizard._fallback_password|escape:html}"{if $NC_CONNECTOR.wizard.api_status != 'ok'} required{/if}>
</div>
<div class="bratonien-actions"><button class="buttonLike" type="submit" name="bratonien_tool" value="nc_connector_wizard_finish" data-bratonien-wizard-end>Verbindung anlegen</button><button class="buttonLike" type="submit" name="bratonien_tool" value="nc_connector_wizard_reset" formnovalidate data-bratonien-wizard-end>Abbrechen</button></div>
</form>
<form method="post" style="margin-top:1rem" data-bratonien-wizard-form><input type="hidden" name="pwg_token" value="{$PWG_TOKEN|escape:html}"><button class="buttonLike" type="submit" name="bratonien_tool" value="nc_connector_wizard_back">Zurück</button></form>
{/if}
</div>
</dialog>
<div class="bratonien-card" style="margin-top:1.5rem">
<h4>Bestehende WebDAV-Verbindungen</h4>
{if $NC_CONNECTOR.connection_count > 0}
{foreach from=$NC_CONNECTOR.connections item=connection}
<details style="margin:.6rem 0">
<summary><strong>{$connection.display_name|escape:html}</strong> · aktiv{if isset($connection.last_sync) && ($connection.last_sync.state == 'error' || $connection.last_sync.state == 'warning')} · Laufzeitproblem{/if}</summary>
<div style="padding:.75rem 0">
<form method="post" class="bratonien-actions"><input type="hidden" name="pwg_token" value="{$PWG_TOKEN|escape:html}"><input type="hidden" name="connection_id" value="{$connection.id|escape:html}"><input name="connection_name" type="text" value="{$connection.name|escape:html}" required><button class="buttonLike" type="submit" name="bratonien_tool" value="nc_connector_update_name">Name speichern</button></form>
<div class="bratonien-actions" style="margin-top:.6rem">
<form method="post"><input type="hidden" name="pwg_token" value="{$PWG_TOKEN|escape:html}"><input type="hidden" name="connection_id" value="{$connection.id|escape:html}"><button class="buttonLike bratonien-delete-button" type="submit" name="bratonien_tool" value="nc_connector_delete" onclick="return confirm('WebDAV-Verbindung wirklich löschen? Die zugehörigen Piwigo-Inhalte dieser Verbindung werden entfernt; Nextcloud-Dateien bleiben unverändert.');">Löschen</button></form>
</div>
{if isset($connection.last_sync) && $connection.last_sync.timestamp > 0}
<p class="bratonien-base-note"><strong>Letzter Abgleich:</strong> {$connection.last_sync.label|escape:html} · {$connection.last_sync.message|escape:html}</p>
{if $connection.last_sync.state == 'error'}<p class="bratonien-main-cache__warning"><strong>Laufzeitfehler:</strong> {$connection.last_sync.message|escape:html}</p>{/if}
{if $connection.last_sync.state == 'warning'}<p class="bratonien-main-cache__warning"><strong>Laufzeitwarnung:</strong> {$connection.last_sync.message|escape:html}</p>{/if}
{if $connection.last_sync.api_state == 'error'}<p class="bratonien-main-cache__warning"><strong>API:</strong> {$connection.last_sync.api_message|escape:html}</p>{/if}
{if $connection.last_sync.fallback_state == 'error'}<p class="bratonien-main-cache__warning"><strong>Fallback:</strong> {$connection.last_sync.fallback_message|escape:html}</p>{/if}
{if $connection.last_sync.error_detail}<details><summary>Technische Laufzeitdetails</summary><p class="bratonien-main-cache__warning">{$connection.last_sync.error_detail|escape:html}</p></details>{/if}
{else}
<p class="bratonien-base-note"><strong>Laufzeit:</strong> Noch kein Laufstatus für diese Verbindung vorhanden.</p>
{/if}
<p class="bratonien-base-note"><strong>Nextcloud:</strong> {$connection.config.nextcloud_url|escape:html}</p>
<p class="bratonien-base-note"><strong>Nextcloud-Benutzer:</strong> {$connection.user|escape:html}</p>
<p class="bratonien-base-note"><strong>Ausgewählte Wurzeln:</strong> {$connection.storage_count|escape:html}</p>
<p class="bratonien-base-note"><strong>Piwigo-Zugang:</strong> {if $connection.config.api_enabled}eigene API{elseif $connection.fallback_stored}Fallback{else}kein Zugang gespeichert{/if}</p>
</div>
</details>
{/foreach}
{else}<p class="bratonien-base-note">Noch keine WebDAV-Verbindung vorhanden.</p>{/if}
</div>
{if $NC_CONNECTOR.connection_count > 0}
<details class="bratonien-card" style="margin-top:1.5rem"><summary>Fallback-Zugang einer Verbindung ändern</summary>
<form method="post"><input type="hidden" name="pwg_token" value="{$PWG_TOKEN|escape:html}"><div class="bratonien-form-grid"><label class="bratonien-label">Verbindung</label><select name="connection_id" required>{foreach from=$NC_CONNECTOR.connections item=connection}<option value="{$connection.id|escape:html}">{$connection.name|escape:html}</option>{/foreach}</select><label class="bratonien-label">Piwigo-Benutzer</label><input name="nc_fallback_user" type="text" autocomplete="username"><label class="bratonien-label">Piwigo-Passwort</label><input name="nc_fallback_password" type="password" autocomplete="current-password"></div><div class="bratonien-actions"><button class="buttonLike" type="submit" name="bratonien_tool" value="nc_connector_fallback_save">Fallback speichern</button><button class="buttonLike bratonien-delete-button" type="submit" name="bratonien_tool" value="nc_connector_fallback_delete" formnovalidate>Fallback löschen</button></div></form>
</details>
{/if}
{literal}
<script>
(function(){
var dialog=document.getElementById('bratonien-nc-wizard-dialog');
var openButton=document.getElementById('bratonien-nc-wizard-open');
var closeButton=document.getElementById('bratonien-nc-wizard-close');
var key='bratonienNcWizardOpen';
function openWizard(){try{sessionStorage.setItem(key,'1');}catch(e){} if(typeof dialog.showModal==='function'&&!dialog.open)dialog.showModal();else dialog.setAttribute('open','open');}
function closeWizard(){try{sessionStorage.removeItem(key);}catch(e){} if(typeof dialog.close==='function')dialog.close();else dialog.removeAttribute('open');}
if(openButton&&dialog)openButton.addEventListener('click',openWizard);
if(closeButton&&dialog)closeButton.addEventListener('click',closeWizard);
if(dialog){
dialog.addEventListener('cancel',function(){try{sessionStorage.removeItem(key);}catch(e){}});
dialog.addEventListener('click',function(e){if(e.target===dialog)closeWizard();});
dialog.querySelectorAll('form[data-bratonien-wizard-form]').forEach(function(form){form.addEventListener('submit',function(e){var s=e.submitter;try{if(s&&s.hasAttribute('data-bratonien-wizard-end'))sessionStorage.removeItem(key);else sessionStorage.setItem(key,'1');}catch(x){}});});
try{if(sessionStorage.getItem(key)==='1')openWizard();}catch(e){}
}
})();
</script>
{/literal}
</section>

View File

@@ -0,0 +1,50 @@
<div id="bratonien-webdav-warmup-card" class="bratonien-card" style="margin-top:16px;">
<h4>WebDAV-Quellenindex &amp; Cache-Warmup</h4>
<p>Bratonien Tools vergleicht den aktuellen Shadow-Tree mit einem eigenen kompakten Quellenindex. Nur neue, geänderte oder noch nicht vollständig verarbeitete Quellen werden an Piwigo übergeben. Der Piwigo-Bildcache selbst entscheidet nicht, ob eine Quelle neu ist.</p>
<p class="bratonien-main-cache__warning"><strong>Diagnose:</strong> Der Scan-Test startet synchron eine eigene PHP-CLI-Prüfung und liest ausschließlich Connector-Konfiguration, <code>webdav-map.json</code> und den Shadow-Tree. Er schreibt keinen Index, lädt keine Originale und erzeugt keine Derivate. Damit sehen wir direkt, ob der Scan-Prozess überhaupt starten kann und wie viele Shadow-Links er tatsächlich findet.</p>
<form method="post" class="bratonien-worker-settings">
<input type="hidden" name="pwg_token" value="{$PWG_TOKEN|escape:html}">
<label><input type="checkbox" name="webdav_warmup_enabled" value="1" {if $CACHE_WORKERS.webdav_warmup.enabled}checked{/if}> Automatischen WebDAV-Warmup aktivieren</label>
<label>Bilder pro Batch: <input type="number" name="webdav_warmup_batch_size" value="{$CACHE_WORKERS.webdav_warmup.batch_size}" min="1" max="50" step="1"></label>
<label>Index-Abgleich: <input type="number" name="webdav_warmup_periodic_hours" value="{$CACHE_WORKERS.webdav_warmup.periodic_hours}" min="1" max="168" step="1"> Stunden</label>
<button class="buttonLike" type="submit" name="bratonien_tool" value="image_cache_webdav_warmup_settings">Warmup-Einstellungen speichern</button>
</form>
<div class="bratonien-form-grid" style="margin-top:12px;">
<span class="bratonien-label">Änderungserkennung</span><span>Shadow-Tree ↔ eigener Quellenindex; Piwigo-Index und Cache-Dateien sind dafür nicht maßgeblich</span>
<span class="bratonien-label">Stufe 1</span><span>Von Piwigo definierte Derivate bis einschließlich 1920 px längster Kante</span>
<span class="bratonien-label">Stufe 2</span><span>Danach alle übrigen von Piwigo definierten Derivate</span>
<span class="bratonien-label">Letzter Status</span><span><strong>{$CACHE_WORKERS.webdav_warmup.status.state|default:'idle'|escape:html}</strong>{if $CACHE_WORKERS.webdav_warmup.status.message} · {$CACHE_WORKERS.webdav_warmup.status.message|escape:html}{/if}</span>
</div>
<div class="bratonien-actions">
<form method="post">
<input type="hidden" name="pwg_token" value="{$PWG_TOKEN|escape:html}">
<button class="buttonLike" type="submit" name="bratonien_tool" value="image_cache_webdav_scan_diagnostic">Scan jetzt testen</button>
</form>
<form method="post">
<input type="hidden" name="pwg_token" value="{$PWG_TOKEN|escape:html}">
<button class="buttonLike" type="submit" name="bratonien_tool" value="image_cache_webdav_warmup_manual">Quellenindex jetzt abgleichen</button>
</form>
<form method="post">
<input type="hidden" name="pwg_token" value="{$PWG_TOKEN|escape:html}">
<button class="buttonLike" type="submit" name="bratonien_tool" value="image_cache_webdav_warmup_audit">Produktive Pfade prüfen</button>
</form>
</div>
<p class="bratonien-base-note">Der Scan-Test und der Pfadaudit sind schreibgeschützt. Warmup und On-Demand verwenden denselben Bild-Lock; während der produktiven Materialisierung wird zusätzlich der Connector-Sync-Lock geteilt gehalten, damit Source- und Shadow-Tree nicht ausgetauscht werden können.</p>
</div>
{literal}
<script>
(function(){
function moveWarmupCard(){
var card=document.getElementById('bratonien-webdav-warmup-card');
var section=document.getElementById('wartung');
if(!card||!section||card.parentNode===section)return;
section.appendChild(card);
}
if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',moveWarmupCard);else moveWarmupCard();
})();
</script>
{/literal}

View File

@@ -61,7 +61,12 @@ function bratonien_tools_save_album_rule()
)));
}
return array('message'=>'Albumregel gespeichert.');
if (function_exists('bratonien_tools_presentation_refresh_enqueue'))
{
bratonien_tools_presentation_refresh_enqueue(array($category), 'album-watermark-rule-changed');
}
return array('message'=>'Albumregel gespeichert. Betroffene Vorschauen werden im Hintergrund aktualisiert.');
}
function bratonien_tools_get_category_tree()

View File

@@ -108,9 +108,10 @@ function bratonien_tools_save_watermark_profile()
throw new RuntimeException('Profilname darf nicht leer sein.');
}
$existing_profile = $id > 0 ? bratonien_tools_get_watermark_profile($id) : null;
if ($id > 0)
{
if (!bratonien_tools_get_watermark_profile($id))
if (!$existing_profile)
{
throw new RuntimeException('Wasserzeichenprofil nicht gefunden.');
}
@@ -128,7 +129,14 @@ function bratonien_tools_save_watermark_profile()
mass_inserts($table, array_keys($data), array($data));
}
return array('message'=>'Wasserzeichenprofil gespeichert.');
if ($id > 0 && function_exists('bratonien_tools_presentation_refresh_enqueue_all'))
{
bratonien_tools_presentation_refresh_enqueue_all('watermark-profile-changed');
}
return array('message'=>$id > 0
? 'Wasserzeichenprofil gespeichert. Betroffene Vorschauen werden im Hintergrund aktualisiert.'
: 'Wasserzeichenprofil gespeichert.');
}
function bratonien_tools_profile_is_referenced($id)

View File

@@ -4,15 +4,47 @@ if (!defined('PHPWG_ROOT_PATH'))
die('Hacking attempt!');
}
function bratonien_tools_default_public_watermark_profile_id()
{
if (!function_exists('bratonien_tools_create_default_watermark_profiles'))
{
return null;
}
bratonien_tools_create_default_watermark_profiles();
$table = bratonien_tools_table('watermark_profiles');
$row = pwg_db_fetch_assoc(pwg_query(
"SELECT id FROM ".$table.
" WHERE active=1 AND name='Oeffentlich' ORDER BY id ASC LIMIT 1"
));
return $row ? (int)$row['id'] : null;
}
function bratonien_tools_get_watermark_defaults()
{
$defaults = conf_get_param('bratonien_watermark_defaults', null);
$defaults = $defaults ? json_decode($defaults, true) : array();
return array_merge(array(
$defaults = array_merge(array(
'public_profile' => null,
'private_profile' => null,
), is_array($defaults) ? $defaults : array());
// Oeffentliche Alben sind standardmaessig geschuetzt. Nur eine explizite
// Albumregel (anderes Profil oder deaktiviert) darf dieses Verhalten
// ueberschreiben. Bestehende Installationen ohne gesetztes globales
// Oeffentlich-Profil werden automatisch auf das mitgelieferte Profil
// "Oeffentlich" migriert.
if (empty($defaults['public_profile']))
{
$public_profile = bratonien_tools_default_public_watermark_profile_id();
if ($public_profile)
{
$defaults['public_profile'] = $public_profile;
conf_update_param('bratonien_watermark_defaults', json_encode($defaults));
}
}
return $defaults;
}
function bratonien_tools_validate_default_profile($value)
@@ -34,12 +66,23 @@ function bratonien_tools_validate_default_profile($value)
function bratonien_tools_save_watermark_defaults()
{
$public_profile = bratonien_tools_validate_default_profile($_POST['public_profile'] ?? null);
if ($public_profile === null)
{
$public_profile = bratonien_tools_default_public_watermark_profile_id();
}
$config = array(
'public_profile' => bratonien_tools_validate_default_profile($_POST['public_profile'] ?? null),
'public_profile' => $public_profile,
'private_profile' => bratonien_tools_validate_default_profile($_POST['private_profile'] ?? null),
);
conf_update_param('bratonien_watermark_defaults', json_encode($config));
return array('message'=>'Globale Wasserzeichenregeln gespeichert.');
if (function_exists('bratonien_tools_presentation_refresh_enqueue_all'))
{
bratonien_tools_presentation_refresh_enqueue_all('global-watermark-rules-changed');
}
return array('message'=>'Globale Wasserzeichenregeln gespeichert. Oeffentliche Alben verwenden ohne abweichende Albumregel immer das Standard-Wasserzeichenprofil. Vorschauen werden im Hintergrund an die neuen Regeln angepasst.');
}

183
webdav-derivative-debug.php Normal file
View File

@@ -0,0 +1,183 @@
<?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_debug_out($status, array $data)
{
http_response_code((int)$status);
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store');
echo json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
exit;
}
global $user;
if (!isset($user['status']) || !in_array($user['status'], array('admin', 'webmaster'), true))
{
bratonien_tools_webdav_debug_out(403, array('ok'=>false, 'stage'=>'auth', 'error'=>'Nur fuer Administratoren/Webmaster.'));
}
$image_id = (int)($_GET['id'] ?? 0);
if ($image_id < 1)
{
bratonien_tools_webdav_debug_out(400, array('ok'=>false, 'stage'=>'input', 'error'=>'Bild-ID fehlt.'));
}
$debug = array(
'ok'=>false,
'image_id'=>$image_id,
'stage'=>'start',
);
$result = pwg_query('SELECT id, path, coi FROM '.IMAGES_TABLE.' WHERE id='.$image_id.' LIMIT 1');
if (!pwg_db_num_rows($result))
{
$debug['stage'] = 'image-row';
$debug['error'] = 'Bild nicht gefunden.';
bratonien_tools_webdav_debug_out(404, $debug);
}
$row = pwg_db_fetch_assoc($result);
$image_path = (string)($row['path'] ?? '');
$debug['images_path'] = $image_path;
$absolute = $image_path;
if (strpos($absolute, '/') !== 0)
{
$absolute = PHPWG_ROOT_PATH.ltrim(preg_replace('#^\./#', '', $absolute), '/');
}
$debug['absolute_path'] = $absolute;
$debug['absolute_exists'] = file_exists($absolute);
$debug['absolute_is_file'] = is_file($absolute);
$debug['absolute_is_link'] = is_link($absolute);
if (is_link($absolute))
{
$debug['link_target'] = readlink($absolute);
}
$resolved = realpath($absolute);
$debug['realpath'] = $resolved === false ? null : $resolved;
if ($resolved === false)
{
$debug['stage'] = 'realpath';
$debug['error'] = 'realpath() konnte images.path nicht aufloesen.';
bratonien_tools_webdav_debug_out(200, $debug);
}
$normalized = str_replace('\\', '/', $resolved);
$debug['normalized_realpath'] = $normalized;
$match = array();
if (!preg_match('#/nc-webdav-source/connection-([0-9]+)/root-([0-9]+)/(.*)$#', $normalized, $match))
{
$debug['stage'] = 'source-regex';
$debug['error'] = 'realpath passt nicht zum erwarteten nc-webdav-source-Schema.';
bratonien_tools_webdav_debug_out(200, $debug);
}
$connection_id = (int)$match[1];
$root_fileid = (int)$match[2];
$relative_path = trim((string)$match[3], '/');
$debug['connection_id'] = $connection_id;
$debug['root_fileid'] = $root_fileid;
$debug['relative_path'] = $relative_path;
$table = defined('BRATONIEN_TOOLS_NC_CONNECTIONS_TABLE')
? BRATONIEN_TOOLS_NC_CONNECTIONS_TABLE
: $GLOBALS['prefixeTable'].'bratonien_tools_nc_connections';
$debug['connections_table'] = $table;
$connection_result = pwg_query('SELECT id, enabled, adapter, config_json FROM `'.$table.'` WHERE id='.$connection_id.' LIMIT 1');
if (!pwg_db_num_rows($connection_result))
{
$debug['stage'] = 'connection-row';
$debug['error'] = 'Erkannte WebDAV-Verbindung existiert nicht in der Connector-Tabelle.';
bratonien_tools_webdav_debug_out(200, $debug);
}
$connection_row = pwg_db_fetch_assoc($connection_result);
$debug['connection_enabled'] = (int)($connection_row['enabled'] ?? 0);
$debug['connection_adapter'] = (string)($connection_row['adapter'] ?? '');
$config = json_decode((string)($connection_row['config_json'] ?? ''), true);
if (!is_array($config))
{
$debug['stage'] = 'config-json';
$debug['error'] = 'config_json ist kein gueltiges JSON-Objekt.';
bratonien_tools_webdav_debug_out(200, $debug);
}
$debug['source_mode'] = (string)($config['source_mode'] ?? '');
$debug['state_dir'] = (string)($config['state_dir'] ?? '');
$debug['parallel_gallery_root'] = (string)($config['parallel_gallery_root'] ?? '');
$roots = isset($config['roots']) && is_array($config['roots']) ? $config['roots'] : array();
$debug['roots'] = array();
$root_path = '';
foreach ($roots as $root)
{
$entry = array(
'fileid'=>(int)($root['fileid'] ?? 0),
'webdav_path'=>(string)($root['webdav_path'] ?? ''),
'display_name'=>(string)($root['display_name'] ?? ''),
);
$debug['roots'][] = $entry;
if ($entry['fileid'] === $root_fileid)
{
$root_path = trim($entry['webdav_path'], '/');
}
}
$debug['matched_root_path'] = $root_path;
if ($debug['source_mode'] !== 'webdav-placeholder')
{
$debug['stage'] = 'source-mode';
$debug['error'] = 'source_mode ist nicht webdav-placeholder.';
bratonien_tools_webdav_debug_out(200, $debug);
}
if ($root_path === '')
{
$debug['stage'] = 'root-match';
$debug['error'] = 'root_fileid aus dem Dateipfad kommt in config.roots nicht vor.';
bratonien_tools_webdav_debug_out(200, $debug);
}
$mapping_file = rtrim((string)($config['state_dir'] ?? ''), '/').'/webdav-map.json';
$debug['mapping_file'] = $mapping_file;
$debug['mapping_readable'] = is_readable($mapping_file);
$debug['mapping_has_resolved_key'] = false;
$debug['mapping_has_normalized_key'] = false;
$debug['mapping_entry'] = null;
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']))
{
$debug['mapping_has_resolved_key'] = array_key_exists($resolved, $mapping['files']);
$debug['mapping_has_normalized_key'] = array_key_exists($normalized, $mapping['files']);
$entry = $mapping['files'][$resolved] ?? $mapping['files'][$normalized] ?? null;
if (is_array($entry))
{
$debug['mapping_entry'] = $entry;
}
}
else
{
$debug['mapping_error'] = 'Mapping-Datei ist ungueltig oder enthaelt kein files-Objekt.';
}
}
$debug['runtime_source_info'] = bratonien_tools_webdav_image_source_info($image_id);
$debug['stage'] = $debug['runtime_source_info'] ? 'ok' : 'runtime-source-info-null';
$debug['ok'] = (bool)$debug['runtime_source_info'];
if (!$debug['ok'])
{
$debug['error'] = 'Die produktive Zuordnungsfunktion liefert trotz der obigen Zwischenergebnisse null.';
}
bratonien_tools_webdav_debug_out(200, $debug);

View File

@@ -0,0 +1,70 @@
<?php
define('PHPWG_ROOT_PATH', '../../');
include_once(PHPWG_ROOT_PATH.'include/common.inc.php');
require_once(PHPWG_ROOT_PATH.'include/derivative.inc.php');
if (!defined('BRATONIEN_TOOLS_PATH'))
{
define('BRATONIEN_TOOLS_ID', basename(__DIR__));
define('BRATONIEN_TOOLS_PATH', PHPWG_ROOT_PATH.'plugins/'.BRATONIEN_TOOLS_ID.'/');
}
require_once(BRATONIEN_TOOLS_PATH.'include/webdav_materialize_runtime.inc.php');
$image_id = (int)($_GET['id'] ?? 0);
if ($image_id < 1)
{
http_response_code(400);
header('Content-Type: text/plain; charset=utf-8');
echo 'Ungueltige Derivatanforderung.';
exit;
}
$source = bratonien_tools_webdav_materialize_source_info($image_id);
if (!$source)
{
http_response_code(404);
header('Content-Type: text/plain; charset=utf-8');
echo 'WebDAV-Bildquelle nicht gefunden.';
exit;
}
$state_dir = rtrim((string)($source['state_dir'] ?? ''), '/');
if ($state_dir === '')
{
http_response_code(503);
header('Content-Type: text/plain; charset=utf-8');
echo 'Connector-State-Verzeichnis fehlt.';
exit;
}
$lock = @fopen($state_dir.'/webdav-sync.lock', 'c');
if (!$lock)
{
http_response_code(503);
header('Content-Type: text/plain; charset=utf-8');
echo 'Connector-Sync-Lock konnte nicht geoeffnet werden.';
exit;
}
// On-Demand bleibt parallel zu anderen Bildabrufen moeglich, verhindert aber
// fuer die Dauer dieses einzelnen Derivataufrufs einen exklusiven Connector-
// Tree-Swap. Der bestehende Bild-Lock im eigentlichen Endpoint koordiniert
// weiterhin On-Demand und Warmup fuer dieselbe Bild-ID.
if (!@flock($lock, LOCK_SH))
{
fclose($lock);
http_response_code(503);
header('Content-Type: text/plain; charset=utf-8');
echo 'Connector-Sync-Schutz konnte nicht gesetzt werden.';
exit;
}
try
{
include BRATONIEN_TOOLS_PATH.'webdav-derivative.php';
}
finally
{
@flock($lock, LOCK_UN);
fclose($lock);
}

494
webdav-derivative-test.php Normal file
View File

@@ -0,0 +1,494 @@
<?php
define('PHPWG_ROOT_PATH', '../../');
include_once(PHPWG_ROOT_PATH.'include/common.inc.php');
require_once(PHPWG_ROOT_PATH.'include/derivative.inc.php');
function bratonien_tools_webdav_derivative_test_abort($status, $message)
{
http_response_code((int)$status);
header('Content-Type: text/plain; charset=utf-8');
header('Cache-Control: no-store');
echo $message;
exit;
}
function bratonien_tools_webdav_derivative_test_decrypt_secret($blob, $hex_key)
{
$hex_key = trim((string)$hex_key);
if (!preg_match('/^[a-f0-9]{64}$/', $hex_key)) return null;
$outer = base64_decode(trim((string)$blob), true);
$payload = is_string($outer) ? json_decode($outer, true) : null;
if (!is_array($payload) || (int)($payload['v'] ?? 0) !== 1) return null;
$iv = base64_decode((string)($payload['iv'] ?? ''), true);
$tag = base64_decode((string)($payload['tag'] ?? ''), true);
$cipher = base64_decode((string)($payload['data'] ?? ''), true);
if (!is_string($iv) || !is_string($tag) || !is_string($cipher)) return null;
$plain = openssl_decrypt($cipher, 'aes-256-gcm', hex2bin($hex_key), OPENSSL_RAW_DATA, $iv, $tag);
if ($plain === false) return null;
$decoded = json_decode((string)$plain, true);
return is_array($decoded) ? $decoded : null;
}
function bratonien_tools_webdav_derivative_test_quote_path($path)
{
$parts = array_values(array_filter(explode('/', trim((string)$path, '/')), 'strlen'));
return implode('/', array_map('rawurlencode', $parts));
}
function bratonien_tools_webdav_derivative_test_source_info($image_id, array $image_row)
{
$image_id = (int)$image_id;
$path = (string)($image_row['path'] ?? '');
if ($image_id < 1 || $path === '') return null;
$absolute = $path;
if (strpos($absolute, '/') !== 0)
{
$absolute = PHPWG_ROOT_PATH.ltrim(preg_replace('#^\\./#', '', $absolute), '/');
}
$resolved = realpath($absolute);
if ($resolved === false) return null;
$normalized = str_replace('\\', '/', $resolved);
if (!preg_match('#/nc-webdav-source/connection-([0-9]+)/root-([0-9]+)/(.*)$#', $normalized, $match))
{
return null;
}
$connection_id = (int)$match[1];
$root_fileid = (int)$match[2];
$relative_path = trim((string)$match[3], '/');
if ($connection_id < 1 || $root_fileid < 1 || $relative_path === '') return null;
$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 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 null;
$root_found = false;
$root_path = '';
$roots = isset($config['roots']) && is_array($config['roots']) ? $config['roots'] : array();
foreach ($roots as $root)
{
if ((int)($root['fileid'] ?? 0) === $root_fileid)
{
$root_found = true;
$root_path = trim((string)($root['webdav_path'] ?? ''), '/');
break;
}
}
if (!$root_found) return null;
$webdav_path = trim($root_path === '' ? $relative_path : $root_path.'/'.$relative_path, '/');
if ($webdav_path === '') return null;
$content_type = '';
$size = 0;
$etag = '';
$state_dir = rtrim((string)($config['state_dir'] ?? ''), '/');
if ($state_dir !== '')
{
$mapping_file = $state_dir.'/webdav-map.json';
if (is_readable($mapping_file))
{
$mapping = json_decode((string)file_get_contents($mapping_file), true);
if (is_array($mapping) && isset($mapping['files']) && is_array($mapping['files']))
{
$entry = $mapping['files'][$resolved] ?? $mapping['files'][$normalized] ?? null;
if (is_array($entry) && (string)($entry['kind'] ?? '') === 'file')
{
$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 array(
'image_id'=>$image_id,
'connection_id'=>$connection_id,
'webdav_path'=>$webdav_path,
'content_type'=>$content_type,
'size'=>$size,
'etag'=>$etag,
'coi'=>$image_row['coi'] ?? null,
);
}
function bratonien_tools_webdav_derivative_test_download(array $source, $destination, &$detail=null)
{
$detail = '';
$table = $GLOBALS['prefixeTable'].'bratonien_tools_nc_connections';
$result = pwg_query('SELECT config_json, secret_blob FROM `'.$table.'` WHERE id='.(int)$source['connection_id'].' LIMIT 1');
if (!pwg_db_num_rows($result))
{
$detail = 'WebDAV-Verbindung nicht gefunden.';
return false;
}
$row = pwg_db_fetch_assoc($result);
$config = json_decode((string)$row['config_json'], true);
if (!is_array($config))
{
$detail = 'WebDAV-Konfiguration ist ungueltig.';
return false;
}
$key_result = pwg_query("SELECT value FROM ".$GLOBALS['prefixeTable']."config WHERE param='bratonien_nc_connector_secret' LIMIT 1");
if (!pwg_db_num_rows($key_result))
{
$detail = 'Connector-Schluessel fehlt.';
return false;
}
$key_row = pwg_db_fetch_assoc($key_result);
$credentials = bratonien_tools_webdav_derivative_test_decrypt_secret((string)$row['secret_blob'], (string)$key_row['value']);
if (!is_array($credentials))
{
$detail = 'WebDAV-Zugangsdaten konnten nicht gelesen werden.';
return false;
}
$base_url = rtrim((string)($config['nextcloud_url'] ?? ''), '/');
$user = trim((string)($credentials['nextcloud_user'] ?? ''));
$password = (string)($credentials['nextcloud_password'] ?? '');
$webdav_path = trim((string)($source['webdav_path'] ?? ''), '/');
if ($base_url === '' || $user === '' || $password === '' || $webdav_path === '')
{
$detail = 'WebDAV-Bildquelle ist unvollstaendig.';
return false;
}
$fp = @fopen($destination, 'xb');
if (!$fp)
{
$detail = 'Temporaere Quelldatei konnte nicht angelegt werden.';
return false;
}
$url = $base_url.'/remote.php/dav/files/'.rawurlencode($user).'/'.bratonien_tools_webdav_derivative_test_quote_path($webdav_path);
$ch = curl_init($url);
curl_setopt_array($ch, array(
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_TIMEOUT => 180,
CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
CURLOPT_USERPWD => $user.':'.$password,
CURLOPT_RETURNTRANSFER => false,
CURLOPT_FAILONERROR => false,
CURLOPT_FILE => $fp,
CURLOPT_USERAGENT => 'Bratonien-Tools-WebDAV-Derivative-Parallel-Test',
));
$ok = curl_exec($ch);
$errno = curl_errno($ch);
$error = curl_error($ch);
$http = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
fclose($fp);
if ($ok === false || $errno !== 0 || $http < 200 || $http >= 300)
{
@unlink($destination);
$detail = 'Nextcloud-Download fehlgeschlagen (HTTP '.$http.', cURL '.$errno.($error !== '' ? ': '.$error : '').').';
return false;
}
if (!is_file($destination) || filesize($destination) < 1 || @getimagesize($destination) === false)
{
@unlink($destination);
$detail = 'Nextcloud-Datei ist kein lesbares Bild.';
return false;
}
return true;
}
function bratonien_tools_webdav_derivative_test_inner_url($derivative_path)
{
$derivative_root = PHPWG_ROOT_PATH.PWG_DERIVATIVE_DIR;
if (strpos($derivative_path, $derivative_root) !== 0) return null;
$location = ltrim(substr($derivative_path, strlen($derivative_root)), '/');
if ($location === '') return null;
$segments = array_map('rawurlencode', explode('/', $location));
return rtrim(get_absolute_root_url(), '/').'/i.php?/'.implode('/', $segments);
}
function bratonien_tools_webdav_derivative_test_call_i($url, &$response_body, &$response_type, &$response_status, &$detail=null)
{
$detail = '';
$response_body = '';
$response_type = 'application/octet-stream';
$response_status = 500;
$ch = curl_init($url);
curl_setopt_array($ch, array(
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_TIMEOUT => 180,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FAILONERROR => false,
CURLOPT_USERAGENT => 'Bratonien-Tools-Derivative-Parallel-Gate',
));
$body = curl_exec($ch);
$errno = curl_errno($ch);
$error = curl_error($ch);
$status = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
$content_type = (string)curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
curl_close($ch);
$response_status = $status;
if ($content_type !== '') $response_type = $content_type;
if (is_string($body)) $response_body = $body;
if ($body === false || $errno !== 0)
{
$detail = 'Interner i.php-Aufruf fehlgeschlagen (cURL '.$errno.($error !== '' ? ': '.$error : '').').';
return false;
}
if ($status < 200 || $status >= 400)
{
$detail = 'i.php antwortete mit HTTP '.$status.'.';
return false;
}
return true;
}
global $user;
if (!isset($user['status']) || !in_array($user['status'], array('admin', 'webmaster'), true))
{
bratonien_tools_webdav_derivative_test_abort(403, 'Dieser Test-Endpunkt ist nur fuer Administratoren verfuegbar.');
}
$metrics_requested = isset($_GET['metrics']) && (string)$_GET['metrics'] === '1';
$metrics_started_at = microtime(true);
$memory_start = memory_get_usage(true);
if (function_exists('memory_reset_peak_usage'))
{
memory_reset_peak_usage();
}
$image_id = (int)($_GET['id'] ?? 0);
if ($image_id < 1)
{
bratonien_tools_webdav_derivative_test_abort(400, 'Bild-ID fehlt.');
}
$type = trim((string)($_GET['type'] ?? IMG_THUMB));
$defined = ImageStdParams::get_defined_type_map();
if (!isset($defined[$type]))
{
bratonien_tools_webdav_derivative_test_abort(400, 'Unbekannter oder deaktivierter Derivat-Typ: '.$type);
}
$result = pwg_query('SELECT * FROM '.IMAGES_TABLE.' WHERE id='.$image_id.' LIMIT 1');
if (!pwg_db_num_rows($result))
{
bratonien_tools_webdav_derivative_test_abort(404, 'Bild nicht gefunden.');
}
$image_row = pwg_db_fetch_assoc($result);
$source = bratonien_tools_webdav_derivative_test_source_info($image_id, $image_row);
if (!$source)
{
bratonien_tools_webdav_derivative_test_abort(404, 'Keine WebDAV-Quelle fuer dieses Bild gefunden.');
}
$upload_dir = rtrim((string)($GLOBALS['conf']['upload_dir'] ?? './upload'), '/');
$test_rel_dir = $upload_dir.'/bratonien-webdav-test';
$test_root = PHPWG_ROOT_PATH.$test_rel_dir;
if (!is_dir($test_root) && !@mkdir($test_root, 0755, true))
{
bratonien_tools_webdav_derivative_test_abort(500, 'Paralleler Testbereich konnte nicht angelegt werden: '.$test_root);
}
if (!is_writable($test_root))
{
bratonien_tools_webdav_derivative_test_abort(500, 'Paralleler Testbereich ist fuer PHP nicht beschreibbar: '.$test_root);
}
$lock_path = $test_root.'/image-'.$image_id.'.lock';
$lock = @fopen($lock_path, 'c');
if (!$lock || !flock($lock, LOCK_EX))
{
if ($lock) fclose($lock);
bratonien_tools_webdav_derivative_test_abort(503, 'Paralleler Test-Lock konnte nicht gesetzt werden.');
}
$extension = strtolower(pathinfo((string)($image_row['path'] ?? ''), PATHINFO_EXTENSION));
if (!in_array($extension, array('jpg', 'jpeg', 'png', 'gif', 'webp'), true))
{
$extension = 'jpg';
}
$token = getmypid().'-'.bin2hex(random_bytes(6));
$source_filename = 'source-'.$image_id.'-'.$token.'.'.$extension;
$source_path = $test_root.'/'.$source_filename;
$source_rel = $test_rel_dir.'/'.$source_filename;
$temp_image_id = 0;
$derivative_path = '';
$cleaned = false;
$cleanup = function() use (&$cleaned, &$temp_image_id, &$derivative_path, $source_path, $lock)
{
if ($cleaned) return;
$cleaned = true;
if ($temp_image_id > 0)
{
@pwg_query('DELETE FROM '.IMAGES_TABLE.' WHERE id='.(int)$temp_image_id.' LIMIT 1');
$temp_image_id = 0;
}
if ($derivative_path !== '' && is_file($derivative_path))
{
@unlink($derivative_path);
}
if (is_file($source_path))
{
@unlink($source_path);
}
@flock($lock, LOCK_UN);
@fclose($lock);
};
register_shutdown_function($cleanup);
try
{
$detail = '';
if (!bratonien_tools_webdav_derivative_test_download($source, $source_path, $detail))
{
bratonien_tools_webdav_derivative_test_abort(502, $detail);
}
$source_bytes = (int)filesize($source_path);
$dimensions = @getimagesize($source_path);
if (!is_array($dimensions) || empty($dimensions[0]) || empty($dimensions[1]))
{
bratonien_tools_webdav_derivative_test_abort(500, 'Paralleles Original besitzt keine gueltigen Bildabmessungen.');
}
$test_row = $image_row;
unset($test_row['id']);
$test_row['path'] = $source_rel;
$test_row['file'] = $source_filename;
if (array_key_exists('width', $test_row)) $test_row['width'] = (int)$dimensions[0];
if (array_key_exists('height', $test_row)) $test_row['height'] = (int)$dimensions[1];
single_insert(IMAGES_TABLE, $test_row);
$temp_image_id = (int)pwg_db_insert_id();
if ($temp_image_id < 1)
{
bratonien_tools_webdav_derivative_test_abort(500, 'Temporaerer Piwigo-Testeintrag konnte nicht angelegt werden.');
}
$test_row['id'] = $temp_image_id;
$test_src = new SrcImage($test_row);
$derivative = new DerivativeImage($defined[$type], $test_src);
if ($derivative->same_as_source())
{
bratonien_tools_webdav_derivative_test_abort(409, 'Dieser Typ ist fuer das parallele Testbild identisch mit der Quelle.');
}
$derivative_path = $derivative->get_path();
if ($derivative_path === '')
{
bratonien_tools_webdav_derivative_test_abort(500, 'Piwigo konnte keinen Derivat-Zielpfad fuer den parallelen Test bestimmen.');
}
if (is_file($derivative_path))
{
@unlink($derivative_path);
clearstatcache(true, $derivative_path);
}
$inner_url = bratonien_tools_webdav_derivative_test_inner_url($derivative_path);
if ($inner_url === null)
{
bratonien_tools_webdav_derivative_test_abort(500, 'Piwigo-i.php-URL konnte fuer den parallelen Test nicht bestimmt werden.');
}
$body = '';
$content_type = 'application/octet-stream';
$status = 500;
if (!bratonien_tools_webdav_derivative_test_call_i($inner_url, $body, $content_type, $status, $detail))
{
bratonien_tools_webdav_derivative_test_abort(502, $detail."\n".$body);
}
clearstatcache(true, $derivative_path);
if (!is_file($derivative_path) || !is_readable($derivative_path))
{
bratonien_tools_webdav_derivative_test_abort(
500,
"i.php antwortete, aber das parallele Piwigo-Derivat wurde nicht erzeugt.\n"
.'Testquelle: '.$source_rel."\n"
.'i.php: '.$inner_url
);
}
$derivative_size = @getimagesize($derivative_path);
if (!is_array($derivative_size) || empty($derivative_size[0]) || empty($derivative_size[1]))
{
bratonien_tools_webdav_derivative_test_abort(500, 'Das von i.php erzeugte parallele Derivat ist keine lesbare Bilddatei.');
}
$generated_width = (int)$derivative_size[0];
$generated_height = (int)$derivative_size[1];
$derivative_bytes = (int)filesize($derivative_path);
$cleanup();
$elapsed_ms = round((microtime(true) - $metrics_started_at) * 1000, 2);
$memory_peak = memory_get_peak_usage(true);
$memory_delta_peak = max(0, $memory_peak - $memory_start);
if ($metrics_requested)
{
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store');
echo json_encode(array(
'source_bytes'=>$source_bytes,
'derivative_bytes'=>$derivative_bytes,
'elapsed_ms'=>$elapsed_ms,
'memory_start_bytes'=>$memory_start,
'memory_peak_bytes'=>$memory_peak,
'memory_delta_peak_bytes'=>$memory_delta_peak,
), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
exit;
}
header('X-Bratonien-WebDAV-Test: parallel-i.php-success');
header('X-Bratonien-Resource-Source-Bytes: '.$source_bytes);
header('X-Bratonien-Resource-Derivative-Bytes: '.$derivative_bytes);
header('X-Bratonien-Resource-Elapsed-Ms: '.$elapsed_ms);
header('X-Bratonien-Resource-Memory-Start-Bytes: '.$memory_start);
header('X-Bratonien-Resource-Memory-Peak-Bytes: '.$memory_peak);
header('X-Bratonien-Resource-Memory-Delta-Peak-Bytes: '.$memory_delta_peak);
header('X-Bratonien-WebDAV-Test-Size: '.$generated_width.'x'.$generated_height);
header('Content-Type: '.$content_type);
header('Content-Length: '.strlen($body));
header('Cache-Control: no-store');
http_response_code($status);
echo $body;
}
finally
{
$cleanup();
}

560
webdav-derivative.php Normal file
View File

@@ -0,0 +1,560 @@
<?php
define('PHPWG_ROOT_PATH', '../../');
include_once(PHPWG_ROOT_PATH.'include/common.inc.php');
require_once(PHPWG_ROOT_PATH.'include/derivative.inc.php');
if (!defined('BRATONIEN_TOOLS_PATH'))
{
define('BRATONIEN_TOOLS_ID', basename(__DIR__));
define('BRATONIEN_TOOLS_PATH', PHPWG_ROOT_PATH.'plugins/'.BRATONIEN_TOOLS_ID.'/');
}
require_once(BRATONIEN_TOOLS_PATH.'include/webdav_materialize_runtime.inc.php');
function bratonien_tools_webdav_derivative_debug($request_id, $event, array $fields=array())
{
$parts = array('[BRAT-WD '.$request_id.']', $event);
foreach ($fields as $key => $value)
{
if (is_bool($value)) $value = $value ? '1' : '0';
elseif ($value === null) $value = 'NULL';
elseif (is_array($value) || is_object($value)) $value = json_encode($value);
$parts[] = $key.'='.str_replace(array("\r", "\n"), array('\\r', '\\n'), (string)$value);
}
error_log(implode(' ', $parts));
}
function bratonien_tools_webdav_derivative_abort($status, $message)
{
http_response_code((int)$status);
header('Content-Type: text/plain; charset=utf-8');
header('Cache-Control: no-store');
echo $message;
exit;
}
function bratonien_tools_webdav_derivative_send($target_path, $after_url='')
{
if (isset($_GET['ajaxload']) && (string)$_GET['ajaxload'] === 'true')
{
if ($after_url === '') bratonien_tools_webdav_derivative_abort(400, 'Lazyload-Ziel fehlt.');
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store');
echo json_encode(array('url'=>$after_url), JSON_UNESCAPED_SLASHES);
exit;
}
header('Content-Type: '.(function_exists('get_mimetype') ? get_mimetype($target_path) : 'image/jpeg'));
readfile($target_path);
exit;
}
function bratonien_tools_webdav_derivative_decrypt_secret($blob, $hex_key)
{
$hex_key = trim((string)$hex_key);
if (!preg_match('/^[a-f0-9]{64}$/', $hex_key)) return null;
$outer = base64_decode(trim((string)$blob), true);
$payload = is_string($outer) ? json_decode($outer, true) : null;
if (!is_array($payload) || (int)($payload['v'] ?? 0) !== 1) return null;
$iv = base64_decode((string)($payload['iv'] ?? ''), true);
$tag = base64_decode((string)($payload['tag'] ?? ''), true);
$cipher = base64_decode((string)($payload['data'] ?? ''), true);
if (!is_string($iv) || !is_string($tag) || !is_string($cipher)) return null;
$plain = openssl_decrypt($cipher, 'aes-256-gcm', hex2bin($hex_key), OPENSSL_RAW_DATA, $iv, $tag);
if ($plain === false) return null;
$decoded = json_decode((string)$plain, true);
return is_array($decoded) ? $decoded : null;
}
function bratonien_tools_webdav_derivative_quote_path($path)
{
$parts = array_values(array_filter(explode('/', trim((string)$path, '/')), 'strlen'));
return implode('/', array_map('rawurlencode', $parts));
}
function bratonien_tools_webdav_derivative_connection(array $source, &$detail=null)
{
$detail = '';
$table = $GLOBALS['prefixeTable'].'bratonien_tools_nc_connections';
$result = pwg_query('SELECT config_json, secret_blob FROM `'.$table.'` WHERE id='.(int)$source['connection_id'].' LIMIT 1');
if (!pwg_db_num_rows($result)) { $detail = 'WebDAV-Verbindung nicht gefunden.'; return null; }
$row = pwg_db_fetch_assoc($result);
$config = json_decode((string)$row['config_json'], true);
if (!is_array($config)) { $detail = 'WebDAV-Konfiguration ist ungueltig.'; return null; }
$key_result = pwg_query("SELECT value FROM ".$GLOBALS['prefixeTable']."config WHERE param='bratonien_nc_connector_secret' LIMIT 1");
if (!pwg_db_num_rows($key_result)) { $detail = 'Connector-Schluessel fehlt.'; return null; }
$key_row = pwg_db_fetch_assoc($key_result);
$credentials = bratonien_tools_webdav_derivative_decrypt_secret((string)$row['secret_blob'], (string)$key_row['value']);
if (!is_array($credentials)) { $detail = 'WebDAV-Zugangsdaten konnten nicht gelesen werden.'; return null; }
$base_url = rtrim((string)($config['nextcloud_url'] ?? ''), '/');
$user = trim((string)($credentials['nextcloud_user'] ?? ''));
$password = (string)($credentials['nextcloud_password'] ?? '');
if ($base_url === '' || $user === '' || $password === '') { $detail = 'WebDAV-Verbindung ist unvollstaendig.'; return null; }
return array('base_url'=>$base_url, 'user'=>$user, 'password'=>$password);
}
function bratonien_tools_webdav_derivative_download_url($url, array $connection, $destination, &$detail=null)
{
$detail = '';
$fp = @fopen($destination, 'xb');
if (!$fp) { $detail = 'Temporaere Quelldatei konnte nicht angelegt werden.'; return false; }
$ch = curl_init($url);
curl_setopt_array($ch, array(
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_TIMEOUT => 180,
CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
CURLOPT_USERPWD => $connection['user'].':'.$connection['password'],
CURLOPT_RETURNTRANSFER => false,
CURLOPT_FAILONERROR => false,
CURLOPT_FILE => $fp,
CURLOPT_USERAGENT => 'Bratonien-Tools-WebDAV-Materialize',
));
$ok = curl_exec($ch);
$errno = curl_errno($ch);
$error = curl_error($ch);
$http = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
fclose($fp);
if ($ok === false || $errno !== 0 || $http < 200 || $http >= 300)
{
@unlink($destination);
$detail = 'Nextcloud-Download fehlgeschlagen (HTTP '.$http.', cURL '.$errno.($error !== '' ? ': '.$error : '').').';
return false;
}
if (!is_file($destination) || filesize($destination) < 1 || @getimagesize($destination) === false)
{
@unlink($destination);
$detail = 'Nextcloud-Datei ist kein lesbares Bild.';
return false;
}
return true;
}
function bratonien_tools_webdav_derivative_download(array $source, array $connection, $destination, &$detail=null)
{
$webdav_path = trim((string)($source['webdav_path'] ?? ''), '/');
if ($webdav_path === '') { $detail = 'WebDAV-Bildquelle ist unvollstaendig.'; return false; }
$url = $connection['base_url'].'/remote.php/dav/files/'.rawurlencode($connection['user']).'/'.bratonien_tools_webdav_derivative_quote_path($webdav_path);
return bratonien_tools_webdav_derivative_download_url($url, $connection, $destination, $detail);
}
function bratonien_tools_webdav_derivative_preview_plan($variant, array $derivative_size, array $source, array $image_row)
{
if ($variant !== 'custom:s9999x250' && $variant !== 'standard:square') return null;
if ((int)($source['fileid'] ?? 0) < 1) return null;
if ((int)($source['width'] ?? 0) < 1 || (int)($source['height'] ?? 0) < 1) return null;
if ((int)($image_row['rotation'] ?? 0) !== 0) return null;
$target_width = (int)($derivative_size[0] ?? 0);
$target_height = (int)($derivative_size[1] ?? 0);
if ($target_width < 1 || $target_height < 1 || max($target_width, $target_height) > 800) return null;
$source_width = (int)$source['width'];
$source_height = (int)$source['height'];
$required_width = $target_width * 2;
$required_height = $target_height * 2;
$scale = max($required_width / $source_width, $required_height / $source_height);
$preview_width = max(32, (int)ceil($source_width * $scale));
$preview_height = max(32, (int)ceil($source_height * $scale));
if (max($preview_width, $preview_height) > 1600) return null;
return array(
'fileid'=>(int)$source['fileid'],
'width'=>$preview_width,
'height'=>$preview_height,
);
}
function bratonien_tools_webdav_derivative_download_preview(array $plan, array $connection, $destination, &$detail=null)
{
$query = http_build_query(array(
'fileId'=>(int)$plan['fileid'],
'x'=>(int)$plan['width'],
'y'=>(int)$plan['height'],
'a'=>'true',
'forceIcon'=>'false',
'mode'=>'fill',
'mimeFallback'=>'false',
), '', '&', PHP_QUERY_RFC3986);
$url = $connection['base_url'].'/index.php/core/preview?'.$query;
return bratonien_tools_webdav_derivative_download_url($url, $connection, $destination, $detail);
}
function bratonien_tools_webdav_derivative_make_dir($dir)
{
global $conf;
if (!is_dir($dir))
{
$mode = isset($conf['chmod_value']) ? (int)$conf['chmod_value'] : 0755;
$umask = umask(0);
$ok = @mkdir($dir, $mode, true);
umask($umask);
if (!$ok && !is_dir($dir)) return false;
}
if (!is_writable($dir)) return false;
$index = rtrim($dir, '/').'/index.htm';
if (!file_exists($index)) @file_put_contents($index, 'Not allowed!');
return true;
}
function bratonien_tools_webdav_derivative_generate($source_path, $target_path, $params, array $image_row, &$detail=null)
{
global $conf;
$detail = '';
include_once(PHPWG_ROOT_PATH.'admin/include/image.class.php');
if (!is_object($params)) { $detail = 'Piwigo-Derivatparameter fehlen.'; return false; }
if (!is_file($source_path) || !is_readable($source_path)) { $detail = 'Materialisierte Bildquelle ist nicht lesbar.'; return false; }
if (!bratonien_tools_webdav_derivative_make_dir(dirname($target_path))) { $detail = 'Piwigo-Derivatverzeichnis konnte nicht angelegt werden.'; return false; }
$rotation_angle = isset($image_row['rotation'])
? pwg_image::get_rotation_angle_from_code($image_row['rotation'])
: pwg_image::get_rotation_angle($source_path);
$coi = $image_row['coi'] ?? null;
if (($params->type ?? '') === IMG_CUSTOM)
{
$defined = ImageStdParams::get_defined_type_map();
if (count($defined) > 0)
{
$sharpen = 0;
foreach ($defined as $std_params) $sharpen += $std_params->sharpen;
$params->sharpen = round($sharpen / count($defined));
}
}
$image = null;
$wm_image = null;
try
{
$image = new pwg_image($source_path);
$changes = 0;
if (0 != $rotation_angle)
{
$image->rotate($rotation_angle);
$changes++;
}
$o_size = $d_size = array($image->get_width(), $image->get_height());
$crop_rect = null;
$scaled_size = null;
$params->sizing->compute($o_size, $coi, $crop_rect, $scaled_size);
if ($crop_rect)
{
$image->crop($crop_rect->width(), $crop_rect->height(), $crop_rect->l, $crop_rect->t);
$changes++;
}
if ($scaled_size)
{
$image->resize($scaled_size[0], $scaled_size[1]);
$d_size = $scaled_size;
$changes++;
}
if ($params->sharpen)
{
$changes += $image->sharpen($params->sharpen);
}
if ($params->will_watermark($d_size))
{
$wm = ImageStdParams::get_watermark();
$wm_image = new pwg_image(PHPWG_ROOT_PATH.$wm->file);
$wm_size = array($wm_image->get_width(), $wm_image->get_height());
if ($d_size[0] < $wm_size[0] || $d_size[1] < $wm_size[1])
{
$wm_scaling_params = SizingParams::classic($d_size[0], $d_size[1]);
$tmp = null;
$wm_scaled_size = null;
$wm_scaling_params->compute($wm_size, null, $tmp, $wm_scaled_size);
$wm_size = $wm_scaled_size;
$wm_image->resize($wm_scaled_size[0], $wm_scaled_size[1]);
}
$x = round(($wm->xpos / 100) * ($d_size[0] - $wm_size[0]));
$y = round(($wm->ypos / 100) * ($d_size[1] - $wm_size[1]));
if ($image->compose($wm_image, $x, $y, $wm->opacity))
{
$changes++;
if ($wm->xrepeat || $wm->yrepeat)
{
$xpad = $wm_size[0] + max(30, round($wm_size[0] / 4));
$ypad = $wm_size[1] + max(30, 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] < $d_size[0] && $y2 >= 0 && $y2 + $wm_size[1] < $d_size[1])
{
if (!$image->compose($wm_image, $x2, $y2, $wm->opacity)) break;
}
}
}
}
}
$wm_image->destroy();
$wm_image = null;
}
if (!$changes)
{
$detail = 'Piwigo-Derivat benoetigt keine Bildaenderung.';
return false;
}
if ($d_size[0] * $d_size[1] < ($conf['derivatives_strip_metadata_threshold'] ?? PHP_INT_MAX))
{
$image->strip();
}
$image->write($target_path);
@chmod($target_path, 0644);
clearstatcache(true, $target_path);
if (!is_file($target_path) || !is_readable($target_path) || @getimagesize($target_path) === false)
{
$detail = 'Piwigo hat kein gueltiges finales Derivat erzeugt.';
return false;
}
return true;
}
catch (Throwable $e)
{
$detail = 'Piwigo-Derivaterzeugung fehlgeschlagen: '.$e->getMessage();
return false;
}
finally
{
if ($wm_image) $wm_image->destroy();
if ($image) $image->destroy();
}
}
$request_id = substr(bin2hex(random_bytes(8)), 0, 8);
$image_id = (int)($_GET['id'] ?? 0);
$variant = trim((string)($_GET['variant'] ?? ''));
$after_url = '';
if ($image_id < 1 || $variant === '') bratonien_tools_webdav_derivative_abort(400, 'Ungueltige Derivatanforderung.');
bratonien_tools_webdav_derivative_debug($request_id, 'start', array('image_id'=>$image_id, 'variant'=>$variant));
if (!empty($_GET['after']))
{
$raw_after = strtr((string)$_GET['after'], '-_', '+/');
$padding = strlen($raw_after) % 4;
if ($padding) $raw_after .= str_repeat('=', 4 - $padding);
$decoded_after = base64_decode($raw_after, true);
if (is_string($decoded_after)) $after_url = $decoded_after;
}
if ($after_url !== '')
{
$expected = bratonien_tools_webdav_materialize_after_signature($image_id, $variant, $after_url);
if (!hash_equals($expected, (string)($_GET['sig'] ?? ''))) bratonien_tools_webdav_derivative_abort(403, 'Ungueltige Derivatsignatur.');
}
$result = pwg_query('SELECT id, path, width, height, rotation, coi FROM '.IMAGES_TABLE.' WHERE id='.$image_id.' LIMIT 1');
if (!pwg_db_num_rows($result)) bratonien_tools_webdav_derivative_abort(404, 'Bild nicht gefunden.');
$image_row = pwg_db_fetch_assoc($result);
if (function_exists('get_sql_condition_FandF'))
{
$forbidden = get_sql_condition_FandF(array('visible_images'=>'id'), ' AND');
if ($forbidden !== '')
{
$visible = pwg_query('SELECT id FROM '.IMAGES_TABLE.' WHERE id='.$image_id.$forbidden.' LIMIT 1');
if (!pwg_db_num_rows($visible)) bratonien_tools_webdav_derivative_abort(403, 'Kein Zugriff auf das Bild.');
}
}
$source = bratonien_tools_webdav_materialize_source_info($image_id);
if (!$source) bratonien_tools_webdav_derivative_abort(404, 'WebDAV-Bildquelle nicht gefunden.');
bratonien_tools_webdav_derivative_debug($request_id, 'source_resolved', array(
'connection_id'=>$source['connection_id'],
'root_fileid'=>$source['root_fileid'],
'fileid'=>$source['fileid'] ?? 0,
'webdav_path'=>$source['webdav_path'],
));
$params = bratonien_tools_webdav_materialize_params_from_variant($variant);
if (!$params) bratonien_tools_webdav_derivative_abort(400, 'Unbekannte Derivatvariante.');
$src_image = new SrcImage($image_row);
$real_derivative = new DerivativeImage($params, $src_image);
$target_path = $real_derivative->get_path();
$derivative_size = $real_derivative->get_size();
if ($target_path !== '' && is_file($target_path) && is_readable($target_path))
{
bratonien_tools_webdav_derivative_debug($request_id, 'target_exists', array('target'=>$target_path));
bratonien_tools_webdav_derivative_send($target_path, $after_url);
}
$source_logical_path = (string)$image_row['path'];
if (strpos($source_logical_path, '/') !== 0)
{
$source_logical_path = PHPWG_ROOT_PATH.ltrim(preg_replace('#^\./#', '', $source_logical_path), '/');
}
$lock_dir = PHPWG_ROOT_PATH.'upload/bratonien-webdav-materialize';
if (!is_dir($lock_dir)) @mkdir($lock_dir, 0755, true);
$lock_path = $lock_dir.'/image-'.$image_id.'.lock';
$lock_handle = fopen($lock_path, 'c');
if (!$lock_handle) bratonien_tools_webdav_derivative_abort(500, 'Derivat-Lock konnte nicht geoeffnet werden.');
bratonien_tools_webdav_derivative_debug($request_id, 'waiting_lock', array('lock'=>$lock_path, 'is_link'=>is_link($source_logical_path)));
flock($lock_handle, LOCK_EX);
bratonien_tools_webdav_derivative_debug($request_id, 'lock_acquired', array('is_link'=>is_link($source_logical_path)));
clearstatcache(true, $target_path);
if ($target_path !== '' && is_file($target_path) && is_readable($target_path))
{
bratonien_tools_webdav_derivative_debug($request_id, 'target_created_while_waiting', array('target'=>$target_path));
flock($lock_handle, LOCK_UN);
fclose($lock_handle);
bratonien_tools_webdav_derivative_send($target_path, $after_url);
}
$detail = '';
$connection = bratonien_tools_webdav_derivative_connection($source, $detail);
if (!$connection)
{
flock($lock_handle, LOCK_UN);
fclose($lock_handle);
bratonien_tools_webdav_derivative_abort(502, $detail !== '' ? $detail : 'WebDAV-Verbindung konnte nicht geladen werden.');
}
$temp_dir = $lock_dir.'/tmp';
if (!is_dir($temp_dir)) @mkdir($temp_dir, 0755, true);
$temp_source = $temp_dir.'/source-'.$image_id.'-'.$request_id.'.img';
$source_mode = 'original';
$preview_plan = bratonien_tools_webdav_derivative_preview_plan($variant, $derivative_size, $source, $image_row);
if ($preview_plan)
{
bratonien_tools_webdav_derivative_debug($request_id, 'preview_start', array(
'fileid'=>$preview_plan['fileid'],
'width'=>$preview_plan['width'],
'height'=>$preview_plan['height'],
));
$download_start = microtime(true);
if (bratonien_tools_webdav_derivative_download_preview($preview_plan, $connection, $temp_source, $detail))
{
$source_mode = 'preview';
bratonien_tools_webdav_derivative_debug($request_id, 'download_done', array(
'mode'=>$source_mode,
'ms'=>round((microtime(true) - $download_start) * 1000, 1),
'bytes'=>filesize($temp_source),
));
}
else
{
bratonien_tools_webdav_derivative_debug($request_id, 'preview_failed', array('detail'=>$detail));
$detail = '';
}
}
if ($source_mode !== 'preview')
{
@unlink($temp_source);
$download_start = microtime(true);
if (!bratonien_tools_webdav_derivative_download($source, $connection, $temp_source, $detail))
{
flock($lock_handle, LOCK_UN);
fclose($lock_handle);
bratonien_tools_webdav_derivative_abort(502, $detail !== '' ? $detail : 'WebDAV-Original konnte nicht geladen werden.');
}
bratonien_tools_webdav_derivative_debug($request_id, 'download_done', array(
'mode'=>'original',
'ms'=>round((microtime(true) - $download_start) * 1000, 1),
'bytes'=>filesize($temp_source),
));
}
$source_path = realpath($source_logical_path);
if ($source_path === false || !is_file($source_path))
{
@unlink($temp_source);
flock($lock_handle, LOCK_UN);
fclose($lock_handle);
bratonien_tools_webdav_derivative_abort(500, 'Physischer Platzhalter konnte nicht aufgeloest werden.');
}
$placeholder_backup = $source_path.'.bratonien-placeholder-'.$request_id;
$staging_path = $source_logical_path.'.bratonien-source-'.$request_id;
@unlink($placeholder_backup);
@unlink($staging_path);
if (!@copy($temp_source, $staging_path))
{
@unlink($temp_source);
flock($lock_handle, LOCK_UN);
fclose($lock_handle);
bratonien_tools_webdav_derivative_abort(500, 'Temporaere Bildquelle konnte nicht bereitgestellt werden.');
}
$swapped = false;
try
{
bratonien_tools_webdav_derivative_debug($request_id, 'swap_begin', array('placeholder'=>$source_path, 'mode'=>$source_mode));
if (!@rename($source_path, $placeholder_backup)) throw new RuntimeException('Platzhalter konnte nicht gesichert werden.');
if (!@rename($staging_path, $source_path))
{
@rename($placeholder_backup, $source_path);
throw new RuntimeException('Temporaere Bildquelle konnte nicht eingesetzt werden.');
}
$swapped = true;
bratonien_tools_webdav_derivative_debug($request_id, 'swapped', array('is_link'=>is_link($source_logical_path), 'mode'=>$source_mode));
$generate_start = microtime(true);
bratonien_tools_webdav_derivative_debug($request_id, 'generate_start', array('target'=>$target_path, 'mode'=>$source_mode));
$ok = bratonien_tools_webdav_derivative_generate($source_path, $target_path, $params, $image_row, $detail);
bratonien_tools_webdav_derivative_debug($request_id, 'generate_done', array(
'ok'=>$ok,
'mode'=>$source_mode,
'ms'=>round((microtime(true) - $generate_start) * 1000, 1),
'detail'=>$detail,
));
if (!$ok) throw new RuntimeException($detail !== '' ? $detail : 'Piwigo-Derivat konnte nicht erzeugt werden.');
}
catch (Throwable $e)
{
if ($swapped)
{
@unlink($source_path);
@rename($placeholder_backup, $source_path);
}
else
{
@unlink($staging_path);
}
@unlink($temp_source);
flock($lock_handle, LOCK_UN);
fclose($lock_handle);
bratonien_tools_webdav_derivative_abort(500, $e->getMessage());
}
@unlink($source_path);
@rename($placeholder_backup, $source_path);
@unlink($temp_source);
bratonien_tools_webdav_derivative_debug($request_id, 'restored', array('is_link'=>is_link($source_logical_path)));
flock($lock_handle, LOCK_UN);
fclose($lock_handle);
if (!is_file($target_path) || !is_readable($target_path)) bratonien_tools_webdav_derivative_abort(500, 'Erzeugtes Derivat fehlt.');
$final_size = @getimagesize($target_path);
bratonien_tools_webdav_derivative_debug($request_id, 'serve', array(
'target'=>$target_path,
'width'=>(int)($final_size[0] ?? 0),
'height'=>(int)($final_size[1] ?? 0),
'mode'=>$source_mode,
));
bratonien_tools_webdav_derivative_send($target_path, $after_url);

296
webdav-download-test.php Normal file
View File

@@ -0,0 +1,296 @@
<?php
define('PHPWG_ROOT_PATH', '../../');
include_once(PHPWG_ROOT_PATH.'include/common.inc.php');
function bratonien_tools_webdav_download_test_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_download_test_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_download_test_quote_path($path)
{
$parts = array_values(array_filter(explode('/', trim((string)$path, '/')), 'strlen'));
return implode('/', array_map('rawurlencode', $parts));
}
function bratonien_tools_webdav_download_test_source_info($image_id, array $image_row)
{
$path = (string)($image_row['path'] ?? '');
if ($image_id < 1 || $path === '') return null;
$absolute = $path;
if (strpos($absolute, '/') !== 0)
{
$absolute = PHPWG_ROOT_PATH.ltrim(preg_replace('#^\\./#', '', $absolute), '/');
}
$resolved = realpath($absolute);
if ($resolved === false) return null;
$normalized = str_replace('\\', '/', $resolved);
if (!preg_match('#/nc-webdav-source/connection-([0-9]+)/root-([0-9]+)/(.*)$#', $normalized, $match))
{
return null;
}
$connection_id = (int)$match[1];
$root_fileid = (int)$match[2];
$relative_path = trim((string)$match[3], '/');
if ($connection_id < 1 || $root_fileid < 1 || $relative_path === '') return null;
$table = $GLOBALS['prefixeTable'].'bratonien_tools_nc_connections';
$result = pwg_query('SELECT config_json FROM `'.$table.'` WHERE id='.$connection_id.' LIMIT 1');
if (!pwg_db_num_rows($result)) return null;
$row = pwg_db_fetch_assoc($result);
$config = json_decode((string)$row['config_json'], true);
if (!is_array($config) || (string)($config['source_mode'] ?? '') !== 'webdav-placeholder') return null;
$root_found = false;
$root_path = '';
foreach ((array)($config['roots'] ?? array()) as $root)
{
if ((int)($root['fileid'] ?? 0) === $root_fileid)
{
$root_found = true;
$root_path = trim((string)($root['webdav_path'] ?? ''), '/');
break;
}
}
if (!$root_found) return null;
$webdav_path = trim($root_path === '' ? $relative_path : $root_path.'/'.$relative_path, '/');
if ($webdav_path === '') return null;
$size = 0;
$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), '/');
$size = (int)($entry['size'] ?? 0);
}
}
}
}
return array(
'connection_id'=>$connection_id,
'webdav_path'=>$webdav_path,
'size'=>$size,
);
}
function bratonien_tools_webdav_download_test_connection(array $source)
{
$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)) return null;
$row = pwg_db_fetch_assoc($result);
$config = json_decode((string)$row['config_json'], true);
if (!is_array($config)) return null;
$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)) return null;
$key_row = pwg_db_fetch_assoc($key_result);
$credentials = bratonien_tools_webdav_download_test_decrypt_secret((string)$row['secret_blob'], (string)$key_row['value']);
if (!is_array($credentials)) return null;
$base_url = rtrim((string)($config['nextcloud_url'] ?? ''), '/');
$user = trim((string)($credentials['nextcloud_user'] ?? ''));
$password = (string)($credentials['nextcloud_password'] ?? '');
if ($base_url === '' || $user === '' || $password === '') return null;
return array('base_url'=>$base_url, 'user'=>$user, 'password'=>$password);
}
global $user;
if (!isset($user['status']) || !in_array($user['status'], array('admin', 'webmaster'), true))
{
bratonien_tools_webdav_download_test_abort(403, 'Dieser Test-Endpunkt ist nur fuer Administratoren verfuegbar.');
}
$image_id = (int)($_GET['id'] ?? 0);
$parallel = (int)($_GET['parallel'] ?? 1);
if ($image_id < 1)
{
bratonien_tools_webdav_download_test_abort(400, 'Bild-ID fehlt.');
}
if ($parallel < 1 || $parallel > 20)
{
bratonien_tools_webdav_download_test_abort(400, 'parallel muss zwischen 1 und 20 liegen.');
}
$result = pwg_query('SELECT * FROM '.IMAGES_TABLE.' WHERE id='.$image_id.' LIMIT 1');
if (!pwg_db_num_rows($result))
{
bratonien_tools_webdav_download_test_abort(404, 'Bild nicht gefunden.');
}
$image_row = pwg_db_fetch_assoc($result);
$source = bratonien_tools_webdav_download_test_source_info($image_id, $image_row);
if (!$source)
{
bratonien_tools_webdav_download_test_abort(404, 'Keine WebDAV-Quelle fuer dieses Bild gefunden.');
}
$connection = bratonien_tools_webdav_download_test_connection($source);
if (!$connection)
{
bratonien_tools_webdav_download_test_abort(500, 'WebDAV-Verbindung konnte nicht geladen werden.');
}
$upload_dir = rtrim((string)($GLOBALS['conf']['upload_dir'] ?? './upload'), '/');
$test_rel_dir = $upload_dir.'/bratonien-webdav-download-test';
$test_root = PHPWG_ROOT_PATH.$test_rel_dir;
if (!is_dir($test_root) && !@mkdir($test_root, 0755, true))
{
bratonien_tools_webdav_download_test_abort(500, 'Download-Testbereich konnte nicht angelegt werden: '.$test_root);
}
if (!is_writable($test_root))
{
bratonien_tools_webdav_download_test_abort(500, 'Download-Testbereich ist fuer PHP nicht beschreibbar: '.$test_root);
}
$url = $connection['base_url'].'/remote.php/dav/files/'.rawurlencode($connection['user']).'/'.bratonien_tools_webdav_download_test_quote_path($source['webdav_path']);
$token = getmypid().'-'.bin2hex(random_bytes(6));
$multi = curl_multi_init();
$items = array();
for ($i = 0; $i < $parallel; $i++)
{
$path = $test_root.'/download-'.$image_id.'-'.$token.'-'.$i.'.tmp';
$fp = @fopen($path, 'xb');
if (!$fp)
{
foreach ($items as $item)
{
@fclose($item['fp']);
@unlink($item['path']);
curl_multi_remove_handle($multi, $item['ch']);
curl_close($item['ch']);
}
curl_multi_close($multi);
bratonien_tools_webdav_download_test_abort(500, 'Temporaere Download-Datei konnte nicht angelegt werden.');
}
$ch = curl_init($url);
curl_setopt_array($ch, array(
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_TIMEOUT => 180,
CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
CURLOPT_USERPWD => $connection['user'].':'.$connection['password'],
CURLOPT_RETURNTRANSFER => false,
CURLOPT_FAILONERROR => false,
CURLOPT_FILE => $fp,
CURLOPT_USERAGENT => 'Bratonien-Tools-WebDAV-Download-Stress-Test',
));
curl_multi_add_handle($multi, $ch);
$items[] = array('ch'=>$ch, 'fp'=>$fp, 'path'=>$path);
}
$started_at = microtime(true);
do
{
$status = curl_multi_exec($multi, $running);
if ($status !== CURLM_OK) break;
if ($running > 0)
{
$selected = curl_multi_select($multi, 1.0);
if ($selected === -1) usleep(10000);
}
}
while ($running > 0);
$elapsed_seconds = microtime(true) - $started_at;
$downloads = array();
$total_bytes = 0;
$successful = 0;
$failed = 0;
foreach ($items as $index => $item)
{
@fflush($item['fp']);
@fclose($item['fp']);
$http = (int)curl_getinfo($item['ch'], CURLINFO_HTTP_CODE);
$time_ms = round((float)curl_getinfo($item['ch'], CURLINFO_TOTAL_TIME) * 1000, 2);
$errno = curl_errno($item['ch']);
$error = curl_error($item['ch']);
$bytes = is_file($item['path']) ? (int)filesize($item['path']) : 0;
$ok = ($errno === 0 && $http >= 200 && $http < 300 && $bytes > 0);
if ($ok) $successful++; else $failed++;
$total_bytes += $bytes;
$downloads[] = array(
'index'=>$index + 1,
'ok'=>$ok,
'http'=>$http,
'bytes'=>$bytes,
'elapsed_ms'=>$time_ms,
'mbps'=>$time_ms > 0 ? round(($bytes * 8) / ($time_ms / 1000) / 1000000, 2) : 0,
'curl_errno'=>$errno,
'curl_error'=>$error,
);
@unlink($item['path']);
curl_multi_remove_handle($multi, $item['ch']);
curl_close($item['ch']);
}
curl_multi_close($multi);
$elapsed_ms = round($elapsed_seconds * 1000, 2);
$aggregate_mbps = $elapsed_seconds > 0 ? round(($total_bytes * 8) / $elapsed_seconds / 1000000, 2) : 0;
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store');
echo json_encode(array(
'image_id'=>$image_id,
'parallel'=>$parallel,
'same_source_repeated'=>true,
'expected_source_bytes'=>(int)$source['size'],
'successful'=>$successful,
'failed'=>$failed,
'total_bytes'=>$total_bytes,
'peak_temp_disk_bytes'=>$total_bytes,
'elapsed_ms'=>$elapsed_ms,
'aggregate_mbps'=>$aggregate_mbps,
'downloads'=>$downloads,
), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);

174
webdav-image.php Normal file
View File

@@ -0,0 +1,174 @@
<?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');
require_once(BRATONIEN_TOOLS_PATH.'include/webdav_materialize_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_materialize_source_info($image_id);
if (!$source) bratonien_tools_webdav_image_abort(404, 'Keine WebDAV-Quelle für dieses Bild gefunden.');
if (!empty($_GET['preview']))
{
$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.8.6',
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;
}