functions.php 91 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547
  1. <?php
  2. require_once __DIR__ . "/../config.php";
  3. function readJsonFile($file)
  4. {
  5. if (!file_exists($file)) {
  6. return [];
  7. }
  8. $content = file_get_contents($file);
  9. if ($content === false || trim($content) === "") {
  10. return [];
  11. }
  12. $data = json_decode($content, true);
  13. return is_array($data) ? $data : [];
  14. }
  15. function writeJsonFile($file, $data)
  16. {
  17. $dir = dirname($file);
  18. if (!is_dir($dir) && !mkdir($dir, 02775, true) && !is_dir($dir)) {
  19. return false;
  20. }
  21. @chmod($dir, 02775);
  22. if (file_exists($file) && !is_writable($file)) {
  23. @chmod($file, 0664);
  24. }
  25. $json = json_encode(
  26. $data,
  27. JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES,
  28. );
  29. // Atomic write using temp file + rename
  30. $tmpFile = $file . ".tmp";
  31. $result = file_put_contents($tmpFile, $json, LOCK_EX);
  32. if ($result === false) {
  33. return false;
  34. }
  35. @chmod($tmpFile, 0664);
  36. // Rename is atomic on same filesystem
  37. if (!rename($tmpFile, $file)) {
  38. unlink($tmpFile);
  39. return false;
  40. }
  41. @chmod($file, 0664);
  42. return true;
  43. }
  44. function sanitize($input)
  45. {
  46. return trim(strip_tags((string) $input));
  47. }
  48. function escape($value)
  49. {
  50. return htmlspecialchars((string) $value, ENT_QUOTES, "UTF-8");
  51. }
  52. /**
  53. * CSRF Protection
  54. */
  55. function generateCsrfToken()
  56. {
  57. if (empty($_SESSION["csrf_token"])) {
  58. $_SESSION["csrf_token"] = bin2hex(random_bytes(32));
  59. }
  60. return $_SESSION["csrf_token"];
  61. }
  62. function validateCsrfToken($token)
  63. {
  64. if (empty($_SESSION["csrf_token"])) {
  65. return false;
  66. }
  67. return hash_equals($_SESSION["csrf_token"], $token);
  68. }
  69. function csrfField()
  70. {
  71. return '<input type="hidden" name="csrf_token" value="' .
  72. escape(generateCsrfToken()) .
  73. '">';
  74. }
  75. /**
  76. * File-based rate limiting (per client IP) for shared hosting without Redis.
  77. * State lives under DATA_DIR/ratelimit/ (not web-accessible with default .htaccess).
  78. */
  79. function getRateLimitClientIp(): string
  80. {
  81. $ip = trim((string) ($_SERVER["REMOTE_ADDR"] ?? ""));
  82. return $ip !== "" ? $ip : "unknown";
  83. }
  84. function getRateLimitStatePath(string $name): ?string
  85. {
  86. $name = preg_replace("/[^a-z0-9_-]/", "", strtolower($name));
  87. if ($name === "") {
  88. $name = "default";
  89. }
  90. $dir = rtrim(DATA_DIR, "/\\") . "/ratelimit";
  91. return $dir . "/" . $name . ".json";
  92. }
  93. /**
  94. * @return bool true if under limit; when $consume is true, increments counter on allow
  95. */
  96. function rateLimitEvaluate(
  97. string $name,
  98. int $maxAttempts,
  99. int $windowSeconds,
  100. bool $consume,
  101. ): bool {
  102. if ($maxAttempts < 1 || $windowSeconds < 1) {
  103. return true;
  104. }
  105. $path = getRateLimitStatePath($name);
  106. if ($path === null) {
  107. return true;
  108. }
  109. $dir = dirname($path);
  110. if (
  111. !is_dir($dir) &&
  112. !@mkdir($dir, 02775, true) &&
  113. !is_dir($dir)
  114. ) {
  115. return true;
  116. }
  117. if (is_dir($dir)) {
  118. @chmod($dir, 02775);
  119. }
  120. $fh = fopen($path, "c+");
  121. if ($fh === false) {
  122. return true;
  123. }
  124. if (!flock($fh, LOCK_EX)) {
  125. fclose($fh);
  126. return true;
  127. }
  128. rewind($fh);
  129. $raw = stream_get_contents($fh);
  130. $data = [];
  131. if (is_string($raw) && trim($raw) !== "") {
  132. $decoded = json_decode($raw, true);
  133. if (is_array($decoded)) {
  134. $data = $decoded;
  135. }
  136. }
  137. $now = time();
  138. $ip = getRateLimitClientIp();
  139. foreach ($data as $key => $entry) {
  140. if (!is_array($entry)) {
  141. unset($data[$key]);
  142. continue;
  143. }
  144. $w = (int) ($entry["w"] ?? 0);
  145. if ($now - $w > $windowSeconds * 2) {
  146. unset($data[$key]);
  147. }
  148. }
  149. $entry = isset($data[$ip]) && is_array($data[$ip]) ? $data[$ip] : null;
  150. $windowStart = (int) ($entry["w"] ?? $now);
  151. $count = (int) ($entry["c"] ?? 0);
  152. if ($entry === null || $now - $windowStart > $windowSeconds) {
  153. $windowStart = $now;
  154. $count = 0;
  155. }
  156. if ($count >= $maxAttempts) {
  157. flock($fh, LOCK_UN);
  158. fclose($fh);
  159. return false;
  160. }
  161. if ($consume) {
  162. $count++;
  163. $data[$ip] = ["w" => $windowStart, "c" => $count];
  164. $payload = json_encode($data, JSON_UNESCAPED_UNICODE);
  165. if ($payload === false) {
  166. flock($fh, LOCK_UN);
  167. fclose($fh);
  168. return true;
  169. }
  170. ftruncate($fh, 0);
  171. rewind($fh);
  172. fwrite($fh, $payload);
  173. fflush($fh);
  174. @chmod($path, 0660);
  175. }
  176. flock($fh, LOCK_UN);
  177. fclose($fh);
  178. return true;
  179. }
  180. /**
  181. * @return bool true if under limit (and counter updated), false if blocked
  182. */
  183. function rateLimitTryConsume(string $name, int $maxAttempts, int $windowSeconds): bool
  184. {
  185. return rateLimitEvaluate($name, $maxAttempts, $windowSeconds, true);
  186. }
  187. function rateLimitClearIp(string $name, ?string $ip = null): void
  188. {
  189. $path = getRateLimitStatePath($name);
  190. if ($path === null || !is_file($path)) {
  191. return;
  192. }
  193. $ip = $ip ?? getRateLimitClientIp();
  194. $fh = fopen($path, "c+");
  195. if ($fh === false) {
  196. return;
  197. }
  198. if (!flock($fh, LOCK_EX)) {
  199. fclose($fh);
  200. return;
  201. }
  202. rewind($fh);
  203. $raw = stream_get_contents($fh);
  204. $data = [];
  205. if (is_string($raw) && trim($raw) !== "") {
  206. $decoded = json_decode($raw, true);
  207. if (is_array($decoded)) {
  208. $data = $decoded;
  209. }
  210. }
  211. unset($data[$ip]);
  212. $payload = json_encode($data, JSON_UNESCAPED_UNICODE);
  213. if ($payload !== false) {
  214. ftruncate($fh, 0);
  215. rewind($fh);
  216. fwrite($fh, $payload);
  217. fflush($fh);
  218. }
  219. flock($fh, LOCK_UN);
  220. fclose($fh);
  221. }
  222. /** Max failed admin login attempts per IP within the window. */
  223. function getAdminLoginRateLimitMax(): int
  224. {
  225. return defined("ADMIN_LOGIN_RATE_LIMIT_MAX")
  226. ? max(1, (int) ADMIN_LOGIN_RATE_LIMIT_MAX)
  227. : 10;
  228. }
  229. function getAdminLoginRateLimitWindow(): int
  230. {
  231. return defined("ADMIN_LOGIN_RATE_LIMIT_WINDOW")
  232. ? max(60, (int) ADMIN_LOGIN_RATE_LIMIT_WINDOW)
  233. : 900;
  234. }
  235. function isAdminLoginRateLimited(): bool
  236. {
  237. $path = getRateLimitStatePath("admin_login");
  238. if ($path === null || !is_file($path)) {
  239. return false;
  240. }
  241. $fh = fopen($path, "r");
  242. if ($fh === false) {
  243. return false;
  244. }
  245. if (!flock($fh, LOCK_SH)) {
  246. fclose($fh);
  247. return false;
  248. }
  249. rewind($fh);
  250. $raw = stream_get_contents($fh);
  251. flock($fh, LOCK_UN);
  252. fclose($fh);
  253. $data = [];
  254. if (is_string($raw) && trim($raw) !== "") {
  255. $decoded = json_decode($raw, true);
  256. if (is_array($decoded)) {
  257. $data = $decoded;
  258. }
  259. }
  260. $ip = getRateLimitClientIp();
  261. $now = time();
  262. $window = getAdminLoginRateLimitWindow();
  263. $max = getAdminLoginRateLimitMax();
  264. if (!isset($data[$ip]) || !is_array($data[$ip])) {
  265. return false;
  266. }
  267. $windowStart = (int) ($data[$ip]["w"] ?? 0);
  268. $count = (int) ($data[$ip]["c"] ?? 0);
  269. if ($now - $windowStart > $window) {
  270. return false;
  271. }
  272. return $count >= $max;
  273. }
  274. function recordAdminLoginFailure(): void
  275. {
  276. rateLimitTryConsume(
  277. "admin_login",
  278. getAdminLoginRateLimitMax(),
  279. getAdminLoginRateLimitWindow(),
  280. );
  281. }
  282. function clearAdminLoginRateLimitForCurrentIp(): void
  283. {
  284. rateLimitClearIp("admin_login", getRateLimitClientIp());
  285. }
  286. function getCheckoutRateLimitMax(): int
  287. {
  288. return defined("CHECKOUT_RATE_LIMIT_MAX")
  289. ? max(1, (int) CHECKOUT_RATE_LIMIT_MAX)
  290. : 30;
  291. }
  292. function getCheckoutRateLimitWindow(): int
  293. {
  294. return defined("CHECKOUT_RATE_LIMIT_WINDOW")
  295. ? max(60, (int) CHECKOUT_RATE_LIMIT_WINDOW)
  296. : 3600;
  297. }
  298. function checkoutRateLimitWouldAllow(): bool
  299. {
  300. return rateLimitEvaluate(
  301. "checkout",
  302. getCheckoutRateLimitMax(),
  303. getCheckoutRateLimitWindow(),
  304. false,
  305. );
  306. }
  307. function checkoutRateLimitTryConsume(): bool
  308. {
  309. return rateLimitTryConsume(
  310. "checkout",
  311. getCheckoutRateLimitMax(),
  312. getCheckoutRateLimitWindow(),
  313. );
  314. }
  315. function getUploadFilename($filename)
  316. {
  317. $filename = trim((string) $filename);
  318. if ($filename === "") {
  319. return "";
  320. }
  321. return basename($filename);
  322. }
  323. function getUploadPath($filename)
  324. {
  325. $filename = getUploadFilename($filename);
  326. if ($filename === "") {
  327. return null;
  328. }
  329. return rtrim(UPLOADS_DIR, "/\\") . "/" . $filename;
  330. }
  331. function getUploadUrl($filename)
  332. {
  333. $filename = getUploadFilename($filename);
  334. if ($filename === "") {
  335. return null;
  336. }
  337. return rtrim(UPLOADS_URL, "/\\") . "/" . rawurlencode($filename);
  338. }
  339. function setFlashMessage($key, $type, $message)
  340. {
  341. $key = trim((string) $key);
  342. $type = trim((string) $type);
  343. $message = trim((string) $message);
  344. if ($key === "" || $type === "" || $message === "") {
  345. return;
  346. }
  347. $_SESSION["flash_messages"][$key] = [
  348. "type" => $type,
  349. "message" => $message,
  350. ];
  351. }
  352. function consumeFlashMessage($key)
  353. {
  354. $key = trim((string) $key);
  355. if ($key === "") {
  356. return null;
  357. }
  358. $messages = $_SESSION["flash_messages"] ?? [];
  359. if (
  360. !is_array($messages) ||
  361. !isset($messages[$key]) ||
  362. !is_array($messages[$key])
  363. ) {
  364. return null;
  365. }
  366. $message = $messages[$key];
  367. unset($_SESSION["flash_messages"][$key]);
  368. $type = trim((string) ($message["type"] ?? ""));
  369. $text = trim((string) ($message["message"] ?? ""));
  370. if ($type === "" || $text === "") {
  371. return null;
  372. }
  373. return [
  374. "type" => $type,
  375. "message" => $text,
  376. ];
  377. }
  378. function normalizeAdminUsername($username)
  379. {
  380. return trim((string) $username);
  381. }
  382. function normalizeAdminDescription($description)
  383. {
  384. return trim((string) $description);
  385. }
  386. function normalizeAdminEmail($email)
  387. {
  388. return strtolower(trim((string) $email));
  389. }
  390. function isValidAdminUsername($username)
  391. {
  392. $username = normalizeAdminUsername($username);
  393. return preg_match('/^[A-Za-z0-9][A-Za-z0-9._-]{2,49}$/', $username) === 1;
  394. }
  395. function isValidAdminDescription($description)
  396. {
  397. $description = normalizeAdminDescription($description);
  398. if ($description === "") {
  399. return false;
  400. }
  401. $length = function_exists("mb_strlen")
  402. ? mb_strlen($description)
  403. : strlen($description);
  404. return $length <= 120;
  405. }
  406. function isValidAdminEmail($email)
  407. {
  408. $email = normalizeAdminEmail($email);
  409. return $email !== "" && filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
  410. }
  411. function getDefaultAdminDescription($username)
  412. {
  413. return "Admin";
  414. }
  415. function getDefaultAdminEmail()
  416. {
  417. $email = defined("ADMIN_EMAIL") ? normalizeAdminEmail(ADMIN_EMAIL) : "";
  418. return isValidAdminEmail($email) ? $email : "";
  419. }
  420. function getAdminAccounts()
  421. {
  422. $data = readJsonFile(ADMINS_FILE);
  423. $records =
  424. isset($data["admins"]) && is_array($data["admins"])
  425. ? $data["admins"]
  426. : [];
  427. $accounts = [];
  428. foreach ($records as $username => $record) {
  429. $username = normalizeAdminUsername($username);
  430. if ($username === "") {
  431. continue;
  432. }
  433. if (is_string($record)) {
  434. $record = [
  435. "password_hash" => $record,
  436. "description" => getDefaultAdminDescription($username),
  437. "email" => getDefaultAdminEmail(),
  438. ];
  439. }
  440. if (!is_array($record)) {
  441. continue;
  442. }
  443. $hash = isset($record["password_hash"])
  444. ? (string) $record["password_hash"]
  445. : "";
  446. if ($hash === "") {
  447. continue;
  448. }
  449. $description = normalizeAdminDescription(
  450. $record["description"] ?? getDefaultAdminDescription($username),
  451. );
  452. if (!isValidAdminDescription($description)) {
  453. $description = getDefaultAdminDescription($username);
  454. }
  455. $email = normalizeAdminEmail(
  456. $record["email"] ?? getDefaultAdminEmail(),
  457. );
  458. if (!isValidAdminEmail($email)) {
  459. $email = getDefaultAdminEmail();
  460. }
  461. $accounts[$username] = [
  462. "password_hash" => $hash,
  463. "description" => $description,
  464. "email" => $email,
  465. ];
  466. }
  467. ksort($accounts);
  468. return $accounts;
  469. }
  470. function getAdminUsers()
  471. {
  472. $users = [];
  473. foreach (getAdminAccounts() as $username => $record) {
  474. $users[$username] = $record["password_hash"];
  475. }
  476. return $users;
  477. }
  478. function saveAdminAccounts($accounts)
  479. {
  480. $result = [];
  481. foreach ($accounts as $username => $record) {
  482. $username = normalizeAdminUsername($username);
  483. if ($username === "" || !is_array($record)) {
  484. continue;
  485. }
  486. $hash = isset($record["password_hash"])
  487. ? (string) $record["password_hash"]
  488. : "";
  489. if ($hash === "") {
  490. continue;
  491. }
  492. $description = normalizeAdminDescription(
  493. $record["description"] ?? getDefaultAdminDescription($username),
  494. );
  495. if (!isValidAdminDescription($description)) {
  496. $description = getDefaultAdminDescription($username);
  497. }
  498. $email = normalizeAdminEmail(
  499. $record["email"] ?? getDefaultAdminEmail(),
  500. );
  501. if (!isValidAdminEmail($email)) {
  502. $email = getDefaultAdminEmail();
  503. }
  504. $result[$username] = [
  505. "password_hash" => $hash,
  506. "description" => $description,
  507. "email" => $email,
  508. ];
  509. }
  510. ksort($result);
  511. return writeJsonFile(ADMINS_FILE, ["admins" => $result]);
  512. }
  513. function getDefaultCategories()
  514. {
  515. return [["id" => "apparel", "label" => "Bekleidung"]];
  516. }
  517. function normalizeCategoryId($id)
  518. {
  519. $id = trim((string) $id);
  520. if ($id === "") {
  521. return "";
  522. }
  523. if (function_exists("iconv")) {
  524. $converted = @iconv("UTF-8", "ASCII//TRANSLIT//IGNORE", $id);
  525. if (is_string($converted) && $converted !== "") {
  526. $id = $converted;
  527. }
  528. }
  529. $id = strtolower($id);
  530. $id = preg_replace("/[^a-z0-9]+/", "-", $id);
  531. return trim((string) $id, "-");
  532. }
  533. function normalizeCategoryLabel($label)
  534. {
  535. return trim((string) $label);
  536. }
  537. function isValidCategoryLabel($label)
  538. {
  539. $label = normalizeCategoryLabel($label);
  540. if ($label === "") {
  541. return false;
  542. }
  543. $length = function_exists("mb_strlen") ? mb_strlen($label) : strlen($label);
  544. return $length <= 80;
  545. }
  546. function normalizeCategories($categories)
  547. {
  548. $normalized = [];
  549. if (!is_array($categories)) {
  550. $categories = [];
  551. }
  552. foreach ($categories as $category) {
  553. if (!is_array($category)) {
  554. continue;
  555. }
  556. $id = normalizeCategoryId($category["id"] ?? "");
  557. $label = normalizeCategoryLabel($category["label"] ?? "");
  558. if ($id === "" || !isValidCategoryLabel($label)) {
  559. continue;
  560. }
  561. $normalized[$id] = [
  562. "id" => $id,
  563. "label" => $label,
  564. ];
  565. }
  566. if (empty($normalized)) {
  567. foreach (getDefaultCategories() as $category) {
  568. $normalized[$category["id"]] = $category;
  569. }
  570. }
  571. uasort($normalized, function ($left, $right) {
  572. return strcasecmp($left["label"], $right["label"]);
  573. });
  574. return array_values($normalized);
  575. }
  576. function getCategories()
  577. {
  578. $data = readJsonFile(CATEGORIES_FILE);
  579. return normalizeCategories($data["categories"] ?? []);
  580. }
  581. function saveCategories($categories)
  582. {
  583. return writeJsonFile(CATEGORIES_FILE, [
  584. "categories" => normalizeCategories($categories),
  585. ]);
  586. }
  587. function getCategoryById($categoryId)
  588. {
  589. $categoryId = normalizeCategoryId($categoryId);
  590. foreach (getCategories() as $category) {
  591. if ($category["id"] === $categoryId) {
  592. return $category;
  593. }
  594. }
  595. return null;
  596. }
  597. function getCategoryLabel($categoryId)
  598. {
  599. $category = getCategoryById($categoryId);
  600. if ($category !== null) {
  601. return $category["label"];
  602. }
  603. return trim((string) $categoryId);
  604. }
  605. function getCategoryLabels($categoryIds)
  606. {
  607. $labels = [];
  608. foreach (normalizeProductCategoryIds($categoryIds) as $categoryId) {
  609. $labels[] = getCategoryLabel($categoryId);
  610. }
  611. return $labels;
  612. }
  613. function getCategoryChipPalette($categoryId)
  614. {
  615. $categoryId = normalizeCategoryId($categoryId);
  616. if ($categoryId === "") {
  617. return [
  618. "background" => "#ebe8df",
  619. "border" => "#d0c8b5",
  620. "text" => "#4b4b4b",
  621. ];
  622. }
  623. $hash = crc32($categoryId);
  624. if ($hash < 0) {
  625. $hash = $hash * -1;
  626. }
  627. // Spread hues across a distinct red -> blue range.
  628. $hueSteps = [0, 16, 32, 48, 66, 84, 104, 128, 152, 176, 200, 224];
  629. $hue = $hueSteps[$hash % count($hueSteps)];
  630. $saturation = 44 + (($hash >> 8) % 10);
  631. $lightness = 84 + (($hash >> 16) % 7);
  632. $background = "hsl(" . $hue . ", " . $saturation . "%, " . $lightness . "%)";
  633. $border = "hsl(" . $hue . ", " . ($saturation + 8) . "%, " . ($lightness - 16) . "%)";
  634. $text = "hsl(" . $hue . ", " . ($saturation + 18) . "%, 24%)";
  635. return [
  636. "background" => $background,
  637. "border" => $border,
  638. "text" => $text,
  639. ];
  640. }
  641. function generateCategoryIdFromLabel($label, $existingCategories = [])
  642. {
  643. $baseId = normalizeCategoryId($label);
  644. if ($baseId === "") {
  645. $baseId = "category";
  646. }
  647. $used = [];
  648. foreach (normalizeCategories($existingCategories) as $category) {
  649. $used[$category["id"]] = true;
  650. }
  651. $candidate = $baseId;
  652. $counter = 2;
  653. while (isset($used[$candidate])) {
  654. $candidate = $baseId . "-" . $counter;
  655. $counter++;
  656. }
  657. return $candidate;
  658. }
  659. function isCategoryInUse($categoryId)
  660. {
  661. foreach (getProducts() as $product) {
  662. if (productHasCategory($product, $categoryId)) {
  663. return true;
  664. }
  665. }
  666. return false;
  667. }
  668. function normalizeProductCategoryIds($categoryValue)
  669. {
  670. if (is_array($categoryValue)) {
  671. $rawIds = $categoryValue;
  672. } elseif ($categoryValue === null || $categoryValue === "") {
  673. $rawIds = [];
  674. } else {
  675. $rawIds = [$categoryValue];
  676. }
  677. $normalized = [];
  678. foreach ($rawIds as $categoryId) {
  679. $categoryId = normalizeCategoryId($categoryId);
  680. if ($categoryId !== "") {
  681. $normalized[$categoryId] = $categoryId;
  682. }
  683. }
  684. return array_values($normalized);
  685. }
  686. function getProductCategoryIds($product)
  687. {
  688. if (isset($product["categories"])) {
  689. return normalizeProductCategoryIds($product["categories"]);
  690. }
  691. return normalizeProductCategoryIds($product["category"] ?? []);
  692. }
  693. function productHasCategory($product, $categoryId)
  694. {
  695. $categoryId = normalizeCategoryId($categoryId);
  696. if ($categoryId === "") {
  697. return false;
  698. }
  699. return in_array($categoryId, getProductCategoryIds($product), true);
  700. }
  701. function getProductSizes($product)
  702. {
  703. if (isset($product["sizes"]) && is_array($product["sizes"])) {
  704. $sizes = $product["sizes"];
  705. } elseif (isset($product["sizes"]) && is_string($product["sizes"])) {
  706. $sizes = explode(",", $product["sizes"]);
  707. } else {
  708. $sizes = [];
  709. }
  710. $normalized = [];
  711. foreach ($sizes as $size) {
  712. $size = trim((string) $size);
  713. if ($size !== "") {
  714. $normalized[$size] = $size;
  715. }
  716. }
  717. return array_values($normalized);
  718. }
  719. function productUsesSizeStock($product)
  720. {
  721. return !empty(getProductSizes($product));
  722. }
  723. function normalizeAvailabilityLabels($sizes, $labels)
  724. {
  725. $result = [];
  726. if (!is_array($labels)) {
  727. $labels = [];
  728. }
  729. foreach ($sizes as $size) {
  730. $text = trim((string) ($labels[$size] ?? ""));
  731. $result[$size] = $text;
  732. }
  733. return $result;
  734. }
  735. function getAvailabilityLabel($product, $size)
  736. {
  737. $labels =
  738. isset($product["availability_labels"]) &&
  739. is_array($product["availability_labels"])
  740. ? $product["availability_labels"]
  741. : [];
  742. return trim((string) ($labels[$size] ?? ""));
  743. }
  744. function normalizeProductRecord($product, $defaultCategoryId = "")
  745. {
  746. if (!is_array($product)) {
  747. return null;
  748. }
  749. $productId = isset($product["id"]) ? (int) $product["id"] : 0;
  750. $name = trim((string) ($product["name"] ?? ""));
  751. if ($productId <= 0 || $name === "") {
  752. return null;
  753. }
  754. $sizes = getProductSizes($product);
  755. if (empty($sizes)) {
  756. $sizes = ["Standard"];
  757. }
  758. $categories = getProductCategoryIds($product);
  759. if (empty($categories) && $defaultCategoryId !== "") {
  760. $categories = [$defaultCategoryId];
  761. }
  762. $availabilityLabels = normalizeAvailabilityLabels(
  763. $sizes,
  764. isset($product["availability_labels"]) &&
  765. is_array($product["availability_labels"])
  766. ? $product["availability_labels"]
  767. : [],
  768. );
  769. return [
  770. "id" => $productId,
  771. "name" => $name,
  772. "description" => trim((string) ($product["description"] ?? "")),
  773. "image" => trim((string) ($product["image"] ?? "")),
  774. "categories" => $categories,
  775. "sizes" => implode(",", $sizes),
  776. "availability_labels" => $availabilityLabels,
  777. ];
  778. }
  779. function getProducts()
  780. {
  781. $data = readJsonFile(PRODUCTS_FILE);
  782. $rawProducts =
  783. isset($data["products"]) && is_array($data["products"])
  784. ? $data["products"]
  785. : [];
  786. $categories = getCategories();
  787. $defaultCategoryId = !empty($categories) ? $categories[0]["id"] : "apparel";
  788. $products = [];
  789. foreach ($rawProducts as $product) {
  790. $normalized = normalizeProductRecord($product, $defaultCategoryId);
  791. if ($normalized !== null) {
  792. $products[] = $normalized;
  793. }
  794. }
  795. usort($products, function ($left, $right) {
  796. return strcasecmp($left["name"], $right["name"]);
  797. });
  798. return $products;
  799. }
  800. function getProductById($id)
  801. {
  802. $id = (int) $id;
  803. foreach (getProducts() as $product) {
  804. if ((int) $product["id"] === $id) {
  805. return $product;
  806. }
  807. }
  808. return null;
  809. }
  810. function saveProducts($products)
  811. {
  812. $categories = getCategories();
  813. $defaultCategoryId = !empty($categories) ? $categories[0]["id"] : "apparel";
  814. $normalized = [];
  815. foreach ($products as $product) {
  816. $record = normalizeProductRecord($product, $defaultCategoryId);
  817. if ($record !== null) {
  818. $normalized[] = $record;
  819. }
  820. }
  821. return writeJsonFile(PRODUCTS_FILE, [
  822. "products" => array_values($normalized),
  823. ]);
  824. }
  825. function getFaqFilePath(): string
  826. {
  827. $dataDir = defined("DATA_DIR") ? DATA_DIR : dirname(__DIR__) . "/data/";
  828. $defaultPath = rtrim($dataDir, "/\\") . "/faq.json";
  829. if (!defined("FAQ_FILE") || !is_string(FAQ_FILE) || FAQ_FILE === "") {
  830. return $defaultPath;
  831. }
  832. $configuredPath = FAQ_FILE;
  833. $normalizedDataDir = str_replace("\\", "/", rtrim($dataDir, "/\\")) . "/";
  834. $normalizedConfigured = str_replace("\\", "/", $configuredPath);
  835. if (strpos($normalizedConfigured, $normalizedDataDir) !== 0) {
  836. return $defaultPath;
  837. }
  838. return $configuredPath;
  839. }
  840. function getFaqContent(): string
  841. {
  842. $defaultContent =
  843. "# FAQ\n\nHier kann der FAQ-Inhalt im Admin-Bereich bearbeitet werden.";
  844. $data = readJsonFile(getFaqFilePath());
  845. if (!isset($data["content"]) || !is_string($data["content"])) {
  846. return $defaultContent;
  847. }
  848. return $data["content"];
  849. }
  850. function saveFaqContent(string $markdown): bool
  851. {
  852. return writeJsonFile(getFaqFilePath(), ["content" => (string) $markdown]);
  853. }
  854. function renderFaqInlineMarkdown(string $text): string
  855. {
  856. $escaped = escape($text);
  857. $escaped = preg_replace_callback(
  858. '/\[([^\]]+)\]\(([^)\s]+)\)/',
  859. function ($matches) {
  860. $label = $matches[1];
  861. $url = trim(html_entity_decode($matches[2], ENT_QUOTES, "UTF-8"));
  862. if ($url === "") {
  863. return $matches[0];
  864. }
  865. $scheme = strtolower((string) parse_url($url, PHP_URL_SCHEME));
  866. if (!in_array($scheme, ["http", "https", "mailto"], true)) {
  867. return $matches[0];
  868. }
  869. return '<a href="' . escape($url) . '">' . $label . "</a>";
  870. },
  871. $escaped,
  872. );
  873. $escaped = preg_replace(
  874. "/\*\*(.+?)\*\*/s",
  875. '<strong>$1</strong>',
  876. $escaped,
  877. );
  878. $escaped = preg_replace(
  879. "/(?<!\*)\*(?!\s)(.+?)(?<!\s)\*(?!\*)/s",
  880. '<em>$1</em>',
  881. $escaped,
  882. );
  883. return $escaped;
  884. }
  885. function renderFaqMarkdown(string $markdown): string
  886. {
  887. $normalized = str_replace(["\r\n", "\r"], "\n", $markdown);
  888. $lines = explode("\n", $normalized);
  889. $htmlParts = [];
  890. $paragraphLines = [];
  891. $listType = "";
  892. $flushParagraph = function () use (&$paragraphLines, &$htmlParts): void {
  893. if (empty($paragraphLines)) {
  894. return;
  895. }
  896. $rendered = [];
  897. foreach ($paragraphLines as $line) {
  898. $rendered[] = renderFaqInlineMarkdown($line);
  899. }
  900. $htmlParts[] = "<p>" . implode("<br>\n", $rendered) . "</p>";
  901. $paragraphLines = [];
  902. };
  903. $closeList = function () use (&$listType, &$htmlParts): void {
  904. if ($listType !== "") {
  905. $htmlParts[] = "</" . $listType . ">";
  906. $listType = "";
  907. }
  908. };
  909. foreach ($lines as $line) {
  910. $line = rtrim($line);
  911. $trimmed = trim($line);
  912. if ($trimmed === "") {
  913. $flushParagraph();
  914. $closeList();
  915. continue;
  916. }
  917. if (preg_match('/^(#{1,3})\s+(.+)$/', $trimmed, $matches) === 1) {
  918. $flushParagraph();
  919. $closeList();
  920. $level = strlen($matches[1]);
  921. $htmlParts[] =
  922. "<h" .
  923. $level .
  924. ">" .
  925. renderFaqInlineMarkdown($matches[2]) .
  926. "</h" .
  927. $level .
  928. ">";
  929. continue;
  930. }
  931. if (preg_match('/^\s*[-*]\s+(.+)$/', $line, $matches) === 1) {
  932. $flushParagraph();
  933. if ($listType !== "ul") {
  934. $closeList();
  935. $listType = "ul";
  936. $htmlParts[] = "<ul>";
  937. }
  938. $htmlParts[] =
  939. "<li>" . renderFaqInlineMarkdown($matches[1]) . "</li>";
  940. continue;
  941. }
  942. if (preg_match('/^\s*\d+\.\s+(.+)$/', $line, $matches) === 1) {
  943. $flushParagraph();
  944. if ($listType !== "ol") {
  945. $closeList();
  946. $listType = "ol";
  947. $htmlParts[] = "<ol>";
  948. }
  949. $htmlParts[] =
  950. "<li>" . renderFaqInlineMarkdown($matches[1]) . "</li>";
  951. continue;
  952. }
  953. $closeList();
  954. $paragraphLines[] = $trimmed;
  955. }
  956. $flushParagraph();
  957. $closeList();
  958. return empty($htmlParts)
  959. ? "<p>Keine FAQ-Inhalte vorhanden.</p>"
  960. : implode("\n", $htmlParts);
  961. }
  962. function getDefaultOrganizations()
  963. {
  964. return [
  965. [
  966. "id" => "feuerwehr-freising",
  967. "label" => "Amt 32 - Feuerwehr Freising",
  968. "sort_order" => 10,
  969. "active" => true,
  970. ],
  971. ];
  972. }
  973. function normalizeOrganizationId($id)
  974. {
  975. return normalizeCategoryId($id);
  976. }
  977. function normalizeOrganizationLabel($label)
  978. {
  979. return trim((string) $label);
  980. }
  981. function isValidOrganizationLabel($label)
  982. {
  983. $label = normalizeOrganizationLabel($label);
  984. if ($label === "") {
  985. return false;
  986. }
  987. $length = function_exists("mb_strlen") ? mb_strlen($label) : strlen($label);
  988. return $length <= 120;
  989. }
  990. function normalizeOrganizations($organizations)
  991. {
  992. $normalized = [];
  993. if (!is_array($organizations)) {
  994. $organizations = [];
  995. }
  996. foreach ($organizations as $organization) {
  997. if (!is_array($organization)) {
  998. continue;
  999. }
  1000. $id = normalizeOrganizationId($organization["id"] ?? "");
  1001. $label = normalizeOrganizationLabel($organization["label"] ?? "");
  1002. if ($id === "" || !isValidOrganizationLabel($label)) {
  1003. continue;
  1004. }
  1005. $sortOrder = isset($organization["sort_order"])
  1006. ? (int) $organization["sort_order"]
  1007. : 0;
  1008. $active =
  1009. !isset($organization["active"]) || (bool) $organization["active"];
  1010. $normalized[$id] = [
  1011. "id" => $id,
  1012. "label" => $label,
  1013. "sort_order" => $sortOrder,
  1014. "active" => $active,
  1015. ];
  1016. }
  1017. if (empty($normalized)) {
  1018. foreach (getDefaultOrganizations() as $organization) {
  1019. $normalized[$organization["id"]] = $organization;
  1020. }
  1021. }
  1022. uasort($normalized, function ($left, $right) {
  1023. if ($left["sort_order"] === $right["sort_order"]) {
  1024. return strcasecmp($left["label"], $right["label"]);
  1025. }
  1026. return $left["sort_order"] <=> $right["sort_order"];
  1027. });
  1028. return array_values($normalized);
  1029. }
  1030. function getOrganizations($onlyActive = false)
  1031. {
  1032. $data = readJsonFile(ORGANIZATIONS_FILE);
  1033. $organizations = normalizeOrganizations($data["organizations"] ?? []);
  1034. if ($onlyActive) {
  1035. $organizations = array_values(
  1036. array_filter($organizations, function ($organization) {
  1037. return !empty($organization["active"]);
  1038. }),
  1039. );
  1040. }
  1041. return $organizations;
  1042. }
  1043. function saveOrganizations($organizations)
  1044. {
  1045. return writeJsonFile(ORGANIZATIONS_FILE, [
  1046. "organizations" => normalizeOrganizations($organizations),
  1047. ]);
  1048. }
  1049. function getOrganizationById($organizationId)
  1050. {
  1051. $organizationId = normalizeOrganizationId($organizationId);
  1052. foreach (getOrganizations(false) as $organization) {
  1053. if ($organization["id"] === $organizationId) {
  1054. return $organization;
  1055. }
  1056. }
  1057. return null;
  1058. }
  1059. function generateOrganizationIdFromLabel($label, $existingOrganizations = [])
  1060. {
  1061. $baseId = normalizeOrganizationId($label);
  1062. if ($baseId === "") {
  1063. $baseId = "organization";
  1064. }
  1065. $used = [];
  1066. foreach (normalizeOrganizations($existingOrganizations) as $organization) {
  1067. $used[$organization["id"]] = true;
  1068. }
  1069. $candidate = $baseId;
  1070. $counter = 2;
  1071. while (isset($used[$candidate])) {
  1072. $candidate = $baseId . "-" . $counter;
  1073. $counter++;
  1074. }
  1075. return $candidate;
  1076. }
  1077. function getDefaultSystemSettings()
  1078. {
  1079. $startpageIntroText = "";
  1080. if (defined("DISCLAIMER_LINES") && is_array(DISCLAIMER_LINES)) {
  1081. $lines = array_filter(
  1082. array_map(function ($line) {
  1083. return trim((string) $line);
  1084. }, DISCLAIMER_LINES),
  1085. function ($line) {
  1086. return $line !== "";
  1087. },
  1088. );
  1089. $startpageIntroText = implode("\n", $lines);
  1090. }
  1091. return [
  1092. "order_recipient_email" => defined("ORDER_RECIPIENT_EMAIL")
  1093. ? ORDER_RECIPIENT_EMAIL
  1094. : getDefaultAdminEmail(),
  1095. "attach_order_pdf_to_admin_email" => defined(
  1096. "ATTACH_ORDER_PDF_TO_ADMIN_EMAIL",
  1097. )
  1098. ? (bool) ATTACH_ORDER_PDF_TO_ADMIN_EMAIL
  1099. : true,
  1100. "startpage_intro_text" => $startpageIntroText,
  1101. ];
  1102. }
  1103. function normalizeSystemSettings($settings)
  1104. {
  1105. $defaults = getDefaultSystemSettings();
  1106. if (!is_array($settings)) {
  1107. $settings = [];
  1108. }
  1109. $recipientEmail = normalizeAdminEmail(
  1110. $settings["order_recipient_email"] ??
  1111. $defaults["order_recipient_email"],
  1112. );
  1113. if (!isValidAdminEmail($recipientEmail)) {
  1114. $recipientEmail = $defaults["order_recipient_email"];
  1115. }
  1116. $startpageIntroText = trim(
  1117. (string) ($settings["startpage_intro_text"] ?? $defaults["startpage_intro_text"]),
  1118. );
  1119. return [
  1120. "order_recipient_email" => $recipientEmail,
  1121. "attach_order_pdf_to_admin_email" => !empty(
  1122. $settings["attach_order_pdf_to_admin_email"]
  1123. ),
  1124. "startpage_intro_text" => $startpageIntroText,
  1125. ];
  1126. }
  1127. function getSystemSettings()
  1128. {
  1129. $data = readJsonFile(SETTINGS_FILE);
  1130. return normalizeSystemSettings($data["settings"] ?? []);
  1131. }
  1132. function saveSystemSettings($settings)
  1133. {
  1134. return writeJsonFile(SETTINGS_FILE, [
  1135. "settings" => normalizeSystemSettings($settings),
  1136. ]);
  1137. }
  1138. function getOrderRecipientEmail()
  1139. {
  1140. $settings = getSystemSettings();
  1141. return $settings["order_recipient_email"];
  1142. }
  1143. function shouldAttachOrderPdfToAdminEmail()
  1144. {
  1145. $settings = getSystemSettings();
  1146. return !empty($settings["attach_order_pdf_to_admin_email"]);
  1147. }
  1148. function getStartpageIntroLines()
  1149. {
  1150. $settings = getSystemSettings();
  1151. $text = trim((string) ($settings["startpage_intro_text"] ?? ""));
  1152. if ($text === "") {
  1153. return [];
  1154. }
  1155. $lines = preg_split('/\R+/', $text) ?: [];
  1156. $lines = array_values(
  1157. array_filter(
  1158. array_map(function ($line) {
  1159. return trim((string) $line);
  1160. }, $lines),
  1161. function ($line) {
  1162. return $line !== "";
  1163. },
  1164. ),
  1165. );
  1166. return $lines;
  1167. }
  1168. function backorderStatusEmpty(): string
  1169. {
  1170. return "";
  1171. }
  1172. function backorderStatusToBeBackordered(): string
  1173. {
  1174. return "to_be_backordered";
  1175. }
  1176. function backorderStatusOrdered(): string
  1177. {
  1178. return "ordered";
  1179. }
  1180. /** Statuses persisted on order line items (load/save). */
  1181. function getBackorderStatusesForStorage(): array
  1182. {
  1183. return [
  1184. backorderStatusEmpty(),
  1185. backorderStatusToBeBackordered(),
  1186. backorderStatusOrdered(),
  1187. ];
  1188. }
  1189. /** Statuses settable from order detail (mark for external reorder). */
  1190. function getBackorderStatusesForAdminMarking(): array
  1191. {
  1192. return [backorderStatusEmpty(), backorderStatusToBeBackordered()];
  1193. }
  1194. function isValidBackorderStatusForStorage(string $status): bool
  1195. {
  1196. return in_array($status, getBackorderStatusesForStorage(), true);
  1197. }
  1198. function isValidBackorderStatusForAdminMarking(string $status): bool
  1199. {
  1200. return in_array($status, getBackorderStatusesForAdminMarking(), true);
  1201. }
  1202. function normalizeOrderItem($item)
  1203. {
  1204. if (!is_array($item)) {
  1205. return null;
  1206. }
  1207. $productId = isset($item["product_id"]) ? (int) $item["product_id"] : 0;
  1208. if ($productId <= 0) {
  1209. return null;
  1210. }
  1211. $product = getProductById($productId);
  1212. if ($product === null) {
  1213. return null;
  1214. }
  1215. $size = trim((string) ($item["size"] ?? ""));
  1216. $sizes = getProductSizes($product);
  1217. if (!empty($sizes)) {
  1218. if ($size === "" || !in_array($size, $sizes, true)) {
  1219. return null;
  1220. }
  1221. } else {
  1222. $size = "";
  1223. }
  1224. $backorderStatus = trim((string) ($item["backorder_status"] ?? ""));
  1225. if (!isValidBackorderStatusForStorage($backorderStatus)) {
  1226. $backorderStatus = backorderStatusEmpty();
  1227. }
  1228. return [
  1229. "product_id" => $productId,
  1230. "product_name" => $product["name"],
  1231. "size" => $size,
  1232. "availability_label" =>
  1233. $size !== "" ? getAvailabilityLabel($product, $size) : "",
  1234. "is_processed" => !empty($item["is_processed"]),
  1235. "backorder_status" => $backorderStatus,
  1236. "backordered_at" => trim((string) ($item["backordered_at"] ?? "")),
  1237. "ordered_at" => trim((string) ($item["ordered_at"] ?? "")),
  1238. ];
  1239. }
  1240. function normalizeOrderItems($items)
  1241. {
  1242. $normalized = [];
  1243. $seen = [];
  1244. if (!is_array($items)) {
  1245. return [];
  1246. }
  1247. foreach ($items as $item) {
  1248. $record = normalizeOrderItem($item);
  1249. if ($record === null) {
  1250. continue;
  1251. }
  1252. $key = $record["product_id"] . "|" . $record["size"];
  1253. if (isset($seen[$key])) {
  1254. continue;
  1255. }
  1256. $seen[$key] = true;
  1257. $normalized[] = $record;
  1258. }
  1259. return array_values($normalized);
  1260. }
  1261. function getOrders()
  1262. {
  1263. $data = readJsonFile(ORDERS_FILE);
  1264. $orders =
  1265. isset($data["orders"]) && is_array($data["orders"])
  1266. ? $data["orders"]
  1267. : [];
  1268. $normalized = [];
  1269. foreach ($orders as $order) {
  1270. $record = normalizeOrderRecord($order);
  1271. if ($record !== null) {
  1272. $normalized[] = $record;
  1273. }
  1274. }
  1275. return $normalized;
  1276. }
  1277. function saveOrders($orders)
  1278. {
  1279. $normalized = [];
  1280. foreach ($orders as $order) {
  1281. $record = normalizeOrderRecord($order);
  1282. if ($record !== null) {
  1283. $normalized[] = $record;
  1284. }
  1285. }
  1286. $result = writeJsonFile(ORDERS_FILE, [
  1287. "orders" => array_values($normalized),
  1288. ]);
  1289. if (!$result) {
  1290. logError("Failed to save orders", [
  1291. "file" => ORDERS_FILE,
  1292. "order_count" => count($normalized),
  1293. ]);
  1294. }
  1295. return (bool) $result;
  1296. }
  1297. function generateOrderId()
  1298. {
  1299. $orders = getOrders();
  1300. $year = date("Y");
  1301. $prefix = defined("ORDER_PREFIX") ? ORDER_PREFIX : "ORD";
  1302. $max = 0;
  1303. $pattern = "/^" . preg_quote($prefix, "/") . '-\d{4}-(\d+)$/';
  1304. foreach ($orders as $order) {
  1305. if (preg_match($pattern, (string) $order["id"], $matches) === 1) {
  1306. $number = (int) $matches[1];
  1307. if ($number > $max) {
  1308. $max = $number;
  1309. }
  1310. }
  1311. }
  1312. return sprintf("%s-%s-%03d", $prefix, $year, $max + 1);
  1313. }
  1314. function normalizeOrderRecord($order)
  1315. {
  1316. if (!is_array($order)) {
  1317. return null;
  1318. }
  1319. $id = trim((string) ($order["id"] ?? ""));
  1320. $customerName = trim((string) ($order["customer_name"] ?? ""));
  1321. $customerEmail = normalizeAdminEmail($order["customer_email"] ?? "");
  1322. $organizationId = normalizeOrganizationId($order["organization_id"] ?? "");
  1323. $organizationLabel = trim((string) ($order["organization_label"] ?? ""));
  1324. $items = normalizeOrderItems($order["items"] ?? []);
  1325. if (
  1326. $id === "" ||
  1327. $customerName === "" ||
  1328. !isValidAdminEmail($customerEmail) ||
  1329. $organizationId === "" ||
  1330. $organizationLabel === "" ||
  1331. empty($items)
  1332. ) {
  1333. return null;
  1334. }
  1335. $createdAt = trim((string) ($order["created_at"] ?? ""));
  1336. if ($createdAt === "") {
  1337. $createdAt = date("Y-m-d H:i:s");
  1338. }
  1339. $status = trim((string) ($order["status"] ?? "open"));
  1340. $allowedStatuses = ["open", "partial", "processed", "cancelled"];
  1341. if (!in_array($status, $allowedStatuses, true)) {
  1342. $status = "open";
  1343. }
  1344. $normalized = [
  1345. "id" => $id,
  1346. "customer_name" => $customerName,
  1347. "customer_email" => $customerEmail,
  1348. "organization_id" => $organizationId,
  1349. "organization_label" => $organizationLabel,
  1350. "comment" => trim((string) ($order["comment"] ?? "")),
  1351. "items" => $items,
  1352. "status" => $status,
  1353. "created_at" => $createdAt,
  1354. "updated_at" => trim((string) ($order["updated_at"] ?? $createdAt)),
  1355. "cancelled_at" => trim((string) ($order["cancelled_at"] ?? "")),
  1356. "cancelled_by" => trim((string) ($order["cancelled_by"] ?? "")),
  1357. "cancellation_reason" => trim(
  1358. (string) ($order["cancellation_reason"] ?? ""),
  1359. ),
  1360. "admin_notified_at" => trim(
  1361. (string) ($order["admin_notified_at"] ?? ""),
  1362. ),
  1363. ];
  1364. return refreshOrderState($normalized);
  1365. }
  1366. function refreshOrderState($order)
  1367. {
  1368. if (!is_array($order)) {
  1369. return null;
  1370. }
  1371. if (($order["status"] ?? "") === "cancelled") {
  1372. return $order;
  1373. }
  1374. $processedCount = 0;
  1375. foreach ($order["items"] as $item) {
  1376. if (!empty($item["is_processed"])) {
  1377. $processedCount++;
  1378. }
  1379. }
  1380. if ($processedCount <= 0) {
  1381. $order["status"] = "open";
  1382. } elseif ($processedCount >= count($order["items"])) {
  1383. $order["status"] = "processed";
  1384. } else {
  1385. $order["status"] = "partial";
  1386. }
  1387. return $order;
  1388. }
  1389. function getOrderById($orderId)
  1390. {
  1391. $orderId = trim((string) $orderId);
  1392. if ($orderId === "") {
  1393. return null;
  1394. }
  1395. foreach (getOrders() as $order) {
  1396. if ($order["id"] === $orderId) {
  1397. return $order;
  1398. }
  1399. }
  1400. return null;
  1401. }
  1402. function buildAbsoluteUrl($path)
  1403. {
  1404. $path = "/" . ltrim((string) $path, "/");
  1405. $siteUrl = defined("SITE_URL") ? trim((string) SITE_URL) : "";
  1406. if (strpos($siteUrl, "://") !== false) {
  1407. return rtrim($siteUrl, "/") . $path;
  1408. }
  1409. $basePath = trim($siteUrl);
  1410. if ($basePath !== "" && $basePath !== "/") {
  1411. $path = "/" . trim($basePath, "/") . $path;
  1412. }
  1413. $canonical = defined("SITE_CANONICAL_ORIGIN")
  1414. ? trim((string) SITE_CANONICAL_ORIGIN)
  1415. : "";
  1416. if (
  1417. $canonical !== "" &&
  1418. preg_match("#\Ahttps?://[^\s/]+#i", $canonical)
  1419. ) {
  1420. return rtrim($canonical, "/") . $path;
  1421. }
  1422. $scheme = isHttpsRequest() ? "https" : "http";
  1423. $host = $_SERVER["HTTP_HOST"] ?? "";
  1424. if ($host === "") {
  1425. return $path;
  1426. }
  1427. return $scheme . "://" . $host . $path;
  1428. }
  1429. function isHttpsRequest(): bool
  1430. {
  1431. if (
  1432. !empty($_SERVER["HTTPS"]) &&
  1433. strtolower((string) $_SERVER["HTTPS"]) !== "off"
  1434. ) {
  1435. return true;
  1436. }
  1437. if (
  1438. !empty($_SERVER["HTTP_X_FORWARDED_PROTO"]) &&
  1439. strtolower((string) $_SERVER["HTTP_X_FORWARDED_PROTO"]) === "https"
  1440. ) {
  1441. return true;
  1442. }
  1443. if (
  1444. !empty($_SERVER["SERVER_PORT"]) &&
  1445. (int) $_SERVER["SERVER_PORT"] === 443
  1446. ) {
  1447. return true;
  1448. }
  1449. return false;
  1450. }
  1451. function createOrder(
  1452. $customerName,
  1453. $customerEmail,
  1454. $organizationId,
  1455. $comment,
  1456. $items,
  1457. ) {
  1458. $customerName = sanitize($customerName);
  1459. $customerEmail = normalizeAdminEmail($customerEmail);
  1460. $organizationId = normalizeOrganizationId($organizationId);
  1461. $comment = trim((string) $comment);
  1462. $items = normalizeOrderItems($items);
  1463. if ($customerName === "") {
  1464. return [
  1465. "success" => false,
  1466. "message" => "Bitte geben Sie einen Namen ein.",
  1467. ];
  1468. }
  1469. if (!isValidAdminEmail($customerEmail)) {
  1470. return [
  1471. "success" => false,
  1472. "message" => "Bitte geben Sie eine gültige E-Mail-Adresse ein.",
  1473. ];
  1474. }
  1475. if (empty($items)) {
  1476. return [
  1477. "success" => false,
  1478. "message" =>
  1479. "Der Warenkorb ist leer oder enthält ungültige Positionen.",
  1480. ];
  1481. }
  1482. $organization = getOrganizationById($organizationId);
  1483. if ($organization === null || empty($organization["active"])) {
  1484. return [
  1485. "success" => false,
  1486. "message" => "Bitte wählen Sie eine gültige Organisation aus.",
  1487. ];
  1488. }
  1489. $now = date("Y-m-d H:i:s");
  1490. $order = [
  1491. "id" => generateOrderId(),
  1492. "customer_name" => $customerName,
  1493. "customer_email" => $customerEmail,
  1494. "organization_id" => $organization["id"],
  1495. "organization_label" => $organization["label"],
  1496. "comment" => $comment,
  1497. "items" => $items,
  1498. "status" => "open",
  1499. "created_at" => $now,
  1500. "updated_at" => $now,
  1501. "cancelled_at" => "",
  1502. "cancelled_by" => "",
  1503. "cancellation_reason" => "",
  1504. "admin_notified_at" => "",
  1505. ];
  1506. $orders = getOrders();
  1507. $orders[] = $order;
  1508. if (!saveOrders($orders)) {
  1509. return [
  1510. "success" => false,
  1511. "message" =>
  1512. "Die Bestellung konnte nicht gespeichert werden. Bitte versuchen Sie es erneut.",
  1513. ];
  1514. }
  1515. logAccess("Order created in createOrder", [
  1516. "order_id" => $order["id"],
  1517. "customer" => $customerEmail,
  1518. "organization" => $organization["label"],
  1519. ]);
  1520. $result = sendConfirmedOrderAdminNotification($order);
  1521. if ($result) {
  1522. markOrderAdminNotified($order["id"]);
  1523. $order = getOrderById($order["id"]);
  1524. }
  1525. sendOrderCreatedCustomerEmail($order);
  1526. return ["success" => true, "order" => $order];
  1527. }
  1528. function markOrderAdminNotified($orderId)
  1529. {
  1530. $orders = getOrders();
  1531. foreach ($orders as &$order) {
  1532. if ($order["id"] !== $orderId) {
  1533. continue;
  1534. }
  1535. $order["admin_notified_at"] = date("Y-m-d H:i:s");
  1536. $order["updated_at"] = date("Y-m-d H:i:s");
  1537. break;
  1538. }
  1539. unset($order);
  1540. saveOrders($orders);
  1541. }
  1542. function toggleOrderItemProcessed($orderId, $itemIndex)
  1543. {
  1544. $orders = getOrders();
  1545. $now = date("Y-m-d H:i:s");
  1546. foreach ($orders as &$order) {
  1547. if ($order["id"] !== $orderId) {
  1548. continue;
  1549. }
  1550. if ($order["status"] === "cancelled") {
  1551. return [
  1552. "success" => false,
  1553. "message" =>
  1554. "Stornierte Bestellungen können nicht mehr bearbeitet werden.",
  1555. ];
  1556. }
  1557. if (!isset($order["items"][$itemIndex])) {
  1558. return [
  1559. "success" => false,
  1560. "message" => "Position nicht gefunden.",
  1561. ];
  1562. }
  1563. $order["items"][$itemIndex]["is_processed"] = empty(
  1564. $order["items"][$itemIndex]["is_processed"]
  1565. );
  1566. $order["updated_at"] = $now;
  1567. $order = refreshOrderState($order);
  1568. saveOrders($orders);
  1569. return ["success" => true, "order" => $order];
  1570. }
  1571. unset($order);
  1572. return ["success" => false, "message" => "Bestellung nicht gefunden."];
  1573. }
  1574. function cancelOrder($orderId, $adminUsername, $reason = "")
  1575. {
  1576. $orders = getOrders();
  1577. $now = date("Y-m-d H:i:s");
  1578. $adminUsername = normalizeAdminUsername($adminUsername);
  1579. $reason = trim((string) $reason);
  1580. foreach ($orders as &$order) {
  1581. if ($order["id"] !== $orderId) {
  1582. continue;
  1583. }
  1584. if ($order["status"] === "cancelled") {
  1585. return [
  1586. "success" => false,
  1587. "message" => "Die Bestellung ist bereits storniert.",
  1588. ];
  1589. }
  1590. $order["status"] = "cancelled";
  1591. $order["cancelled_at"] = $now;
  1592. $order["cancelled_by"] = $adminUsername;
  1593. $order["cancellation_reason"] = $reason;
  1594. $order["updated_at"] = $now;
  1595. foreach ($order["items"] as &$item) {
  1596. $item["backorder_status"] = "";
  1597. $item["backordered_at"] = "";
  1598. $item["ordered_at"] = "";
  1599. }
  1600. unset($item);
  1601. saveOrders($orders);
  1602. return ["success" => true, "order" => $order];
  1603. }
  1604. unset($order);
  1605. return ["success" => false, "message" => "Bestellung nicht gefunden."];
  1606. }
  1607. function uncancelOrder($orderId)
  1608. {
  1609. $orders = getOrders();
  1610. $now = date("Y-m-d H:i:s");
  1611. foreach ($orders as &$order) {
  1612. if ($order["id"] !== $orderId) {
  1613. continue;
  1614. }
  1615. if ($order["status"] !== "cancelled") {
  1616. return [
  1617. "success" => false,
  1618. "message" => "Die Bestellung ist nicht storniert.",
  1619. ];
  1620. }
  1621. $order["cancelled_at"] = "";
  1622. $order["cancelled_by"] = "";
  1623. $order["cancellation_reason"] = "";
  1624. $order["status"] = "open";
  1625. $order["updated_at"] = $now;
  1626. $order = refreshOrderState($order);
  1627. saveOrders($orders);
  1628. return ["success" => true, "order" => $order];
  1629. }
  1630. unset($order);
  1631. return ["success" => false, "message" => "Bestellung nicht gefunden."];
  1632. }
  1633. function orderItemCanBeManaged($order)
  1634. {
  1635. if (($order["status"] ?? "") === "cancelled") {
  1636. return [
  1637. "success" => false,
  1638. "message" =>
  1639. "Stornierte Bestellungen können nicht mehr bearbeitet werden.",
  1640. ];
  1641. }
  1642. return ["success" => true];
  1643. }
  1644. function setOrderItemBackorderStatus($orderId, $itemIndex, $status)
  1645. {
  1646. if (!isValidBackorderStatusForAdminMarking($status)) {
  1647. return ["success" => false, "message" => "Ungültiger Nachbestellstatus."];
  1648. }
  1649. $orders = getOrders();
  1650. $now = date("Y-m-d H:i:s");
  1651. foreach ($orders as &$order) {
  1652. if ($order["id"] !== $orderId) {
  1653. continue;
  1654. }
  1655. $guard = orderItemCanBeManaged($order);
  1656. if (!$guard["success"]) {
  1657. return $guard;
  1658. }
  1659. if (!isset($order["items"][$itemIndex])) {
  1660. return [
  1661. "success" => false,
  1662. "message" => "Position nicht gefunden.",
  1663. ];
  1664. }
  1665. if ($status === backorderStatusToBeBackordered()) {
  1666. if (!empty($order["items"][$itemIndex]["is_processed"])) {
  1667. return [
  1668. "success" => false,
  1669. "message" =>
  1670. "Bearbeitete Positionen können nicht als Nachbestellung markiert werden.",
  1671. ];
  1672. }
  1673. $order["items"][$itemIndex]["backorder_status"] =
  1674. backorderStatusToBeBackordered();
  1675. $order["items"][$itemIndex]["backordered_at"] = $now;
  1676. $order["items"][$itemIndex]["ordered_at"] = "";
  1677. } else {
  1678. $order["items"][$itemIndex]["backorder_status"] = backorderStatusEmpty();
  1679. $order["items"][$itemIndex]["backordered_at"] = "";
  1680. $order["items"][$itemIndex]["ordered_at"] = "";
  1681. }
  1682. $order["updated_at"] = $now;
  1683. saveOrders($orders);
  1684. return ["success" => true, "order" => $order];
  1685. }
  1686. unset($order);
  1687. return ["success" => false, "message" => "Bestellung nicht gefunden."];
  1688. }
  1689. function toggleOrderItemBackorder($orderId, $itemIndex)
  1690. {
  1691. $orders = getOrders();
  1692. foreach ($orders as $order) {
  1693. if ($order["id"] !== $orderId) {
  1694. continue;
  1695. }
  1696. if (!isset($order["items"][$itemIndex])) {
  1697. return [
  1698. "success" => false,
  1699. "message" => "Position nicht gefunden.",
  1700. ];
  1701. }
  1702. $current = (string) ($order["items"][$itemIndex]["backorder_status"] ?? "");
  1703. $newStatus = $current === "to_be_backordered" ? "" : "to_be_backordered";
  1704. return setOrderItemBackorderStatus($orderId, $itemIndex, $newStatus);
  1705. }
  1706. return ["success" => false, "message" => "Bestellung nicht gefunden."];
  1707. }
  1708. function getManualBackorders()
  1709. {
  1710. $data = readJsonFile(MANUAL_BACKORDERS_FILE);
  1711. $entries =
  1712. isset($data["entries"]) && is_array($data["entries"])
  1713. ? $data["entries"]
  1714. : [];
  1715. $normalized = [];
  1716. foreach ($entries as $entry) {
  1717. if (!is_array($entry)) {
  1718. continue;
  1719. }
  1720. $id = trim((string) ($entry["id"] ?? ""));
  1721. $productId = (int) ($entry["product_id"] ?? 0);
  1722. $productName = trim((string) ($entry["product_name"] ?? ""));
  1723. $size = trim((string) ($entry["size"] ?? ""));
  1724. $status = trim((string) ($entry["backorder_status"] ?? ""));
  1725. if ($id === "" || $productId <= 0 || $productName === "" || $status === "") {
  1726. continue;
  1727. }
  1728. if (!in_array($status, ["to_be_backordered", "ordered"], true)) {
  1729. continue;
  1730. }
  1731. $normalized[] = [
  1732. "id" => $id,
  1733. "product_id" => $productId,
  1734. "product_name" => $productName,
  1735. "size" => $size,
  1736. "backorder_status" => $status,
  1737. "backordered_at" => trim((string) ($entry["backordered_at"] ?? "")),
  1738. "ordered_at" => trim((string) ($entry["ordered_at"] ?? "")),
  1739. "created_at" => trim((string) ($entry["created_at"] ?? "")),
  1740. ];
  1741. }
  1742. return $normalized;
  1743. }
  1744. function saveManualBackorders($entries)
  1745. {
  1746. return writeJsonFile(MANUAL_BACKORDERS_FILE, [
  1747. "entries" => array_values($entries),
  1748. ]);
  1749. }
  1750. function generateManualBackorderId()
  1751. {
  1752. return "mb-" . date("YmdHis") . "-" . bin2hex(random_bytes(4));
  1753. }
  1754. function addManualBackorderItems($productId, $size, $quantity)
  1755. {
  1756. $productId = (int) $productId;
  1757. $size = trim((string) $size);
  1758. $quantity = (int) $quantity;
  1759. if ($productId <= 0 || $quantity <= 0) {
  1760. return [
  1761. "success" => false,
  1762. "message" => "Ungültige Menge oder Artikel.",
  1763. ];
  1764. }
  1765. if ($quantity > 100) {
  1766. return [
  1767. "success" => false,
  1768. "message" => "Maximal 100 Positionen auf einmal.",
  1769. ];
  1770. }
  1771. $product = getProductById($productId);
  1772. if ($product === null) {
  1773. return ["success" => false, "message" => "Artikel nicht gefunden."];
  1774. }
  1775. $allowedSizes = getProductSizes($product);
  1776. if (empty($allowedSizes)) {
  1777. $allowedSizes = ["Standard"];
  1778. }
  1779. if (!in_array($size, $allowedSizes, true)) {
  1780. return ["success" => false, "message" => "Ungültige Größe für diesen Artikel."];
  1781. }
  1782. $entries = getManualBackorders();
  1783. $now = date("Y-m-d H:i:s");
  1784. for ($i = 0; $i < $quantity; $i++) {
  1785. $entries[] = [
  1786. "id" => generateManualBackorderId(),
  1787. "product_id" => $productId,
  1788. "product_name" => $product["name"],
  1789. "size" => $size,
  1790. "backorder_status" => "to_be_backordered",
  1791. "backordered_at" => $now,
  1792. "ordered_at" => "",
  1793. "created_at" => $now,
  1794. ];
  1795. }
  1796. if (!saveManualBackorders($entries)) {
  1797. return [
  1798. "success" => false,
  1799. "message" => "Nachbestellungen konnten nicht gespeichert werden.",
  1800. ];
  1801. }
  1802. return ["success" => true, "added" => $quantity];
  1803. }
  1804. function collectBackorderItemRefs()
  1805. {
  1806. $refs = [];
  1807. foreach (getManualBackorders() as $entry) {
  1808. $refs[] = [
  1809. "order_id" => "",
  1810. "item_index" => 0,
  1811. "manual_id" => $entry["id"],
  1812. "is_manual" => true,
  1813. "product_id" => $entry["product_id"],
  1814. "product_name" => $entry["product_name"],
  1815. "size" => $entry["size"],
  1816. "backorder_status" => $entry["backorder_status"],
  1817. "created_at" => $entry["created_at"] !== "" ? $entry["created_at"] : $entry["backordered_at"],
  1818. "sort_at" =>
  1819. $entry["backorder_status"] === "ordered"
  1820. ? ($entry["ordered_at"] !== ""
  1821. ? $entry["ordered_at"]
  1822. : $entry["created_at"])
  1823. : ($entry["backordered_at"] !== ""
  1824. ? $entry["backordered_at"]
  1825. : $entry["created_at"]),
  1826. ];
  1827. }
  1828. foreach (getOrders() as $order) {
  1829. if (($order["status"] ?? "") === "cancelled") {
  1830. continue;
  1831. }
  1832. foreach ($order["items"] as $itemIndex => $item) {
  1833. $status = (string) ($item["backorder_status"] ?? "");
  1834. if ($status === "") {
  1835. continue;
  1836. }
  1837. $refs[] = [
  1838. "order_id" => $order["id"],
  1839. "item_index" => (int) $itemIndex,
  1840. "product_id" => (int) $item["product_id"],
  1841. "product_name" => $item["product_name"],
  1842. "size" => $item["size"],
  1843. "backorder_status" => $status,
  1844. "created_at" => $order["created_at"],
  1845. "sort_at" =>
  1846. $status === "ordered"
  1847. ? ($item["ordered_at"] !== ""
  1848. ? $item["ordered_at"]
  1849. : $order["created_at"])
  1850. : ($item["backordered_at"] !== ""
  1851. ? $item["backordered_at"]
  1852. : $order["created_at"]),
  1853. ];
  1854. }
  1855. }
  1856. return $refs;
  1857. }
  1858. function compareBackorderRefs(array $left, array $right): int
  1859. {
  1860. $cmp = strcmp((string) ($left["sort_at"] ?? ""), (string) ($right["sort_at"] ?? ""));
  1861. if ($cmp !== 0) {
  1862. return $cmp;
  1863. }
  1864. $cmp = strcmp((string) ($left["order_id"] ?? ""), (string) ($right["order_id"] ?? ""));
  1865. if ($cmp !== 0) {
  1866. return $cmp;
  1867. }
  1868. return strcmp((string) ($left["manual_id"] ?? ""), (string) ($right["manual_id"] ?? ""));
  1869. }
  1870. function getBackorderGroups()
  1871. {
  1872. $refs = collectBackorderItemRefs();
  1873. $groups = [];
  1874. foreach ($refs as $ref) {
  1875. $key = $ref["product_id"] . "|" . $ref["size"];
  1876. if (!isset($groups[$key])) {
  1877. $groups[$key] = [
  1878. "product_id" => $ref["product_id"],
  1879. "product_name" => $ref["product_name"],
  1880. "size" => $ref["size"],
  1881. "to_be_backordered" => 0,
  1882. "ordered" => 0,
  1883. "items_to_be_backordered" => [],
  1884. "items_ordered" => [],
  1885. ];
  1886. }
  1887. if ($ref["backorder_status"] === "to_be_backordered") {
  1888. $groups[$key]["to_be_backordered"]++;
  1889. $groups[$key]["items_to_be_backordered"][] = $ref;
  1890. } elseif ($ref["backorder_status"] === "ordered") {
  1891. $groups[$key]["ordered"]++;
  1892. $groups[$key]["items_ordered"][] = $ref;
  1893. }
  1894. }
  1895. foreach ($groups as &$group) {
  1896. usort($group["items_to_be_backordered"], "compareBackorderRefs");
  1897. usort($group["items_ordered"], "compareBackorderRefs");
  1898. }
  1899. unset($group);
  1900. $result = array_values($groups);
  1901. usort($result, function ($left, $right) {
  1902. $cmp = strcmp($left["product_name"], $right["product_name"]);
  1903. if ($cmp !== 0) {
  1904. return $cmp;
  1905. }
  1906. return strcmp($left["size"], $right["size"]);
  1907. });
  1908. return $result;
  1909. }
  1910. function applyBackorderBulkUpdate($productId, $size, $fromStatus, $toStatus, $quantity)
  1911. {
  1912. $productId = (int) $productId;
  1913. $size = trim((string) $size);
  1914. $quantity = (int) $quantity;
  1915. if ($productId <= 0 || $quantity <= 0) {
  1916. return [
  1917. "success" => false,
  1918. "message" => "Ungültige Menge oder Artikel.",
  1919. ];
  1920. }
  1921. $refs = collectBackorderItemRefs();
  1922. $candidates = [];
  1923. foreach ($refs as $ref) {
  1924. if (
  1925. $ref["product_id"] !== $productId ||
  1926. $ref["size"] !== $size ||
  1927. $ref["backorder_status"] !== $fromStatus
  1928. ) {
  1929. continue;
  1930. }
  1931. $candidates[] = $ref;
  1932. }
  1933. usort($candidates, "compareBackorderRefs");
  1934. if ($quantity > count($candidates)) {
  1935. return [
  1936. "success" => false,
  1937. "message" =>
  1938. "Nur " .
  1939. count($candidates) .
  1940. " Position(en) verfügbar, " .
  1941. $quantity .
  1942. " angefordert.",
  1943. ];
  1944. }
  1945. $targets = array_slice($candidates, 0, $quantity);
  1946. $orders = getOrders();
  1947. $manualEntries = getManualBackorders();
  1948. $manualChanged = false;
  1949. $now = date("Y-m-d H:i:s");
  1950. $updated = 0;
  1951. foreach ($targets as $target) {
  1952. if (!empty($target["is_manual"])) {
  1953. $manualId = (string) ($target["manual_id"] ?? "");
  1954. foreach ($manualEntries as &$entry) {
  1955. if ($entry["id"] !== $manualId) {
  1956. continue;
  1957. }
  1958. if ($toStatus === "ordered") {
  1959. $entry["backorder_status"] = "ordered";
  1960. $entry["ordered_at"] = $now;
  1961. } else {
  1962. $entry["backorder_status"] = "";
  1963. $entry["ordered_at"] = "";
  1964. }
  1965. $manualChanged = true;
  1966. $updated++;
  1967. break;
  1968. }
  1969. unset($entry);
  1970. continue;
  1971. }
  1972. foreach ($orders as &$order) {
  1973. if ($order["id"] !== $target["order_id"]) {
  1974. continue;
  1975. }
  1976. $itemIndex = $target["item_index"];
  1977. if (!isset($order["items"][$itemIndex])) {
  1978. continue 2;
  1979. }
  1980. if ($toStatus === backorderStatusOrdered()) {
  1981. $order["items"][$itemIndex]["backorder_status"] = backorderStatusOrdered();
  1982. $order["items"][$itemIndex]["ordered_at"] = $now;
  1983. } else {
  1984. $order["items"][$itemIndex]["backorder_status"] = backorderStatusEmpty();
  1985. $order["items"][$itemIndex]["ordered_at"] = "";
  1986. }
  1987. $order["updated_at"] = $now;
  1988. $updated++;
  1989. break;
  1990. }
  1991. unset($order);
  1992. }
  1993. if ($updated === 0) {
  1994. return [
  1995. "success" => false,
  1996. "message" => "Keine Positionen aktualisiert.",
  1997. ];
  1998. }
  1999. if ($manualChanged) {
  2000. $manualEntries = array_values(
  2001. array_filter($manualEntries, function ($entry) {
  2002. return ($entry["backorder_status"] ?? "") !== "";
  2003. }),
  2004. );
  2005. if (!saveManualBackorders($manualEntries)) {
  2006. return [
  2007. "success" => false,
  2008. "message" => "Manuelle Nachbestellungen konnten nicht gespeichert werden.",
  2009. ];
  2010. }
  2011. }
  2012. saveOrders($orders);
  2013. return ["success" => true, "updated" => $updated];
  2014. }
  2015. function markBackorderItemsOrdered($productId, $size, $quantity)
  2016. {
  2017. return applyBackorderBulkUpdate(
  2018. $productId,
  2019. $size,
  2020. "to_be_backordered",
  2021. "ordered",
  2022. $quantity,
  2023. );
  2024. }
  2025. function markBackorderItemsDelivered($productId, $size, $quantity)
  2026. {
  2027. return applyBackorderBulkUpdate($productId, $size, "ordered", "", $quantity);
  2028. }
  2029. function orderHasBackorder($order)
  2030. {
  2031. if (!is_array($order["items"] ?? null)) {
  2032. return false;
  2033. }
  2034. foreach ($order["items"] as $item) {
  2035. if (($item["backorder_status"] ?? "") !== "") {
  2036. return true;
  2037. }
  2038. }
  2039. return false;
  2040. }
  2041. function getOrderOpenBackorderSummary($order)
  2042. {
  2043. $statuses = [];
  2044. if (!is_array($order["items"] ?? null)) {
  2045. return ["label" => "", "class" => ""];
  2046. }
  2047. foreach ($order["items"] as $item) {
  2048. if (!empty($item["is_processed"])) {
  2049. continue;
  2050. }
  2051. $status = trim((string) ($item["backorder_status"] ?? ""));
  2052. if ($status !== "") {
  2053. $statuses[$status] = true;
  2054. }
  2055. }
  2056. if ($statuses === []) {
  2057. return ["label" => "", "class" => ""];
  2058. }
  2059. if (count($statuses) > 1) {
  2060. return ["label" => "Gemischt", "class" => "status-backorder"];
  2061. }
  2062. $status = array_key_first($statuses);
  2063. return [
  2064. "label" => getBackorderStatusLabel($status),
  2065. "class" => getBackorderStatusClass($status),
  2066. ];
  2067. }
  2068. function getBackorderStatusLabel($status)
  2069. {
  2070. switch ((string) $status) {
  2071. case "to_be_backordered":
  2072. return "Nachzubestellen";
  2073. case "ordered":
  2074. return "Wartet auf Lieferung";
  2075. default:
  2076. return "-";
  2077. }
  2078. }
  2079. function getBackorderStatusClass($status)
  2080. {
  2081. switch ((string) $status) {
  2082. case "to_be_backordered":
  2083. return "status-backorder";
  2084. case "ordered":
  2085. return "status-backorder-waiting";
  2086. default:
  2087. return "";
  2088. }
  2089. }
  2090. function getOrderStatusLabel($order)
  2091. {
  2092. if (($order["status"] ?? "") === "cancelled") {
  2093. return "Storniert";
  2094. }
  2095. if (($order["status"] ?? "") === "processed") {
  2096. return "Bearbeitet";
  2097. }
  2098. if (($order["status"] ?? "") === "partial") {
  2099. return "Teilweise bearbeitet";
  2100. }
  2101. return "Offen";
  2102. }
  2103. function getOrderStatusClass($order)
  2104. {
  2105. if (($order["status"] ?? "") === "cancelled") {
  2106. return "status-cancelled";
  2107. }
  2108. if (($order["status"] ?? "") === "processed") {
  2109. return "status-processed";
  2110. }
  2111. if (($order["status"] ?? "") === "partial") {
  2112. return "status-partial";
  2113. }
  2114. return "status-open";
  2115. }
  2116. function formatDate($dateString)
  2117. {
  2118. $dateString = trim((string) $dateString);
  2119. if ($dateString === "") {
  2120. return "-";
  2121. }
  2122. try {
  2123. $date = new DateTimeImmutable($dateString);
  2124. return $date->format("d.m.Y H:i");
  2125. } catch (Exception $exception) {
  2126. return $dateString;
  2127. }
  2128. }
  2129. function getCart()
  2130. {
  2131. $cart = $_SESSION["cart"] ?? [];
  2132. if (!is_array($cart)) {
  2133. $cart = [];
  2134. }
  2135. $normalized = [];
  2136. foreach ($cart as $item) {
  2137. $productId = isset($item["product_id"]) ? (int) $item["product_id"] : 0;
  2138. $size = trim((string) ($item["size"] ?? ""));
  2139. $product = getProductById($productId);
  2140. if ($product === null) {
  2141. continue;
  2142. }
  2143. $sizes = getProductSizes($product);
  2144. if (!empty($sizes)) {
  2145. if ($size === "" || !in_array($size, $sizes, true)) {
  2146. continue;
  2147. }
  2148. } else {
  2149. $size = "";
  2150. }
  2151. if (isset($normalized[$productId])) {
  2152. unset($normalized[$productId]);
  2153. }
  2154. $normalized[$productId] = [
  2155. "product_id" => $productId,
  2156. "size" => $size,
  2157. ];
  2158. }
  2159. $_SESSION["cart"] = array_values($normalized);
  2160. return $_SESSION["cart"];
  2161. }
  2162. function addCartItem($productId, $size = "")
  2163. {
  2164. $productId = (int) $productId;
  2165. $size = trim((string) $size);
  2166. $product = getProductById($productId);
  2167. if ($product === null) {
  2168. return [
  2169. "success" => false,
  2170. "status" => "error",
  2171. ];
  2172. }
  2173. $sizes = getProductSizes($product);
  2174. if (!empty($sizes)) {
  2175. if ($size === "" || !in_array($size, $sizes, true)) {
  2176. return [
  2177. "success" => false,
  2178. "status" => "error",
  2179. ];
  2180. }
  2181. } else {
  2182. $size = "";
  2183. }
  2184. $cart = getCart();
  2185. foreach ($cart as $index => $item) {
  2186. if ((int) $item["product_id"] !== $productId) {
  2187. continue;
  2188. }
  2189. $existingSize = trim((string) ($item["size"] ?? ""));
  2190. if ($existingSize === $size) {
  2191. return [
  2192. "success" => true,
  2193. "status" => "unchanged",
  2194. "size" => $size,
  2195. ];
  2196. }
  2197. $cart[$index]["size"] = $size;
  2198. $_SESSION["cart"] = array_values($cart);
  2199. return [
  2200. "success" => true,
  2201. "status" => "replaced",
  2202. "size" => $size,
  2203. "previous_size" => $existingSize,
  2204. ];
  2205. }
  2206. $cart[] = [
  2207. "product_id" => $productId,
  2208. "size" => $size,
  2209. ];
  2210. $_SESSION["cart"] = array_values($cart);
  2211. return [
  2212. "success" => true,
  2213. "status" => "added",
  2214. "size" => $size,
  2215. ];
  2216. }
  2217. function removeCartItem($productId, $size)
  2218. {
  2219. $productId = (int) $productId;
  2220. $size = trim((string) $size);
  2221. $cart = getCart();
  2222. $filtered = [];
  2223. foreach ($cart as $item) {
  2224. $itemProductId = (int) ($item["product_id"] ?? 0);
  2225. $itemSize = trim((string) ($item["size"] ?? ""));
  2226. if ($itemProductId === $productId && $itemSize === $size) {
  2227. continue;
  2228. }
  2229. $filtered[] = $item;
  2230. }
  2231. $_SESSION["cart"] = array_values($filtered);
  2232. }
  2233. function clearCart()
  2234. {
  2235. $_SESSION["cart"] = [];
  2236. }
  2237. function getCartItemsDetailed()
  2238. {
  2239. $items = [];
  2240. foreach (getCart() as $cartItem) {
  2241. $product = getProductById($cartItem["product_id"]);
  2242. if ($product === null) {
  2243. continue;
  2244. }
  2245. $size = trim((string) ($cartItem["size"] ?? ""));
  2246. $items[] = [
  2247. "product" => $product,
  2248. "size" => $size,
  2249. "availability_label" =>
  2250. $size !== "" ? getAvailabilityLabel($product, $size) : "",
  2251. ];
  2252. }
  2253. return $items;
  2254. }
  2255. function buildOrderItemsFromCart()
  2256. {
  2257. $items = [];
  2258. foreach (getCart() as $cartItem) {
  2259. $product = getProductById($cartItem["product_id"]);
  2260. if ($product === null) {
  2261. continue;
  2262. }
  2263. $size = trim((string) ($cartItem["size"] ?? ""));
  2264. $items[] = [
  2265. "product_id" => $product["id"],
  2266. "size" => $size,
  2267. "is_processed" => false,
  2268. ];
  2269. }
  2270. return normalizeOrderItems($items);
  2271. }
  2272. function buildOrderItemsHtml($order)
  2273. {
  2274. $parts = [];
  2275. foreach ($order["items"] as $item) {
  2276. $label = "<strong>" . escape($item["product_name"]) . "</strong>";
  2277. if ($item["size"] !== "") {
  2278. $label .= " - Größe: " . escape($item["size"]);
  2279. }
  2280. if (!empty($item["availability_label"])) {
  2281. $label .=
  2282. "<br><small>" .
  2283. nl2br(escape($item["availability_label"])) .
  2284. "</small>";
  2285. }
  2286. $parts[] =
  2287. '<li style="margin: 0 0 0.75rem 0; padding: 0.9rem 1rem; background: #f8f4e7; border: 1px solid #d7ceb5; border-radius: 18px; color: #111111;">' .
  2288. $label .
  2289. "</li>";
  2290. }
  2291. return '<ul style="list-style: none; margin: 0; padding: 0;">' .
  2292. implode("", $parts) .
  2293. "</ul>";
  2294. }
  2295. function buildOrderSummaryHtml($order, $title, $introHtml, $extraHtml = "")
  2296. {
  2297. $itemsHtml = buildOrderItemsHtml($order);
  2298. return '
  2299. <html>
  2300. <head>
  2301. <meta charset="UTF-8">
  2302. </head>
  2303. <body style="font-family: \'Freising Sans\', Arial, sans-serif; line-height: 1.6; color: #111111; background: #f4efe1; padding: 1.5rem;">
  2304. <div style="max-width: 720px; margin: 0 auto; background: #ffffff; padding: 2rem; border-radius: 28px; border: 1px solid #d7ceb5; box-shadow: 0 18px 40px rgba(16, 16, 16, 0.08);">
  2305. <p style="margin: 0 0 0.5rem; font-size: 0.8rem; letter-spacing: 0.08em; text-transform: uppercase; color: #5e5a4d;">' .
  2306. escape(SITE_DEPARTMENT_NAME) .
  2307. '</p>
  2308. <h1 style="margin: 0; font-size: 1.75rem; line-height: 1.2; color: #111111;">' .
  2309. escape(SITE_NAME) .
  2310. '</h1>
  2311. <p style="margin: 0.25rem 0 1.5rem; font-size: 1rem; color: #5e5a4d;">' .
  2312. escape(SITE_SERVICE_HEADER) .
  2313. '</p>
  2314. <div style="width: 80px; height: 6px; border-radius: 999px; background: #ffd71c; margin-bottom: 1.5rem;"></div>
  2315. <h2 style="color: #111111; margin-top: 0;">' .
  2316. escape($title) .
  2317. '</h2>
  2318. ' .
  2319. $introHtml .
  2320. '
  2321. <div style="background: #f8f4e7; border: 2px solid #ffd71c; padding: 1.5rem; margin: 1.5rem 0; border-radius: 20px;">
  2322. <h3 style="margin-top: 0;">Bestellnummer</h3>
  2323. <p style="margin: 0; color: #111111; font-family: monospace; font-size: 1.05rem;">' .
  2324. escape($order["id"]) .
  2325. '</p>
  2326. </div>
  2327. <p><strong>Name:</strong> ' .
  2328. escape($order["customer_name"]) .
  2329. '</p>
  2330. <p><strong>E-Mail:</strong> ' .
  2331. escape($order["customer_email"]) .
  2332. '</p>
  2333. <p><strong>Organisation:</strong> ' .
  2334. escape($order["organization_label"]) .
  2335. '</p>
  2336. <p><strong>Erstellt am:</strong> ' .
  2337. escape(formatDate($order["created_at"])) .
  2338. '</p>
  2339. <h3>Bestellte Artikel</h3>
  2340. <div style="background: #fffdf6; border: 1px solid #d7ceb5; border-left: 6px solid #ffd71c; border-radius: 20px; padding: 1rem;">' .
  2341. $itemsHtml .
  2342. '</div>
  2343. <p><strong>Kommentar:</strong><br>' .
  2344. ($order["comment"] !== ""
  2345. ? nl2br(escape($order["comment"]))
  2346. : "Kein Kommentar") .
  2347. '</p>
  2348. ' .
  2349. $extraHtml .
  2350. '
  2351. <p style="margin: 2rem 0 0; color: #5e5a4d; font-size: 0.9rem;">' .
  2352. escape(SITE_NAME) .
  2353. " | " .
  2354. escape(SITE_DEPARTMENT_NAME) .
  2355. "<br>" .
  2356. escape(SITE_ADDRESS_LINE) .
  2357. '</p>
  2358. </div>
  2359. </body>
  2360. </html>';
  2361. }
  2362. function sendOrderCreatedCustomerEmail($order)
  2363. {
  2364. $subject = SITE_SERVICE_NAME . ": Ihre Bestellung - " . $order["id"];
  2365. $intro =
  2366. "<p>Guten Tag " .
  2367. escape($order["customer_name"]) .
  2368. ",</p><p>Ihre Bestellung wurde erfasst und an " .
  2369. escape(SITE_DEPARTMENT_NAME) .
  2370. " weitergeleitet.</p>";
  2371. $message = buildOrderSummaryHtml($order, "Bestellung eingegangen", $intro);
  2372. return sendEmail($order["customer_email"], $subject, $message);
  2373. }
  2374. function sendConfirmedOrderAdminNotification($order)
  2375. {
  2376. $recipient = getOrderRecipientEmail();
  2377. if (!isValidAdminEmail($recipient)) {
  2378. return false;
  2379. }
  2380. $subject = SITE_SERVICE_NAME . ": Neue Bestellung - " . $order["id"];
  2381. $intro =
  2382. "<p>Eine neue PSA-Bestellung ist eingegangen und muss bearbeitet werden.</p>";
  2383. $message = buildOrderSummaryHtml($order, "Neue PSA-Bestellung", $intro);
  2384. $attachments = [];
  2385. if (shouldAttachOrderPdfToAdminEmail()) {
  2386. $attachments[] = [
  2387. "filename" => "bestellung-" . strtolower($order["id"]) . ".pdf",
  2388. "content_type" => "application/pdf",
  2389. "content" => renderOrderPdf($order),
  2390. ];
  2391. }
  2392. return sendEmail($recipient, $subject, $message, true, $attachments);
  2393. }
  2394. function sendEmail($to, $subject, $message, $isHtml = true, $attachments = [])
  2395. {
  2396. $headers = [];
  2397. $headers[] = "From: " . FROM_NAME . " <" . FROM_EMAIL . ">";
  2398. $headers[] = "Reply-To: " . FROM_EMAIL;
  2399. $headers[] = "X-Mailer: PHP/" . phpversion();
  2400. if (empty($attachments)) {
  2401. if ($isHtml) {
  2402. $headers[] = "MIME-Version: 1.0";
  2403. $headers[] = "Content-Type: text/html; charset=UTF-8";
  2404. } else {
  2405. $headers[] = "Content-Type: text/plain; charset=UTF-8";
  2406. }
  2407. return mail($to, $subject, $message, implode("\r\n", $headers));
  2408. }
  2409. $boundary = "=_Boundary_" . bin2hex(random_bytes(8));
  2410. $headers[] = "MIME-Version: 1.0";
  2411. $headers[] = 'Content-Type: multipart/mixed; boundary="' . $boundary . '"';
  2412. $body = [];
  2413. $body[] = "--" . $boundary;
  2414. $body[] =
  2415. "Content-Type: " .
  2416. ($isHtml ? "text/html" : "text/plain") .
  2417. "; charset=UTF-8";
  2418. $body[] = "Content-Transfer-Encoding: 8bit";
  2419. $body[] = "";
  2420. $body[] = $message;
  2421. foreach ($attachments as $attachment) {
  2422. if (!is_array($attachment)) {
  2423. continue;
  2424. }
  2425. $filename = trim(
  2426. (string) ($attachment["filename"] ?? "attachment.bin"),
  2427. );
  2428. $contentType = trim(
  2429. (string) ($attachment["content_type"] ??
  2430. "application/octet-stream"),
  2431. );
  2432. $content = isset($attachment["content"])
  2433. ? (string) $attachment["content"]
  2434. : "";
  2435. $body[] = "--" . $boundary;
  2436. $body[] =
  2437. "Content-Type: " . $contentType . '; name="' . $filename . '"';
  2438. $body[] = "Content-Transfer-Encoding: base64";
  2439. $body[] =
  2440. 'Content-Disposition: attachment; filename="' . $filename . '"';
  2441. $body[] = "";
  2442. $body[] = chunk_split(base64_encode($content));
  2443. }
  2444. $body[] = "--" . $boundary . "--";
  2445. $body[] = "";
  2446. return mail(
  2447. $to,
  2448. $subject,
  2449. implode("\r\n", $body),
  2450. implode("\r\n", $headers),
  2451. );
  2452. }
  2453. function pdfEncodeWinAnsi($text)
  2454. {
  2455. $text = str_replace("\r", "", (string) $text);
  2456. if (!function_exists("iconv")) {
  2457. return preg_replace('/[^\x09\x0A\x20-\x7E]/', "?", $text);
  2458. }
  2459. $chars = preg_split("//u", $text, -1, PREG_SPLIT_NO_EMPTY);
  2460. if (!is_array($chars)) {
  2461. $fallback = @iconv("UTF-8", "Windows-1252//TRANSLIT//IGNORE", $text);
  2462. return is_string($fallback) ? $fallback : $text;
  2463. }
  2464. $result = "";
  2465. foreach ($chars as $char) {
  2466. $converted = @iconv("UTF-8", "Windows-1252", $char);
  2467. if ($converted !== false) {
  2468. $result .= $converted;
  2469. continue;
  2470. }
  2471. $fallback = @iconv("UTF-8", "Windows-1252//TRANSLIT", $char);
  2472. if ($fallback !== false && $fallback !== "") {
  2473. $result .= $fallback;
  2474. continue;
  2475. }
  2476. $result .= "?";
  2477. }
  2478. return $result;
  2479. }
  2480. function pdfEscapeText($text)
  2481. {
  2482. $text = str_replace("\\", "\\\\", $text);
  2483. $text = str_replace("(", "\(", $text);
  2484. $text = str_replace(")", "\)", $text);
  2485. return preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', "", $text);
  2486. }
  2487. function pdfWrapAnsiText($text, $maxChars)
  2488. {
  2489. $lines = [];
  2490. $paragraphs = explode("\n", str_replace("\r", "", (string) $text));
  2491. foreach ($paragraphs as $paragraph) {
  2492. $normalized = trim(preg_replace("/\s+/", " ", $paragraph));
  2493. if ($normalized === "") {
  2494. $lines[] = "";
  2495. continue;
  2496. }
  2497. $words = explode(" ", $normalized);
  2498. $current = "";
  2499. foreach ($words as $word) {
  2500. if ($word === "") {
  2501. continue;
  2502. }
  2503. if (strlen($word) > $maxChars) {
  2504. if ($current !== "") {
  2505. $lines[] = $current;
  2506. $current = "";
  2507. }
  2508. $parts = str_split($word, $maxChars);
  2509. $lastIndex = count($parts) - 1;
  2510. for ($i = 0; $i < $lastIndex; $i++) {
  2511. $lines[] = $parts[$i];
  2512. }
  2513. $current = $parts[$lastIndex];
  2514. continue;
  2515. }
  2516. $candidate = $current === "" ? $word : $current . " " . $word;
  2517. if (strlen($candidate) <= $maxChars) {
  2518. $current = $candidate;
  2519. } else {
  2520. if ($current !== "") {
  2521. $lines[] = $current;
  2522. }
  2523. $current = $word;
  2524. }
  2525. }
  2526. if ($current !== "") {
  2527. $lines[] = $current;
  2528. }
  2529. }
  2530. if (empty($lines)) {
  2531. $lines[] = "";
  2532. }
  2533. return $lines;
  2534. }
  2535. function prepareOrderForDocument(array $order): array
  2536. {
  2537. $items = [];
  2538. foreach ($order["items"] ?? [] as $item) {
  2539. if (!is_array($item)) {
  2540. continue;
  2541. }
  2542. $items[] = [
  2543. "product_name" => trim((string) ($item["product_name"] ?? "")),
  2544. "size" => trim((string) ($item["size"] ?? "")),
  2545. "availability_label" => trim(
  2546. (string) ($item["availability_label"] ?? ""),
  2547. ),
  2548. ];
  2549. }
  2550. return [
  2551. "id" => trim((string) ($order["id"] ?? "")),
  2552. "created_at" => trim((string) ($order["created_at"] ?? "")),
  2553. "customer_name" => trim((string) ($order["customer_name"] ?? "")),
  2554. "customer_email" => trim((string) ($order["customer_email"] ?? "")),
  2555. "organization_label" => trim(
  2556. (string) ($order["organization_label"] ?? ""),
  2557. ),
  2558. "comment" => (string) ($order["comment"] ?? ""),
  2559. "items" => $items,
  2560. ];
  2561. }
  2562. function renderOrderPdf(array $order): string
  2563. {
  2564. return generateOrderPdf(prepareOrderForDocument($order));
  2565. }
  2566. function streamOrderPdf(
  2567. array $order,
  2568. string $filename,
  2569. bool $inline = true,
  2570. ): void {
  2571. $pdf = renderOrderPdf($order);
  2572. $safeFilename = preg_replace('/[^A-Za-z0-9._-]+/', "-", $filename) ?: "bestellung.pdf";
  2573. $disposition = $inline ? "inline" : "attachment";
  2574. header("Content-Type: application/pdf");
  2575. header(
  2576. 'Content-Disposition: ' .
  2577. $disposition .
  2578. '; filename="' .
  2579. $safeFilename .
  2580. '"',
  2581. );
  2582. header("Content-Length: " . strlen($pdf));
  2583. echo $pdf;
  2584. exit();
  2585. }
  2586. function generateOrderPdf($order)
  2587. {
  2588. $pageWidth = 595;
  2589. $pageHeight = 842;
  2590. $leftMargin = 45;
  2591. $topY = 800;
  2592. $bottomY = 60;
  2593. $lineHeight = 14;
  2594. $itemLineHeight = 16;
  2595. $pages = [];
  2596. $pageContent = "";
  2597. $y = $topY;
  2598. $pageNumber = 0;
  2599. $encodeText = function ($text) {
  2600. return pdfEncodeWinAnsi((string) $text);
  2601. };
  2602. $orderId = $encodeText($order["id"]);
  2603. $createdAt = $encodeText(formatDate($order["created_at"]));
  2604. $customerName = $encodeText($order["customer_name"]);
  2605. $customerEmail = $encodeText($order["customer_email"]);
  2606. $organization = $encodeText($order["organization_label"]);
  2607. $commentRaw = (string) $order["comment"];
  2608. $writeText = function ($x, $y, $encodedText, $fontSize = 12) use (&$pageContent) {
  2609. $pageContent .=
  2610. "BT\n/F1 " .
  2611. $fontSize .
  2612. " Tf\n1 0 0 1 " .
  2613. number_format($x, 2, ".", "") .
  2614. " " .
  2615. number_format($y, 2, ".", "") .
  2616. " Tm\n(" .
  2617. pdfEscapeText($encodedText) .
  2618. ") Tj\nET\n";
  2619. };
  2620. $startPage = function () use (
  2621. &$pages,
  2622. &$pageContent,
  2623. &$y,
  2624. &$pageNumber,
  2625. $topY,
  2626. $leftMargin,
  2627. $lineHeight,
  2628. $orderId,
  2629. $createdAt,
  2630. $writeText,
  2631. $encodeText
  2632. ) {
  2633. if ($pageContent !== "") {
  2634. $pages[] = $pageContent;
  2635. }
  2636. $pageNumber++;
  2637. $pageContent = "";
  2638. $y = $topY;
  2639. $headerLine = "Bestellung: " . $orderId;
  2640. if ($pageNumber > 1) {
  2641. $headerLine .= " | Seite " . $encodeText((string) $pageNumber);
  2642. }
  2643. $writeText($leftMargin, $y, $headerLine, 14);
  2644. $y -= 19;
  2645. $writeText($leftMargin, $y, "Erstellt am: " . $createdAt, 11);
  2646. $y -= 20;
  2647. };
  2648. $ensureSpace = function ($requiredHeight) use (&$y, $bottomY, $startPage) {
  2649. if ($y - $requiredHeight < $bottomY) {
  2650. $startPage();
  2651. }
  2652. };
  2653. $writeWrapped = function (
  2654. $encodedText,
  2655. $maxChars,
  2656. $fontSize = 11,
  2657. $x = null,
  2658. $spacing = null
  2659. ) use (&$y, $lineHeight, $leftMargin, $writeText, $ensureSpace) {
  2660. $targetX = $x === null ? $leftMargin : $x;
  2661. $step = $spacing === null ? $lineHeight : $spacing;
  2662. $lines = pdfWrapAnsiText($encodedText, $maxChars);
  2663. foreach ($lines as $line) {
  2664. $ensureSpace($step);
  2665. $writeText($targetX, $y, $line, $fontSize);
  2666. $y -= $step;
  2667. }
  2668. };
  2669. $writeSectionTitle = function ($titleText, $fontSize = 13) use (
  2670. &$y,
  2671. $leftMargin,
  2672. $writeText,
  2673. $ensureSpace,
  2674. $encodeText
  2675. ) {
  2676. $ensureSpace(24);
  2677. $writeText($leftMargin, $y, $encodeText($titleText), $fontSize);
  2678. $y -= 18;
  2679. };
  2680. $startPage();
  2681. $writeSectionTitle("Gehört zu");
  2682. $writeWrapped("Name: " . $customerName, 80);
  2683. $writeWrapped("Organisation: " . $organization, 80);
  2684. $writeWrapped("E-Mail: " . $customerEmail, 80);
  2685. $y -= 6;
  2686. $writeSectionTitle("Artikelliste", 15);
  2687. $itemNumber = 1;
  2688. if (empty($order["items"])) {
  2689. $writeWrapped($encodeText("Keine Artikel"), 80, 12);
  2690. } else {
  2691. foreach ($order["items"] as $item) {
  2692. $itemName = $encodeText($item["product_name"]);
  2693. $sizeLabel = $encodeText($item["size"]);
  2694. $hintLabel = $encodeText(
  2695. preg_replace("/\s+/", " ", (string) $item["availability_label"]),
  2696. );
  2697. $writeWrapped(
  2698. $encodeText($itemNumber . ". ") . $itemName,
  2699. 68,
  2700. 14,
  2701. null,
  2702. $itemLineHeight,
  2703. );
  2704. if ($sizeLabel !== "") {
  2705. $writeWrapped(
  2706. $encodeText(" Größe: ") . $sizeLabel,
  2707. 66,
  2708. 12,
  2709. null,
  2710. $itemLineHeight,
  2711. );
  2712. }
  2713. if ($hintLabel !== "") {
  2714. $writeWrapped(
  2715. $encodeText(" Hinweis: ") . $hintLabel,
  2716. 66,
  2717. 12,
  2718. null,
  2719. $itemLineHeight,
  2720. );
  2721. }
  2722. $ensureSpace(40);
  2723. $y -= 40;
  2724. $itemNumber++;
  2725. }
  2726. }
  2727. $y -= 4;
  2728. $writeSectionTitle("Kommentar");
  2729. if (trim($commentRaw) === "") {
  2730. $writeWrapped($encodeText("Kein Kommentar"), 80);
  2731. } else {
  2732. foreach (preg_split('/\r\n|\r|\n/', $commentRaw) as $commentLine) {
  2733. $writeWrapped($encodeText($commentLine), 82);
  2734. }
  2735. }
  2736. $y -= 6;
  2737. $writeSectionTitle("Lagerbearbeitung");
  2738. $warehouseLines = [
  2739. "Ausgegeben am / durch: __________________________________________________",
  2740. "[ ] Vollständig ausgegeben",
  2741. "[ ] Teilweise ausgegeben",
  2742. ];
  2743. foreach ($warehouseLines as $line) {
  2744. $writeWrapped($encodeText($line), 80);
  2745. }
  2746. if ($pageContent !== "") {
  2747. $pages[] = $pageContent;
  2748. }
  2749. if (empty($pages)) {
  2750. $pages[] = "";
  2751. }
  2752. $fontObjectNumber = 3;
  2753. $objects = [];
  2754. $objects[1] = "1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n";
  2755. $objects[
  2756. $fontObjectNumber
  2757. ] = "3 0 obj\n<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>\nendobj\n";
  2758. $kids = [];
  2759. $nextObjectNumber = 4;
  2760. foreach ($pages as $pageStream) {
  2761. $pageObjectNumber = $nextObjectNumber++;
  2762. $contentObjectNumber = $nextObjectNumber++;
  2763. $kids[] = $pageObjectNumber . " 0 R";
  2764. $objects[$pageObjectNumber] =
  2765. $pageObjectNumber .
  2766. " 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 " .
  2767. $pageWidth .
  2768. " " .
  2769. $pageHeight .
  2770. "] /Contents " .
  2771. $contentObjectNumber .
  2772. " 0 R /Resources << /Font << /F1 " .
  2773. $fontObjectNumber .
  2774. " 0 R >> >> >>\nendobj\n";
  2775. $objects[$contentObjectNumber] =
  2776. $contentObjectNumber .
  2777. " 0 obj\n<< /Length " .
  2778. strlen($pageStream) .
  2779. " >>\nstream\n" .
  2780. $pageStream .
  2781. "\nendstream\nendobj\n";
  2782. }
  2783. $objects[2] =
  2784. "2 0 obj\n<< /Type /Pages /Kids [" .
  2785. implode(" ", $kids) .
  2786. "] /Count " .
  2787. count($kids) .
  2788. " >>\nendobj\n";
  2789. ksort($objects);
  2790. $pdf = "%PDF-1.4\n";
  2791. $offsets = [0];
  2792. foreach ($objects as $number => $objectContent) {
  2793. $offsets[$number] = strlen($pdf);
  2794. $pdf .= $objectContent;
  2795. }
  2796. $lastObjectNumber = (int) max(array_keys($objects));
  2797. $xrefOffset = strlen($pdf);
  2798. $pdf .= "xref\n0 " . ($lastObjectNumber + 1) . "\n";
  2799. $pdf .= "0000000000 65535 f \n";
  2800. for ($i = 1; $i <= $lastObjectNumber; $i++) {
  2801. if (isset($offsets[$i])) {
  2802. $pdf .= sprintf("%010d 00000 n \n", $offsets[$i]);
  2803. } else {
  2804. $pdf .= "0000000000 00000 f \n";
  2805. }
  2806. }
  2807. $pdf .= "trailer\n<< /Size " . ($lastObjectNumber + 1) . " /Root 1 0 R >>\n";
  2808. $pdf .= "startxref\n" . $xrefOffset . "\n%%EOF";
  2809. return $pdf;
  2810. }
  2811. /**
  2812. * Input Validation Class
  2813. */
  2814. class Validator
  2815. {
  2816. private $errors = [];
  2817. private $data = [];
  2818. public function __construct($data)
  2819. {
  2820. $this->data = $data;
  2821. }
  2822. public function required($field, $label = null)
  2823. {
  2824. $value = $this->get($field);
  2825. if (empty(trim($value ?? ""))) {
  2826. $this->errors[] = ($label ?? $field) . " ist erforderlich.";
  2827. }
  2828. return $this;
  2829. }
  2830. public function email($field, $label = null)
  2831. {
  2832. $value = $this->get($field);
  2833. if (!empty($value) && !filter_var($value, FILTER_VALIDATE_EMAIL)) {
  2834. $this->errors[] =
  2835. ($label ?? $field) . " muss eine gültige E-Mail-Adresse sein.";
  2836. }
  2837. return $this;
  2838. }
  2839. public function minLength($field, $min, $label = null)
  2840. {
  2841. $value = $this->get($field);
  2842. if (!empty($value) && strlen($value) < $min) {
  2843. $this->errors[] =
  2844. ($label ?? $field) .
  2845. " muss mindestens " .
  2846. $min .
  2847. " Zeichen lang sein.";
  2848. }
  2849. return $this;
  2850. }
  2851. public function maxLength($field, $max, $label = null)
  2852. {
  2853. $value = $this->get($field);
  2854. if (!empty($value) && strlen($value) > $max) {
  2855. $this->errors[] =
  2856. ($label ?? $field) .
  2857. " darf maximal " .
  2858. $max .
  2859. " Zeichen lang sein.";
  2860. }
  2861. return $this;
  2862. }
  2863. public function inArray($field, $allowed, $label = null)
  2864. {
  2865. $value = $this->get($field);
  2866. if (!empty($value) && !in_array($value, $allowed, true)) {
  2867. $this->errors[] = ($label ?? $field) . " ist ungültig.";
  2868. }
  2869. return $this;
  2870. }
  2871. public function get($field)
  2872. {
  2873. return $this->data[$field] ?? null;
  2874. }
  2875. public function addError(string $message): self
  2876. {
  2877. $message = trim($message);
  2878. if ($message !== "") {
  2879. $this->errors[] = $message;
  2880. }
  2881. return $this;
  2882. }
  2883. public function getErrors()
  2884. {
  2885. return $this->errors;
  2886. }
  2887. public function isValid()
  2888. {
  2889. return empty($this->errors);
  2890. }
  2891. }
  2892. /**
  2893. * Error Logging Functions
  2894. */
  2895. if (!defined("LOG_DIR")) {
  2896. define("LOG_DIR", DATA_DIR . "logs/");
  2897. }
  2898. if (!defined("ERROR_LOG_FILE")) {
  2899. define("ERROR_LOG_FILE", LOG_DIR . "error.log");
  2900. }
  2901. if (!defined("ACCESS_LOG_FILE")) {
  2902. define("ACCESS_LOG_FILE", LOG_DIR . "access.log");
  2903. }
  2904. if (!defined("LOG_MAX_BYTES")) {
  2905. define("LOG_MAX_BYTES", 1048576);
  2906. }
  2907. if (!defined("LOG_KEEP_FILES")) {
  2908. define("LOG_KEEP_FILES", 5);
  2909. }
  2910. if (!defined("LOG_MAX_AGE_SECONDS")) {
  2911. define("LOG_MAX_AGE_SECONDS", 2592000);
  2912. }
  2913. function initLogging()
  2914. {
  2915. if (!is_dir(LOG_DIR)) {
  2916. mkdir(LOG_DIR, 02775, true);
  2917. @chmod(LOG_DIR, 02775);
  2918. }
  2919. }
  2920. function rotateLogFileIfNeeded(string $logFile): void
  2921. {
  2922. $maxBytes = max(1024, (int) LOG_MAX_BYTES);
  2923. $keepFiles = max(1, (int) LOG_KEEP_FILES);
  2924. $maxAgeSeconds = max(0, (int) LOG_MAX_AGE_SECONDS);
  2925. $now = time();
  2926. $rotatedFiles = glob($logFile . ".*") ?: [];
  2927. foreach ($rotatedFiles as $rotatedFile) {
  2928. if (preg_match('/\.(\d+)$/', $rotatedFile, $matches) !== 1) {
  2929. continue;
  2930. }
  2931. $index = (int) $matches[1];
  2932. $isTooOld =
  2933. $maxAgeSeconds > 0 &&
  2934. is_file($rotatedFile) &&
  2935. ($now - (int) filemtime($rotatedFile)) > $maxAgeSeconds;
  2936. if ($index > $keepFiles || $isTooOld) {
  2937. @unlink($rotatedFile);
  2938. }
  2939. }
  2940. if (!is_file($logFile) || (filesize($logFile) ?: 0) < $maxBytes) {
  2941. return;
  2942. }
  2943. for ($i = $keepFiles; $i >= 1; $i--) {
  2944. $source = $i === 1 ? $logFile : $logFile . "." . ($i - 1);
  2945. $target = $logFile . "." . $i;
  2946. if (!is_file($source)) {
  2947. continue;
  2948. }
  2949. if ($i === $keepFiles && is_file($target)) {
  2950. @unlink($target);
  2951. }
  2952. @rename($source, $target);
  2953. }
  2954. }
  2955. function logError($message, $context = [], $level = "ERROR")
  2956. {
  2957. initLogging();
  2958. rotateLogFileIfNeeded(ERROR_LOG_FILE);
  2959. $entry = [
  2960. "timestamp" => date("Y-m-d H:i:s.u"),
  2961. "level" => $level,
  2962. "message" => $message,
  2963. "context" => $context,
  2964. "ip" => $_SERVER["REMOTE_ADDR"] ?? "unknown",
  2965. "user_agent" => $_SERVER["HTTP_USER_AGENT"] ?? "unknown",
  2966. "request_uri" => $_SERVER["REQUEST_URI"] ?? "unknown",
  2967. "session_id" => session_id()
  2968. ? substr(session_id(), 0, 8) . "..."
  2969. : "none",
  2970. ];
  2971. $logLine = json_encode($entry, JSON_UNESCAPED_UNICODE) . PHP_EOL;
  2972. file_put_contents(ERROR_LOG_FILE, $logLine, FILE_APPEND | LOCK_EX);
  2973. if (defined("DEVELOPMENT_MODE") && DEVELOPMENT_MODE) {
  2974. error_log(
  2975. "PSA Order: " . $message . " | Context: " . json_encode($context),
  2976. );
  2977. }
  2978. }
  2979. function logAccess($message, $context = [])
  2980. {
  2981. initLogging();
  2982. rotateLogFileIfNeeded(ACCESS_LOG_FILE);
  2983. $entry = [
  2984. "timestamp" => date("Y-m-d H:i:s.u"),
  2985. "message" => $message,
  2986. "context" => $context,
  2987. "ip" => $_SERVER["REMOTE_ADDR"] ?? "unknown",
  2988. "request_method" => $_SERVER["REQUEST_METHOD"] ?? "unknown",
  2989. "request_uri" => $_SERVER["REQUEST_URI"] ?? "unknown",
  2990. ];
  2991. $logLine = json_encode($entry, JSON_UNESCAPED_UNICODE) . PHP_EOL;
  2992. file_put_contents(ACCESS_LOG_FILE, $logLine, FILE_APPEND | LOCK_EX);
  2993. }
  2994. function handleException($exception)
  2995. {
  2996. logError(
  2997. "Uncaught exception: " . $exception->getMessage(),
  2998. [
  2999. "file" => $exception->getFile(),
  3000. "line" => $exception->getLine(),
  3001. "trace" => $exception->getTraceAsString(),
  3002. ],
  3003. "CRITICAL",
  3004. );
  3005. if (defined("DEVELOPMENT_MODE") && DEVELOPMENT_MODE) {
  3006. echo "<h1>Error</h1><pre>" .
  3007. escape($exception->getMessage()) .
  3008. "</pre>";
  3009. } else {
  3010. echo "<h1>Es ist ein Fehler aufgetreten</h1><p>Bitte versuchen Sie es später erneut.</p>";
  3011. }
  3012. exit();
  3013. }
  3014. set_exception_handler("handleException");
  3015. function handleError($errno, $errstr, $errfile, $errline)
  3016. {
  3017. if (!(error_reporting() & $errno)) {
  3018. return false;
  3019. }
  3020. logError(
  3021. "PHP Error: " . $errstr,
  3022. [
  3023. "type" => $errno,
  3024. "file" => $errfile,
  3025. "line" => $errline,
  3026. ],
  3027. "WARNING",
  3028. );
  3029. return true;
  3030. }
  3031. set_error_handler("handleError");