functions.php 97 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760
  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. "nametag_product_name" => "Namensschild",
  1102. ];
  1103. }
  1104. function normalizeSystemSettings($settings)
  1105. {
  1106. $defaults = getDefaultSystemSettings();
  1107. if (!is_array($settings)) {
  1108. $settings = [];
  1109. }
  1110. $recipientEmail = normalizeAdminEmail(
  1111. $settings["order_recipient_email"] ??
  1112. $defaults["order_recipient_email"],
  1113. );
  1114. if (!isValidAdminEmail($recipientEmail)) {
  1115. $recipientEmail = $defaults["order_recipient_email"];
  1116. }
  1117. $startpageIntroText = trim(
  1118. (string) ($settings["startpage_intro_text"] ?? $defaults["startpage_intro_text"]),
  1119. );
  1120. $nametagProductName = trim(
  1121. (string) ($settings["nametag_product_name"] ?? $defaults["nametag_product_name"]),
  1122. );
  1123. if ($nametagProductName === "") {
  1124. $nametagProductName = $defaults["nametag_product_name"];
  1125. }
  1126. return [
  1127. "order_recipient_email" => $recipientEmail,
  1128. "attach_order_pdf_to_admin_email" => !empty(
  1129. $settings["attach_order_pdf_to_admin_email"]
  1130. ),
  1131. "startpage_intro_text" => $startpageIntroText,
  1132. "nametag_product_name" => $nametagProductName,
  1133. ];
  1134. }
  1135. function getSystemSettings()
  1136. {
  1137. $data = readJsonFile(SETTINGS_FILE);
  1138. return normalizeSystemSettings($data["settings"] ?? []);
  1139. }
  1140. function saveSystemSettings($settings)
  1141. {
  1142. return writeJsonFile(SETTINGS_FILE, [
  1143. "settings" => normalizeSystemSettings($settings),
  1144. ]);
  1145. }
  1146. function getOrderRecipientEmail()
  1147. {
  1148. $settings = getSystemSettings();
  1149. return $settings["order_recipient_email"];
  1150. }
  1151. function shouldAttachOrderPdfToAdminEmail()
  1152. {
  1153. $settings = getSystemSettings();
  1154. return !empty($settings["attach_order_pdf_to_admin_email"]);
  1155. }
  1156. function getNametagProductName()
  1157. {
  1158. $settings = getSystemSettings();
  1159. return $settings["nametag_product_name"];
  1160. }
  1161. function getStartpageIntroLines()
  1162. {
  1163. $settings = getSystemSettings();
  1164. $text = trim((string) ($settings["startpage_intro_text"] ?? ""));
  1165. if ($text === "") {
  1166. return [];
  1167. }
  1168. $lines = preg_split('/\R+/', $text) ?: [];
  1169. $lines = array_values(
  1170. array_filter(
  1171. array_map(function ($line) {
  1172. return trim((string) $line);
  1173. }, $lines),
  1174. function ($line) {
  1175. return $line !== "";
  1176. },
  1177. ),
  1178. );
  1179. return $lines;
  1180. }
  1181. function backorderStatusEmpty(): string
  1182. {
  1183. return "";
  1184. }
  1185. function backorderStatusToBeBackordered(): string
  1186. {
  1187. return "to_be_backordered";
  1188. }
  1189. function backorderStatusOrdered(): string
  1190. {
  1191. return "ordered";
  1192. }
  1193. /** Statuses persisted on order line items (load/save). */
  1194. function getBackorderStatusesForStorage(): array
  1195. {
  1196. return [
  1197. backorderStatusEmpty(),
  1198. backorderStatusToBeBackordered(),
  1199. backorderStatusOrdered(),
  1200. ];
  1201. }
  1202. /** Statuses settable from order detail (mark for external reorder). */
  1203. function getBackorderStatusesForAdminMarking(): array
  1204. {
  1205. return [backorderStatusEmpty(), backorderStatusToBeBackordered()];
  1206. }
  1207. function isValidBackorderStatusForStorage(string $status): bool
  1208. {
  1209. return in_array($status, getBackorderStatusesForStorage(), true);
  1210. }
  1211. function isValidBackorderStatusForAdminMarking(string $status): bool
  1212. {
  1213. return in_array($status, getBackorderStatusesForAdminMarking(), true);
  1214. }
  1215. function normalizeOrderItem($item)
  1216. {
  1217. if (!is_array($item)) {
  1218. return null;
  1219. }
  1220. $productId = isset($item["product_id"]) ? (int) $item["product_id"] : 0;
  1221. if ($productId <= 0) {
  1222. return null;
  1223. }
  1224. $product = getProductById($productId);
  1225. if ($product === null) {
  1226. return null;
  1227. }
  1228. $size = trim((string) ($item["size"] ?? ""));
  1229. $sizes = getProductSizes($product);
  1230. if (!empty($sizes)) {
  1231. if ($size === "" || !in_array($size, $sizes, true)) {
  1232. return null;
  1233. }
  1234. } else {
  1235. $size = "";
  1236. }
  1237. $backorderStatus = trim((string) ($item["backorder_status"] ?? ""));
  1238. if (!isValidBackorderStatusForStorage($backorderStatus)) {
  1239. $backorderStatus = backorderStatusEmpty();
  1240. }
  1241. return [
  1242. "product_id" => $productId,
  1243. "product_name" => $product["name"],
  1244. "size" => $size,
  1245. "availability_label" =>
  1246. $size !== "" ? getAvailabilityLabel($product, $size) : "",
  1247. "is_processed" => !empty($item["is_processed"]),
  1248. "backorder_status" => $backorderStatus,
  1249. "backordered_at" => trim((string) ($item["backordered_at"] ?? "")),
  1250. "ordered_at" => trim((string) ($item["ordered_at"] ?? "")),
  1251. ];
  1252. }
  1253. function normalizeOrderItems($items)
  1254. {
  1255. $normalized = [];
  1256. $seen = [];
  1257. if (!is_array($items)) {
  1258. return [];
  1259. }
  1260. foreach ($items as $item) {
  1261. $record = normalizeOrderItem($item);
  1262. if ($record === null) {
  1263. continue;
  1264. }
  1265. $key = $record["product_id"] . "|" . $record["size"];
  1266. if (isset($seen[$key])) {
  1267. continue;
  1268. }
  1269. $seen[$key] = true;
  1270. $normalized[] = $record;
  1271. }
  1272. return array_values($normalized);
  1273. }
  1274. function getOrders()
  1275. {
  1276. $data = readJsonFile(ORDERS_FILE);
  1277. $orders =
  1278. isset($data["orders"]) && is_array($data["orders"])
  1279. ? $data["orders"]
  1280. : [];
  1281. $normalized = [];
  1282. foreach ($orders as $order) {
  1283. $record = normalizeOrderRecord($order);
  1284. if ($record !== null) {
  1285. $normalized[] = $record;
  1286. }
  1287. }
  1288. return $normalized;
  1289. }
  1290. function saveOrders($orders)
  1291. {
  1292. $normalized = [];
  1293. foreach ($orders as $order) {
  1294. $record = normalizeOrderRecord($order);
  1295. if ($record !== null) {
  1296. $normalized[] = $record;
  1297. }
  1298. }
  1299. $result = writeJsonFile(ORDERS_FILE, [
  1300. "orders" => array_values($normalized),
  1301. ]);
  1302. if (!$result) {
  1303. logError("Failed to save orders", [
  1304. "file" => ORDERS_FILE,
  1305. "order_count" => count($normalized),
  1306. ]);
  1307. }
  1308. return (bool) $result;
  1309. }
  1310. function generateOrderId()
  1311. {
  1312. $orders = getOrders();
  1313. $year = date("Y");
  1314. $prefix = defined("ORDER_PREFIX") ? ORDER_PREFIX : "ORD";
  1315. $max = 0;
  1316. $pattern = "/^" . preg_quote($prefix, "/") . '-\d{4}-(\d+)$/';
  1317. foreach ($orders as $order) {
  1318. if (preg_match($pattern, (string) $order["id"], $matches) === 1) {
  1319. $number = (int) $matches[1];
  1320. if ($number > $max) {
  1321. $max = $number;
  1322. }
  1323. }
  1324. }
  1325. return sprintf("%s-%s-%03d", $prefix, $year, $max + 1);
  1326. }
  1327. function normalizeOrderRecord($order)
  1328. {
  1329. if (!is_array($order)) {
  1330. return null;
  1331. }
  1332. $id = trim((string) ($order["id"] ?? ""));
  1333. $customerName = trim((string) ($order["customer_name"] ?? ""));
  1334. $customerEmail = normalizeAdminEmail($order["customer_email"] ?? "");
  1335. $organizationId = normalizeOrganizationId($order["organization_id"] ?? "");
  1336. $organizationLabel = trim((string) ($order["organization_label"] ?? ""));
  1337. $items = normalizeOrderItems($order["items"] ?? []);
  1338. if (
  1339. $id === "" ||
  1340. $customerName === "" ||
  1341. !isValidAdminEmail($customerEmail) ||
  1342. $organizationId === "" ||
  1343. $organizationLabel === "" ||
  1344. empty($items)
  1345. ) {
  1346. return null;
  1347. }
  1348. $createdAt = trim((string) ($order["created_at"] ?? ""));
  1349. if ($createdAt === "") {
  1350. $createdAt = date("Y-m-d H:i:s");
  1351. }
  1352. $status = trim((string) ($order["status"] ?? "open"));
  1353. $allowedStatuses = ["open", "partial", "processed", "cancelled"];
  1354. if (!in_array($status, $allowedStatuses, true)) {
  1355. $status = "open";
  1356. }
  1357. $normalized = [
  1358. "id" => $id,
  1359. "customer_name" => $customerName,
  1360. "customer_email" => $customerEmail,
  1361. "organization_id" => $organizationId,
  1362. "organization_label" => $organizationLabel,
  1363. "comment" => trim((string) ($order["comment"] ?? "")),
  1364. "items" => $items,
  1365. "status" => $status,
  1366. "created_at" => $createdAt,
  1367. "updated_at" => trim((string) ($order["updated_at"] ?? $createdAt)),
  1368. "cancelled_at" => trim((string) ($order["cancelled_at"] ?? "")),
  1369. "cancelled_by" => trim((string) ($order["cancelled_by"] ?? "")),
  1370. "cancellation_reason" => trim(
  1371. (string) ($order["cancellation_reason"] ?? ""),
  1372. ),
  1373. "admin_notified_at" => trim(
  1374. (string) ($order["admin_notified_at"] ?? ""),
  1375. ),
  1376. ];
  1377. return refreshOrderState($normalized);
  1378. }
  1379. function refreshOrderState($order)
  1380. {
  1381. if (!is_array($order)) {
  1382. return null;
  1383. }
  1384. if (($order["status"] ?? "") === "cancelled") {
  1385. return $order;
  1386. }
  1387. $processedCount = 0;
  1388. foreach ($order["items"] as $item) {
  1389. if (!empty($item["is_processed"])) {
  1390. $processedCount++;
  1391. }
  1392. }
  1393. if ($processedCount <= 0) {
  1394. $order["status"] = "open";
  1395. } elseif ($processedCount >= count($order["items"])) {
  1396. $order["status"] = "processed";
  1397. } else {
  1398. $order["status"] = "partial";
  1399. }
  1400. return $order;
  1401. }
  1402. function getOrderById($orderId)
  1403. {
  1404. $orderId = trim((string) $orderId);
  1405. if ($orderId === "") {
  1406. return null;
  1407. }
  1408. foreach (getOrders() as $order) {
  1409. if ($order["id"] === $orderId) {
  1410. return $order;
  1411. }
  1412. }
  1413. return null;
  1414. }
  1415. function buildAbsoluteUrl($path)
  1416. {
  1417. $path = "/" . ltrim((string) $path, "/");
  1418. $siteUrl = defined("SITE_URL") ? trim((string) SITE_URL) : "";
  1419. if (strpos($siteUrl, "://") !== false) {
  1420. return rtrim($siteUrl, "/") . $path;
  1421. }
  1422. $basePath = trim($siteUrl);
  1423. if ($basePath !== "" && $basePath !== "/") {
  1424. $path = "/" . trim($basePath, "/") . $path;
  1425. }
  1426. $canonical = defined("SITE_CANONICAL_ORIGIN")
  1427. ? trim((string) SITE_CANONICAL_ORIGIN)
  1428. : "";
  1429. if (
  1430. $canonical !== "" &&
  1431. preg_match("#\Ahttps?://[^\s/]+#i", $canonical)
  1432. ) {
  1433. return rtrim($canonical, "/") . $path;
  1434. }
  1435. $scheme = isHttpsRequest() ? "https" : "http";
  1436. $host = $_SERVER["HTTP_HOST"] ?? "";
  1437. if ($host === "") {
  1438. return $path;
  1439. }
  1440. return $scheme . "://" . $host . $path;
  1441. }
  1442. function isHttpsRequest(): bool
  1443. {
  1444. if (
  1445. !empty($_SERVER["HTTPS"]) &&
  1446. strtolower((string) $_SERVER["HTTPS"]) !== "off"
  1447. ) {
  1448. return true;
  1449. }
  1450. if (
  1451. !empty($_SERVER["HTTP_X_FORWARDED_PROTO"]) &&
  1452. strtolower((string) $_SERVER["HTTP_X_FORWARDED_PROTO"]) === "https"
  1453. ) {
  1454. return true;
  1455. }
  1456. if (
  1457. !empty($_SERVER["SERVER_PORT"]) &&
  1458. (int) $_SERVER["SERVER_PORT"] === 443
  1459. ) {
  1460. return true;
  1461. }
  1462. return false;
  1463. }
  1464. function createOrder(
  1465. $customerName,
  1466. $customerEmail,
  1467. $organizationId,
  1468. $comment,
  1469. $items,
  1470. ) {
  1471. $customerName = sanitize($customerName);
  1472. $customerEmail = normalizeAdminEmail($customerEmail);
  1473. $organizationId = normalizeOrganizationId($organizationId);
  1474. $comment = trim((string) $comment);
  1475. $items = normalizeOrderItems($items);
  1476. if ($customerName === "") {
  1477. return [
  1478. "success" => false,
  1479. "message" => "Bitte geben Sie einen Namen ein.",
  1480. ];
  1481. }
  1482. if (!isValidAdminEmail($customerEmail)) {
  1483. return [
  1484. "success" => false,
  1485. "message" => "Bitte geben Sie eine gültige E-Mail-Adresse ein.",
  1486. ];
  1487. }
  1488. if (empty($items)) {
  1489. return [
  1490. "success" => false,
  1491. "message" =>
  1492. "Der Warenkorb ist leer oder enthält ungültige Positionen.",
  1493. ];
  1494. }
  1495. $organization = getOrganizationById($organizationId);
  1496. if ($organization === null || empty($organization["active"])) {
  1497. return [
  1498. "success" => false,
  1499. "message" => "Bitte wählen Sie eine gültige Organisation aus.",
  1500. ];
  1501. }
  1502. $now = date("Y-m-d H:i:s");
  1503. $order = [
  1504. "id" => generateOrderId(),
  1505. "customer_name" => $customerName,
  1506. "customer_email" => $customerEmail,
  1507. "organization_id" => $organization["id"],
  1508. "organization_label" => $organization["label"],
  1509. "comment" => $comment,
  1510. "items" => $items,
  1511. "status" => "open",
  1512. "created_at" => $now,
  1513. "updated_at" => $now,
  1514. "cancelled_at" => "",
  1515. "cancelled_by" => "",
  1516. "cancellation_reason" => "",
  1517. "admin_notified_at" => "",
  1518. ];
  1519. $orders = getOrders();
  1520. $orders[] = $order;
  1521. if (!saveOrders($orders)) {
  1522. return [
  1523. "success" => false,
  1524. "message" =>
  1525. "Die Bestellung konnte nicht gespeichert werden. Bitte versuchen Sie es erneut.",
  1526. ];
  1527. }
  1528. logAccess("Order created in createOrder", [
  1529. "order_id" => $order["id"],
  1530. "customer" => $customerEmail,
  1531. "organization" => $organization["label"],
  1532. ]);
  1533. $result = sendConfirmedOrderAdminNotification($order);
  1534. if ($result) {
  1535. markOrderAdminNotified($order["id"]);
  1536. $order = getOrderById($order["id"]);
  1537. }
  1538. sendOrderCreatedCustomerEmail($order);
  1539. return ["success" => true, "order" => $order];
  1540. }
  1541. function markOrderAdminNotified($orderId)
  1542. {
  1543. $orders = getOrders();
  1544. foreach ($orders as &$order) {
  1545. if ($order["id"] !== $orderId) {
  1546. continue;
  1547. }
  1548. $order["admin_notified_at"] = date("Y-m-d H:i:s");
  1549. $order["updated_at"] = date("Y-m-d H:i:s");
  1550. break;
  1551. }
  1552. unset($order);
  1553. saveOrders($orders);
  1554. }
  1555. function toggleOrderItemProcessed($orderId, $itemIndex)
  1556. {
  1557. $orders = getOrders();
  1558. $now = date("Y-m-d H:i:s");
  1559. foreach ($orders as &$order) {
  1560. if ($order["id"] !== $orderId) {
  1561. continue;
  1562. }
  1563. if ($order["status"] === "cancelled") {
  1564. return [
  1565. "success" => false,
  1566. "message" =>
  1567. "Stornierte Bestellungen können nicht mehr bearbeitet werden.",
  1568. ];
  1569. }
  1570. if (!isset($order["items"][$itemIndex])) {
  1571. return [
  1572. "success" => false,
  1573. "message" => "Position nicht gefunden.",
  1574. ];
  1575. }
  1576. $order["items"][$itemIndex]["is_processed"] = empty(
  1577. $order["items"][$itemIndex]["is_processed"]
  1578. );
  1579. if ($order["items"][$itemIndex]["is_processed"]) {
  1580. // Eine bearbeitete Position ist ausgeliefert und darf nicht als
  1581. // offene Nachbestellung in der Uebersicht haengen bleiben.
  1582. $order["items"][$itemIndex]["backorder_status"] = backorderStatusEmpty();
  1583. $order["items"][$itemIndex]["backordered_at"] = "";
  1584. $order["items"][$itemIndex]["ordered_at"] = "";
  1585. }
  1586. $order["updated_at"] = $now;
  1587. $order = refreshOrderState($order);
  1588. if (!saveOrders($orders)) {
  1589. return [
  1590. "success" => false,
  1591. "message" => "Bestellung konnte nicht gespeichert werden.",
  1592. ];
  1593. }
  1594. return ["success" => true, "order" => $order];
  1595. }
  1596. unset($order);
  1597. return ["success" => false, "message" => "Bestellung nicht gefunden."];
  1598. }
  1599. function cancelOrder($orderId, $adminUsername, $reason = "")
  1600. {
  1601. $orders = getOrders();
  1602. $now = date("Y-m-d H:i:s");
  1603. $adminUsername = normalizeAdminUsername($adminUsername);
  1604. $reason = trim((string) $reason);
  1605. foreach ($orders as &$order) {
  1606. if ($order["id"] !== $orderId) {
  1607. continue;
  1608. }
  1609. if ($order["status"] === "cancelled") {
  1610. return [
  1611. "success" => false,
  1612. "message" => "Die Bestellung ist bereits storniert.",
  1613. ];
  1614. }
  1615. $order["status"] = "cancelled";
  1616. $order["cancelled_at"] = $now;
  1617. $order["cancelled_by"] = $adminUsername;
  1618. $order["cancellation_reason"] = $reason;
  1619. $order["updated_at"] = $now;
  1620. foreach ($order["items"] as &$item) {
  1621. $item["backorder_status"] = "";
  1622. $item["backordered_at"] = "";
  1623. $item["ordered_at"] = "";
  1624. }
  1625. unset($item);
  1626. saveOrders($orders);
  1627. return ["success" => true, "order" => $order];
  1628. }
  1629. unset($order);
  1630. return ["success" => false, "message" => "Bestellung nicht gefunden."];
  1631. }
  1632. function uncancelOrder($orderId)
  1633. {
  1634. $orders = getOrders();
  1635. $now = date("Y-m-d H:i:s");
  1636. foreach ($orders as &$order) {
  1637. if ($order["id"] !== $orderId) {
  1638. continue;
  1639. }
  1640. if ($order["status"] !== "cancelled") {
  1641. return [
  1642. "success" => false,
  1643. "message" => "Die Bestellung ist nicht storniert.",
  1644. ];
  1645. }
  1646. $order["cancelled_at"] = "";
  1647. $order["cancelled_by"] = "";
  1648. $order["cancellation_reason"] = "";
  1649. $order["status"] = "open";
  1650. $order["updated_at"] = $now;
  1651. $order = refreshOrderState($order);
  1652. saveOrders($orders);
  1653. return ["success" => true, "order" => $order];
  1654. }
  1655. unset($order);
  1656. return ["success" => false, "message" => "Bestellung nicht gefunden."];
  1657. }
  1658. function orderItemCanBeManaged($order)
  1659. {
  1660. if (($order["status"] ?? "") === "cancelled") {
  1661. return [
  1662. "success" => false,
  1663. "message" =>
  1664. "Stornierte Bestellungen können nicht mehr bearbeitet werden.",
  1665. ];
  1666. }
  1667. return ["success" => true];
  1668. }
  1669. function setOrderItemBackorderStatus($orderId, $itemIndex, $status)
  1670. {
  1671. if (!isValidBackorderStatusForAdminMarking($status)) {
  1672. return ["success" => false, "message" => "Ungültiger Nachbestellstatus."];
  1673. }
  1674. $orders = getOrders();
  1675. $now = date("Y-m-d H:i:s");
  1676. foreach ($orders as &$order) {
  1677. if ($order["id"] !== $orderId) {
  1678. continue;
  1679. }
  1680. $guard = orderItemCanBeManaged($order);
  1681. if (!$guard["success"]) {
  1682. return $guard;
  1683. }
  1684. if (!isset($order["items"][$itemIndex])) {
  1685. return [
  1686. "success" => false,
  1687. "message" => "Position nicht gefunden.",
  1688. ];
  1689. }
  1690. if ($status === backorderStatusToBeBackordered()) {
  1691. if (!empty($order["items"][$itemIndex]["is_processed"])) {
  1692. return [
  1693. "success" => false,
  1694. "message" =>
  1695. "Bearbeitete Positionen können nicht als Nachbestellung markiert werden.",
  1696. ];
  1697. }
  1698. $order["items"][$itemIndex]["backorder_status"] =
  1699. backorderStatusToBeBackordered();
  1700. $order["items"][$itemIndex]["backordered_at"] = $now;
  1701. $order["items"][$itemIndex]["ordered_at"] = "";
  1702. } else {
  1703. $order["items"][$itemIndex]["backorder_status"] = backorderStatusEmpty();
  1704. $order["items"][$itemIndex]["backordered_at"] = "";
  1705. $order["items"][$itemIndex]["ordered_at"] = "";
  1706. }
  1707. $order["updated_at"] = $now;
  1708. saveOrders($orders);
  1709. return ["success" => true, "order" => $order];
  1710. }
  1711. unset($order);
  1712. return ["success" => false, "message" => "Bestellung nicht gefunden."];
  1713. }
  1714. function toggleOrderItemBackorder($orderId, $itemIndex)
  1715. {
  1716. $orders = getOrders();
  1717. foreach ($orders as $order) {
  1718. if ($order["id"] !== $orderId) {
  1719. continue;
  1720. }
  1721. if (!isset($order["items"][$itemIndex])) {
  1722. return [
  1723. "success" => false,
  1724. "message" => "Position nicht gefunden.",
  1725. ];
  1726. }
  1727. $current = (string) ($order["items"][$itemIndex]["backorder_status"] ?? "");
  1728. $newStatus = $current === "to_be_backordered" ? "" : "to_be_backordered";
  1729. return setOrderItemBackorderStatus($orderId, $itemIndex, $newStatus);
  1730. }
  1731. return ["success" => false, "message" => "Bestellung nicht gefunden."];
  1732. }
  1733. function getManualBackorders()
  1734. {
  1735. $data = readJsonFile(MANUAL_BACKORDERS_FILE);
  1736. $entries =
  1737. isset($data["entries"]) && is_array($data["entries"])
  1738. ? $data["entries"]
  1739. : [];
  1740. $normalized = [];
  1741. foreach ($entries as $entry) {
  1742. if (!is_array($entry)) {
  1743. continue;
  1744. }
  1745. $id = trim((string) ($entry["id"] ?? ""));
  1746. $productId = (int) ($entry["product_id"] ?? 0);
  1747. $productName = trim((string) ($entry["product_name"] ?? ""));
  1748. $size = trim((string) ($entry["size"] ?? ""));
  1749. $status = trim((string) ($entry["backorder_status"] ?? ""));
  1750. if ($id === "" || $productId <= 0 || $productName === "" || $status === "") {
  1751. continue;
  1752. }
  1753. if (!in_array($status, ["to_be_backordered", "ordered"], true)) {
  1754. continue;
  1755. }
  1756. $normalized[] = [
  1757. "id" => $id,
  1758. "product_id" => $productId,
  1759. "product_name" => $productName,
  1760. "size" => $size,
  1761. "backorder_status" => $status,
  1762. "backordered_at" => trim((string) ($entry["backordered_at"] ?? "")),
  1763. "ordered_at" => trim((string) ($entry["ordered_at"] ?? "")),
  1764. "created_at" => trim((string) ($entry["created_at"] ?? "")),
  1765. ];
  1766. }
  1767. return $normalized;
  1768. }
  1769. function saveManualBackorders($entries)
  1770. {
  1771. return writeJsonFile(MANUAL_BACKORDERS_FILE, [
  1772. "entries" => array_values($entries),
  1773. ]);
  1774. }
  1775. function generateManualBackorderId()
  1776. {
  1777. return "mb-" . date("YmdHis") . "-" . bin2hex(random_bytes(4));
  1778. }
  1779. function addManualBackorderItems($productId, $size, $quantity)
  1780. {
  1781. $productId = (int) $productId;
  1782. $size = trim((string) $size);
  1783. $quantity = (int) $quantity;
  1784. if ($productId <= 0 || $quantity <= 0) {
  1785. return [
  1786. "success" => false,
  1787. "message" => "Ungültige Menge oder Artikel.",
  1788. ];
  1789. }
  1790. if ($quantity > 100) {
  1791. return [
  1792. "success" => false,
  1793. "message" => "Maximal 100 Positionen auf einmal.",
  1794. ];
  1795. }
  1796. $product = getProductById($productId);
  1797. if ($product === null) {
  1798. return ["success" => false, "message" => "Artikel nicht gefunden."];
  1799. }
  1800. $allowedSizes = getProductSizes($product);
  1801. if (empty($allowedSizes)) {
  1802. $allowedSizes = ["Standard"];
  1803. }
  1804. if (!in_array($size, $allowedSizes, true)) {
  1805. return ["success" => false, "message" => "Ungültige Größe für diesen Artikel."];
  1806. }
  1807. $entries = getManualBackorders();
  1808. $now = date("Y-m-d H:i:s");
  1809. for ($i = 0; $i < $quantity; $i++) {
  1810. $entries[] = [
  1811. "id" => generateManualBackorderId(),
  1812. "product_id" => $productId,
  1813. "product_name" => $product["name"],
  1814. "size" => $size,
  1815. "backorder_status" => "to_be_backordered",
  1816. "backordered_at" => $now,
  1817. "ordered_at" => "",
  1818. "created_at" => $now,
  1819. ];
  1820. }
  1821. if (!saveManualBackorders($entries)) {
  1822. return [
  1823. "success" => false,
  1824. "message" => "Nachbestellungen konnten nicht gespeichert werden.",
  1825. ];
  1826. }
  1827. return ["success" => true, "added" => $quantity];
  1828. }
  1829. function collectBackorderItemRefs()
  1830. {
  1831. $refs = [];
  1832. foreach (getManualBackorders() as $entry) {
  1833. $refs[] = [
  1834. "order_id" => "",
  1835. "item_index" => 0,
  1836. "manual_id" => $entry["id"],
  1837. "is_manual" => true,
  1838. "product_id" => $entry["product_id"],
  1839. "product_name" => $entry["product_name"],
  1840. "size" => $entry["size"],
  1841. "backorder_status" => $entry["backorder_status"],
  1842. "created_at" => $entry["created_at"] !== "" ? $entry["created_at"] : $entry["backordered_at"],
  1843. "sort_at" =>
  1844. $entry["backorder_status"] === "ordered"
  1845. ? ($entry["ordered_at"] !== ""
  1846. ? $entry["ordered_at"]
  1847. : $entry["created_at"])
  1848. : ($entry["backordered_at"] !== ""
  1849. ? $entry["backordered_at"]
  1850. : $entry["created_at"]),
  1851. ];
  1852. }
  1853. foreach (getOrders() as $order) {
  1854. if (($order["status"] ?? "") === "cancelled") {
  1855. continue;
  1856. }
  1857. foreach ($order["items"] as $itemIndex => $item) {
  1858. if (!empty($item["is_processed"])) {
  1859. continue;
  1860. }
  1861. $status = (string) ($item["backorder_status"] ?? "");
  1862. if ($status === "") {
  1863. continue;
  1864. }
  1865. $refs[] = [
  1866. "order_id" => $order["id"],
  1867. "item_index" => (int) $itemIndex,
  1868. "product_id" => (int) $item["product_id"],
  1869. "product_name" => $item["product_name"],
  1870. "size" => $item["size"],
  1871. "backorder_status" => $status,
  1872. "created_at" => $order["created_at"],
  1873. "sort_at" =>
  1874. $status === "ordered"
  1875. ? ($item["ordered_at"] !== ""
  1876. ? $item["ordered_at"]
  1877. : $order["created_at"])
  1878. : ($item["backordered_at"] !== ""
  1879. ? $item["backordered_at"]
  1880. : $order["created_at"]),
  1881. ];
  1882. }
  1883. }
  1884. return $refs;
  1885. }
  1886. function compareBackorderRefs(array $left, array $right): int
  1887. {
  1888. $cmp = strcmp((string) ($left["sort_at"] ?? ""), (string) ($right["sort_at"] ?? ""));
  1889. if ($cmp !== 0) {
  1890. return $cmp;
  1891. }
  1892. $cmp = strcmp((string) ($left["order_id"] ?? ""), (string) ($right["order_id"] ?? ""));
  1893. if ($cmp !== 0) {
  1894. return $cmp;
  1895. }
  1896. return strcmp((string) ($left["manual_id"] ?? ""), (string) ($right["manual_id"] ?? ""));
  1897. }
  1898. function getBackorderGroups()
  1899. {
  1900. $refs = collectBackorderItemRefs();
  1901. $groups = [];
  1902. foreach ($refs as $ref) {
  1903. $key = $ref["product_id"] . "|" . $ref["size"];
  1904. if (!isset($groups[$key])) {
  1905. $groups[$key] = [
  1906. "product_id" => $ref["product_id"],
  1907. "product_name" => $ref["product_name"],
  1908. "size" => $ref["size"],
  1909. "to_be_backordered" => 0,
  1910. "ordered" => 0,
  1911. "items_to_be_backordered" => [],
  1912. "items_ordered" => [],
  1913. ];
  1914. }
  1915. if ($ref["backorder_status"] === "to_be_backordered") {
  1916. $groups[$key]["to_be_backordered"]++;
  1917. $groups[$key]["items_to_be_backordered"][] = $ref;
  1918. } elseif ($ref["backorder_status"] === "ordered") {
  1919. $groups[$key]["ordered"]++;
  1920. $groups[$key]["items_ordered"][] = $ref;
  1921. }
  1922. }
  1923. foreach ($groups as &$group) {
  1924. usort($group["items_to_be_backordered"], "compareBackorderRefs");
  1925. usort($group["items_ordered"], "compareBackorderRefs");
  1926. }
  1927. unset($group);
  1928. $result = array_values($groups);
  1929. usort($result, function ($left, $right) {
  1930. $cmp = strcmp($left["product_name"], $right["product_name"]);
  1931. if ($cmp !== 0) {
  1932. return $cmp;
  1933. }
  1934. return strcmp($left["size"], $right["size"]);
  1935. });
  1936. return $result;
  1937. }
  1938. function applyBackorderBulkUpdate($productId, $size, $fromStatus, $toStatus, $quantity)
  1939. {
  1940. $productId = (int) $productId;
  1941. $size = trim((string) $size);
  1942. $quantity = (int) $quantity;
  1943. if ($productId <= 0 || $quantity <= 0) {
  1944. return [
  1945. "success" => false,
  1946. "message" => "Ungültige Menge oder Artikel.",
  1947. ];
  1948. }
  1949. $refs = collectBackorderItemRefs();
  1950. $candidates = [];
  1951. foreach ($refs as $ref) {
  1952. if (
  1953. $ref["product_id"] !== $productId ||
  1954. $ref["size"] !== $size ||
  1955. $ref["backorder_status"] !== $fromStatus
  1956. ) {
  1957. continue;
  1958. }
  1959. $candidates[] = $ref;
  1960. }
  1961. usort($candidates, "compareBackorderRefs");
  1962. if ($quantity > count($candidates)) {
  1963. return [
  1964. "success" => false,
  1965. "message" =>
  1966. "Nur " .
  1967. count($candidates) .
  1968. " Position(en) verfügbar, " .
  1969. $quantity .
  1970. " angefordert.",
  1971. ];
  1972. }
  1973. $targets = array_slice($candidates, 0, $quantity);
  1974. $orders = getOrders();
  1975. $manualEntries = getManualBackorders();
  1976. $manualChanged = false;
  1977. $now = date("Y-m-d H:i:s");
  1978. $updated = 0;
  1979. foreach ($targets as $target) {
  1980. if (!empty($target["is_manual"])) {
  1981. $manualId = (string) ($target["manual_id"] ?? "");
  1982. foreach ($manualEntries as &$entry) {
  1983. if ($entry["id"] !== $manualId) {
  1984. continue;
  1985. }
  1986. if ($toStatus === "ordered") {
  1987. $entry["backorder_status"] = "ordered";
  1988. $entry["ordered_at"] = $now;
  1989. } else {
  1990. $entry["backorder_status"] = "";
  1991. $entry["ordered_at"] = "";
  1992. }
  1993. $manualChanged = true;
  1994. $updated++;
  1995. break;
  1996. }
  1997. unset($entry);
  1998. continue;
  1999. }
  2000. foreach ($orders as &$order) {
  2001. if ($order["id"] !== $target["order_id"]) {
  2002. continue;
  2003. }
  2004. $itemIndex = $target["item_index"];
  2005. if (!isset($order["items"][$itemIndex])) {
  2006. continue 2;
  2007. }
  2008. if ($toStatus === backorderStatusOrdered()) {
  2009. $order["items"][$itemIndex]["backorder_status"] = backorderStatusOrdered();
  2010. $order["items"][$itemIndex]["ordered_at"] = $now;
  2011. } else {
  2012. $order["items"][$itemIndex]["backorder_status"] = backorderStatusEmpty();
  2013. $order["items"][$itemIndex]["ordered_at"] = "";
  2014. }
  2015. $order["updated_at"] = $now;
  2016. $updated++;
  2017. break;
  2018. }
  2019. unset($order);
  2020. }
  2021. if ($updated === 0) {
  2022. return [
  2023. "success" => false,
  2024. "message" => "Keine Positionen aktualisiert.",
  2025. ];
  2026. }
  2027. if ($manualChanged) {
  2028. $manualEntries = array_values(
  2029. array_filter($manualEntries, function ($entry) {
  2030. return ($entry["backorder_status"] ?? "") !== "";
  2031. }),
  2032. );
  2033. if (!saveManualBackorders($manualEntries)) {
  2034. return [
  2035. "success" => false,
  2036. "message" => "Manuelle Nachbestellungen konnten nicht gespeichert werden.",
  2037. ];
  2038. }
  2039. }
  2040. saveOrders($orders);
  2041. return ["success" => true, "updated" => $updated];
  2042. }
  2043. function markBackorderItemsOrdered($productId, $size, $quantity)
  2044. {
  2045. return applyBackorderBulkUpdate(
  2046. $productId,
  2047. $size,
  2048. "to_be_backordered",
  2049. "ordered",
  2050. $quantity,
  2051. );
  2052. }
  2053. function markBackorderItemsDelivered($productId, $size, $quantity)
  2054. {
  2055. return applyBackorderBulkUpdate($productId, $size, "ordered", "", $quantity);
  2056. }
  2057. function collectNametagOrderItemRefs()
  2058. {
  2059. $nametagProductName = getNametagProductName();
  2060. $refs = [];
  2061. foreach (getOrders() as $order) {
  2062. if (($order["status"] ?? "") === "cancelled") {
  2063. continue;
  2064. }
  2065. foreach ($order["items"] as $itemIndex => $item) {
  2066. if (!empty($item["is_processed"])) {
  2067. continue;
  2068. }
  2069. if (
  2070. trim((string) ($item["product_name"] ?? "")) !==
  2071. $nametagProductName
  2072. ) {
  2073. continue;
  2074. }
  2075. $refs[] = [
  2076. "order_id" => $order["id"],
  2077. "item_index" => (int) $itemIndex,
  2078. "person_name" => $order["customer_name"],
  2079. "organization_label" => $order["organization_label"],
  2080. "size" => $item["size"],
  2081. "availability_label" => $item["availability_label"],
  2082. "backorder_status" => trim(
  2083. (string) ($item["backorder_status"] ?? ""),
  2084. ),
  2085. "created_at" => $order["created_at"],
  2086. "ordered_at" => trim((string) ($item["ordered_at"] ?? "")),
  2087. ];
  2088. }
  2089. }
  2090. return $refs;
  2091. }
  2092. function getOutstandingNametagOrderItems()
  2093. {
  2094. $refs = array_values(
  2095. array_filter(collectNametagOrderItemRefs(), function ($ref) {
  2096. return $ref["backorder_status"] === "" ||
  2097. $ref["backorder_status"] === backorderStatusToBeBackordered();
  2098. }),
  2099. );
  2100. usort($refs, function ($left, $right) {
  2101. return strcmp($left["created_at"], $right["created_at"]);
  2102. });
  2103. return $refs;
  2104. }
  2105. function getOrderedNametagOrderItems()
  2106. {
  2107. $refs = array_values(
  2108. array_filter(collectNametagOrderItemRefs(), function ($ref) {
  2109. return $ref["backorder_status"] === backorderStatusOrdered();
  2110. }),
  2111. );
  2112. usort($refs, function ($left, $right) {
  2113. return strcmp($left["ordered_at"], $right["ordered_at"]);
  2114. });
  2115. return $refs;
  2116. }
  2117. function markNametagOrderItemOrdered($orderId, $itemIndex)
  2118. {
  2119. $nametagProductName = getNametagProductName();
  2120. $orders = getOrders();
  2121. $now = date("Y-m-d H:i:s");
  2122. foreach ($orders as &$order) {
  2123. if ($order["id"] !== $orderId) {
  2124. continue;
  2125. }
  2126. $guard = orderItemCanBeManaged($order);
  2127. if (!$guard["success"]) {
  2128. return $guard;
  2129. }
  2130. if (!isset($order["items"][$itemIndex])) {
  2131. return ["success" => false, "message" => "Position nicht gefunden."];
  2132. }
  2133. $item = $order["items"][$itemIndex];
  2134. if (
  2135. trim((string) ($item["product_name"] ?? "")) !== $nametagProductName
  2136. ) {
  2137. return [
  2138. "success" => false,
  2139. "message" => "Position ist kein Namensschild.",
  2140. ];
  2141. }
  2142. if (!empty($item["is_processed"])) {
  2143. return [
  2144. "success" => false,
  2145. "message" =>
  2146. "Bearbeitete Positionen können nicht als bestellt markiert werden.",
  2147. ];
  2148. }
  2149. $currentBackorderStatus = trim(
  2150. (string) ($item["backorder_status"] ?? ""),
  2151. );
  2152. if (
  2153. $currentBackorderStatus !== "" &&
  2154. $currentBackorderStatus !== backorderStatusToBeBackordered()
  2155. ) {
  2156. return [
  2157. "success" => false,
  2158. "message" => "Position wurde bereits bestellt.",
  2159. ];
  2160. }
  2161. $order["items"][$itemIndex]["backorder_status"] = backorderStatusOrdered();
  2162. $order["items"][$itemIndex]["ordered_at"] = $now;
  2163. $order["updated_at"] = $now;
  2164. if (!saveOrders($orders)) {
  2165. return [
  2166. "success" => false,
  2167. "message" =>
  2168. "Namensschild-Bestellung konnte nicht gespeichert werden.",
  2169. ];
  2170. }
  2171. return ["success" => true];
  2172. }
  2173. unset($order);
  2174. return ["success" => false, "message" => "Bestellung nicht gefunden."];
  2175. }
  2176. function markNametagOrderItemDelivered($orderId, $itemIndex)
  2177. {
  2178. $orders = getOrders();
  2179. $now = date("Y-m-d H:i:s");
  2180. foreach ($orders as &$order) {
  2181. if ($order["id"] !== $orderId) {
  2182. continue;
  2183. }
  2184. $guard = orderItemCanBeManaged($order);
  2185. if (!$guard["success"]) {
  2186. return $guard;
  2187. }
  2188. if (!isset($order["items"][$itemIndex])) {
  2189. return ["success" => false, "message" => "Position nicht gefunden."];
  2190. }
  2191. $item = $order["items"][$itemIndex];
  2192. if (
  2193. trim((string) ($item["backorder_status"] ?? "")) !==
  2194. backorderStatusOrdered()
  2195. ) {
  2196. return [
  2197. "success" => false,
  2198. "message" => "Position wartet nicht auf Lieferung.",
  2199. ];
  2200. }
  2201. $order["items"][$itemIndex]["backorder_status"] = backorderStatusEmpty();
  2202. $order["items"][$itemIndex]["ordered_at"] = "";
  2203. $order["updated_at"] = $now;
  2204. if (!saveOrders($orders)) {
  2205. return [
  2206. "success" => false,
  2207. "message" =>
  2208. "Namensschild-Bestellung konnte nicht gespeichert werden.",
  2209. ];
  2210. }
  2211. return ["success" => true];
  2212. }
  2213. unset($order);
  2214. return ["success" => false, "message" => "Bestellung nicht gefunden."];
  2215. }
  2216. function orderHasBackorder($order)
  2217. {
  2218. if (!is_array($order["items"] ?? null)) {
  2219. return false;
  2220. }
  2221. foreach ($order["items"] as $item) {
  2222. if (($item["backorder_status"] ?? "") !== "") {
  2223. return true;
  2224. }
  2225. }
  2226. return false;
  2227. }
  2228. function getOrderOpenBackorderSummary($order)
  2229. {
  2230. $statuses = [];
  2231. if (!is_array($order["items"] ?? null)) {
  2232. return ["label" => "", "class" => ""];
  2233. }
  2234. foreach ($order["items"] as $item) {
  2235. if (!empty($item["is_processed"])) {
  2236. continue;
  2237. }
  2238. $status = trim((string) ($item["backorder_status"] ?? ""));
  2239. if ($status !== "") {
  2240. $statuses[$status] = true;
  2241. }
  2242. }
  2243. if ($statuses === []) {
  2244. return ["label" => "", "class" => ""];
  2245. }
  2246. if (count($statuses) > 1) {
  2247. return ["label" => "Gemischt", "class" => "status-backorder"];
  2248. }
  2249. $status = array_key_first($statuses);
  2250. return [
  2251. "label" => getBackorderStatusLabel($status),
  2252. "class" => getBackorderStatusClass($status),
  2253. ];
  2254. }
  2255. function getBackorderStatusLabel($status)
  2256. {
  2257. switch ((string) $status) {
  2258. case "to_be_backordered":
  2259. return "Nachzubestellen";
  2260. case "ordered":
  2261. return "Wartet auf Lieferung";
  2262. default:
  2263. return "-";
  2264. }
  2265. }
  2266. function getBackorderStatusClass($status)
  2267. {
  2268. switch ((string) $status) {
  2269. case "to_be_backordered":
  2270. return "status-backorder";
  2271. case "ordered":
  2272. return "status-backorder-waiting";
  2273. default:
  2274. return "";
  2275. }
  2276. }
  2277. function getOrderStatusLabel($order)
  2278. {
  2279. if (($order["status"] ?? "") === "cancelled") {
  2280. return "Storniert";
  2281. }
  2282. if (($order["status"] ?? "") === "processed") {
  2283. return "Bearbeitet";
  2284. }
  2285. if (($order["status"] ?? "") === "partial") {
  2286. return "Teilweise bearbeitet";
  2287. }
  2288. return "Offen";
  2289. }
  2290. function getOrderStatusClass($order)
  2291. {
  2292. if (($order["status"] ?? "") === "cancelled") {
  2293. return "status-cancelled";
  2294. }
  2295. if (($order["status"] ?? "") === "processed") {
  2296. return "status-processed";
  2297. }
  2298. if (($order["status"] ?? "") === "partial") {
  2299. return "status-partial";
  2300. }
  2301. return "status-open";
  2302. }
  2303. function formatDate($dateString)
  2304. {
  2305. $dateString = trim((string) $dateString);
  2306. if ($dateString === "") {
  2307. return "-";
  2308. }
  2309. try {
  2310. $date = new DateTimeImmutable($dateString);
  2311. return $date->format("d.m.Y H:i");
  2312. } catch (Exception $exception) {
  2313. return $dateString;
  2314. }
  2315. }
  2316. function getCart()
  2317. {
  2318. $cart = $_SESSION["cart"] ?? [];
  2319. if (!is_array($cart)) {
  2320. $cart = [];
  2321. }
  2322. $normalized = [];
  2323. foreach ($cart as $item) {
  2324. $productId = isset($item["product_id"]) ? (int) $item["product_id"] : 0;
  2325. $size = trim((string) ($item["size"] ?? ""));
  2326. $product = getProductById($productId);
  2327. if ($product === null) {
  2328. continue;
  2329. }
  2330. $sizes = getProductSizes($product);
  2331. if (!empty($sizes)) {
  2332. if ($size === "" || !in_array($size, $sizes, true)) {
  2333. continue;
  2334. }
  2335. } else {
  2336. $size = "";
  2337. }
  2338. if (isset($normalized[$productId])) {
  2339. unset($normalized[$productId]);
  2340. }
  2341. $normalized[$productId] = [
  2342. "product_id" => $productId,
  2343. "size" => $size,
  2344. ];
  2345. }
  2346. $_SESSION["cart"] = array_values($normalized);
  2347. return $_SESSION["cart"];
  2348. }
  2349. function addCartItem($productId, $size = "")
  2350. {
  2351. $productId = (int) $productId;
  2352. $size = trim((string) $size);
  2353. $product = getProductById($productId);
  2354. if ($product === null) {
  2355. return [
  2356. "success" => false,
  2357. "status" => "error",
  2358. ];
  2359. }
  2360. $sizes = getProductSizes($product);
  2361. if (!empty($sizes)) {
  2362. if ($size === "" || !in_array($size, $sizes, true)) {
  2363. return [
  2364. "success" => false,
  2365. "status" => "error",
  2366. ];
  2367. }
  2368. } else {
  2369. $size = "";
  2370. }
  2371. $cart = getCart();
  2372. foreach ($cart as $index => $item) {
  2373. if ((int) $item["product_id"] !== $productId) {
  2374. continue;
  2375. }
  2376. $existingSize = trim((string) ($item["size"] ?? ""));
  2377. if ($existingSize === $size) {
  2378. return [
  2379. "success" => true,
  2380. "status" => "unchanged",
  2381. "size" => $size,
  2382. ];
  2383. }
  2384. $cart[$index]["size"] = $size;
  2385. $_SESSION["cart"] = array_values($cart);
  2386. return [
  2387. "success" => true,
  2388. "status" => "replaced",
  2389. "size" => $size,
  2390. "previous_size" => $existingSize,
  2391. ];
  2392. }
  2393. $cart[] = [
  2394. "product_id" => $productId,
  2395. "size" => $size,
  2396. ];
  2397. $_SESSION["cart"] = array_values($cart);
  2398. return [
  2399. "success" => true,
  2400. "status" => "added",
  2401. "size" => $size,
  2402. ];
  2403. }
  2404. function removeCartItem($productId, $size)
  2405. {
  2406. $productId = (int) $productId;
  2407. $size = trim((string) $size);
  2408. $cart = getCart();
  2409. $filtered = [];
  2410. foreach ($cart as $item) {
  2411. $itemProductId = (int) ($item["product_id"] ?? 0);
  2412. $itemSize = trim((string) ($item["size"] ?? ""));
  2413. if ($itemProductId === $productId && $itemSize === $size) {
  2414. continue;
  2415. }
  2416. $filtered[] = $item;
  2417. }
  2418. $_SESSION["cart"] = array_values($filtered);
  2419. }
  2420. function clearCart()
  2421. {
  2422. $_SESSION["cart"] = [];
  2423. }
  2424. function getCartItemsDetailed()
  2425. {
  2426. $items = [];
  2427. foreach (getCart() as $cartItem) {
  2428. $product = getProductById($cartItem["product_id"]);
  2429. if ($product === null) {
  2430. continue;
  2431. }
  2432. $size = trim((string) ($cartItem["size"] ?? ""));
  2433. $items[] = [
  2434. "product" => $product,
  2435. "size" => $size,
  2436. "availability_label" =>
  2437. $size !== "" ? getAvailabilityLabel($product, $size) : "",
  2438. ];
  2439. }
  2440. return $items;
  2441. }
  2442. function buildOrderItemsFromCart()
  2443. {
  2444. $items = [];
  2445. foreach (getCart() as $cartItem) {
  2446. $product = getProductById($cartItem["product_id"]);
  2447. if ($product === null) {
  2448. continue;
  2449. }
  2450. $size = trim((string) ($cartItem["size"] ?? ""));
  2451. $items[] = [
  2452. "product_id" => $product["id"],
  2453. "size" => $size,
  2454. "is_processed" => false,
  2455. ];
  2456. }
  2457. return normalizeOrderItems($items);
  2458. }
  2459. function buildOrderItemsHtml($order)
  2460. {
  2461. $parts = [];
  2462. foreach ($order["items"] as $item) {
  2463. $label = "<strong>" . escape($item["product_name"]) . "</strong>";
  2464. if ($item["size"] !== "") {
  2465. $label .= " - Größe: " . escape($item["size"]);
  2466. }
  2467. if (!empty($item["availability_label"])) {
  2468. $label .=
  2469. "<br><small>" .
  2470. nl2br(escape($item["availability_label"])) .
  2471. "</small>";
  2472. }
  2473. $parts[] =
  2474. '<li style="margin: 0 0 0.75rem 0; padding: 0.9rem 1rem; background: #f8f4e7; border: 1px solid #d7ceb5; border-radius: 18px; color: #111111;">' .
  2475. $label .
  2476. "</li>";
  2477. }
  2478. return '<ul style="list-style: none; margin: 0; padding: 0;">' .
  2479. implode("", $parts) .
  2480. "</ul>";
  2481. }
  2482. function buildOrderSummaryHtml($order, $title, $introHtml, $extraHtml = "")
  2483. {
  2484. $itemsHtml = buildOrderItemsHtml($order);
  2485. return '
  2486. <html>
  2487. <head>
  2488. <meta charset="UTF-8">
  2489. </head>
  2490. <body style="font-family: \'Freising Sans\', Arial, sans-serif; line-height: 1.6; color: #111111; background: #f4efe1; padding: 1.5rem;">
  2491. <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);">
  2492. <p style="margin: 0 0 0.5rem; font-size: 0.8rem; letter-spacing: 0.08em; text-transform: uppercase; color: #5e5a4d;">' .
  2493. escape(SITE_DEPARTMENT_NAME) .
  2494. '</p>
  2495. <h1 style="margin: 0; font-size: 1.75rem; line-height: 1.2; color: #111111;">' .
  2496. escape(SITE_NAME) .
  2497. '</h1>
  2498. <p style="margin: 0.25rem 0 1.5rem; font-size: 1rem; color: #5e5a4d;">' .
  2499. escape(SITE_SERVICE_HEADER) .
  2500. '</p>
  2501. <div style="width: 80px; height: 6px; border-radius: 999px; background: #ffd71c; margin-bottom: 1.5rem;"></div>
  2502. <h2 style="color: #111111; margin-top: 0;">' .
  2503. escape($title) .
  2504. '</h2>
  2505. ' .
  2506. $introHtml .
  2507. '
  2508. <div style="background: #f8f4e7; border: 2px solid #ffd71c; padding: 1.5rem; margin: 1.5rem 0; border-radius: 20px;">
  2509. <h3 style="margin-top: 0;">Bestellnummer</h3>
  2510. <p style="margin: 0; color: #111111; font-family: monospace; font-size: 1.05rem;">' .
  2511. escape($order["id"]) .
  2512. '</p>
  2513. </div>
  2514. <p><strong>Name:</strong> ' .
  2515. escape($order["customer_name"]) .
  2516. '</p>
  2517. <p><strong>E-Mail:</strong> ' .
  2518. escape($order["customer_email"]) .
  2519. '</p>
  2520. <p><strong>Organisation:</strong> ' .
  2521. escape($order["organization_label"]) .
  2522. '</p>
  2523. <p><strong>Erstellt am:</strong> ' .
  2524. escape(formatDate($order["created_at"])) .
  2525. '</p>
  2526. <h3>Bestellte Artikel</h3>
  2527. <div style="background: #fffdf6; border: 1px solid #d7ceb5; border-left: 6px solid #ffd71c; border-radius: 20px; padding: 1rem;">' .
  2528. $itemsHtml .
  2529. '</div>
  2530. <p><strong>Kommentar:</strong><br>' .
  2531. ($order["comment"] !== ""
  2532. ? nl2br(escape($order["comment"]))
  2533. : "Kein Kommentar") .
  2534. '</p>
  2535. ' .
  2536. $extraHtml .
  2537. '
  2538. <p style="margin: 2rem 0 0; color: #5e5a4d; font-size: 0.9rem;">' .
  2539. escape(SITE_NAME) .
  2540. " | " .
  2541. escape(SITE_DEPARTMENT_NAME) .
  2542. "<br>" .
  2543. escape(SITE_ADDRESS_LINE) .
  2544. '</p>
  2545. </div>
  2546. </body>
  2547. </html>';
  2548. }
  2549. function sendOrderCreatedCustomerEmail($order)
  2550. {
  2551. $subject = SITE_SERVICE_NAME . ": Ihre Bestellung - " . $order["id"];
  2552. $intro =
  2553. "<p>Guten Tag " .
  2554. escape($order["customer_name"]) .
  2555. ",</p><p>Ihre Bestellung wurde erfasst und an " .
  2556. escape(SITE_DEPARTMENT_NAME) .
  2557. " weitergeleitet.</p>";
  2558. $message = buildOrderSummaryHtml($order, "Bestellung eingegangen", $intro);
  2559. return sendEmail($order["customer_email"], $subject, $message);
  2560. }
  2561. function sendConfirmedOrderAdminNotification($order)
  2562. {
  2563. $recipient = getOrderRecipientEmail();
  2564. if (!isValidAdminEmail($recipient)) {
  2565. return false;
  2566. }
  2567. $subject = SITE_SERVICE_NAME . ": Neue Bestellung - " . $order["id"];
  2568. $intro =
  2569. "<p>Eine neue PSA-Bestellung ist eingegangen und muss bearbeitet werden.</p>";
  2570. $message = buildOrderSummaryHtml($order, "Neue PSA-Bestellung", $intro);
  2571. $attachments = [];
  2572. if (shouldAttachOrderPdfToAdminEmail()) {
  2573. $attachments[] = [
  2574. "filename" => "bestellung-" . strtolower($order["id"]) . ".pdf",
  2575. "content_type" => "application/pdf",
  2576. "content" => renderOrderPdf($order),
  2577. ];
  2578. }
  2579. return sendEmail($recipient, $subject, $message, true, $attachments);
  2580. }
  2581. function sendEmail($to, $subject, $message, $isHtml = true, $attachments = [])
  2582. {
  2583. $headers = [];
  2584. $headers[] = "From: " . FROM_NAME . " <" . FROM_EMAIL . ">";
  2585. $headers[] = "Reply-To: " . FROM_EMAIL;
  2586. $headers[] = "X-Mailer: PHP/" . phpversion();
  2587. if (empty($attachments)) {
  2588. if ($isHtml) {
  2589. $headers[] = "MIME-Version: 1.0";
  2590. $headers[] = "Content-Type: text/html; charset=UTF-8";
  2591. } else {
  2592. $headers[] = "Content-Type: text/plain; charset=UTF-8";
  2593. }
  2594. return mail($to, $subject, $message, implode("\r\n", $headers));
  2595. }
  2596. $boundary = "=_Boundary_" . bin2hex(random_bytes(8));
  2597. $headers[] = "MIME-Version: 1.0";
  2598. $headers[] = 'Content-Type: multipart/mixed; boundary="' . $boundary . '"';
  2599. $body = [];
  2600. $body[] = "--" . $boundary;
  2601. $body[] =
  2602. "Content-Type: " .
  2603. ($isHtml ? "text/html" : "text/plain") .
  2604. "; charset=UTF-8";
  2605. $body[] = "Content-Transfer-Encoding: 8bit";
  2606. $body[] = "";
  2607. $body[] = $message;
  2608. foreach ($attachments as $attachment) {
  2609. if (!is_array($attachment)) {
  2610. continue;
  2611. }
  2612. $filename = trim(
  2613. (string) ($attachment["filename"] ?? "attachment.bin"),
  2614. );
  2615. $contentType = trim(
  2616. (string) ($attachment["content_type"] ??
  2617. "application/octet-stream"),
  2618. );
  2619. $content = isset($attachment["content"])
  2620. ? (string) $attachment["content"]
  2621. : "";
  2622. $body[] = "--" . $boundary;
  2623. $body[] =
  2624. "Content-Type: " . $contentType . '; name="' . $filename . '"';
  2625. $body[] = "Content-Transfer-Encoding: base64";
  2626. $body[] =
  2627. 'Content-Disposition: attachment; filename="' . $filename . '"';
  2628. $body[] = "";
  2629. $body[] = chunk_split(base64_encode($content));
  2630. }
  2631. $body[] = "--" . $boundary . "--";
  2632. $body[] = "";
  2633. return mail(
  2634. $to,
  2635. $subject,
  2636. implode("\r\n", $body),
  2637. implode("\r\n", $headers),
  2638. );
  2639. }
  2640. function pdfEncodeWinAnsi($text)
  2641. {
  2642. $text = str_replace("\r", "", (string) $text);
  2643. if (!function_exists("iconv")) {
  2644. return preg_replace('/[^\x09\x0A\x20-\x7E]/', "?", $text);
  2645. }
  2646. $chars = preg_split("//u", $text, -1, PREG_SPLIT_NO_EMPTY);
  2647. if (!is_array($chars)) {
  2648. $fallback = @iconv("UTF-8", "Windows-1252//TRANSLIT//IGNORE", $text);
  2649. return is_string($fallback) ? $fallback : $text;
  2650. }
  2651. $result = "";
  2652. foreach ($chars as $char) {
  2653. $converted = @iconv("UTF-8", "Windows-1252", $char);
  2654. if ($converted !== false) {
  2655. $result .= $converted;
  2656. continue;
  2657. }
  2658. $fallback = @iconv("UTF-8", "Windows-1252//TRANSLIT", $char);
  2659. if ($fallback !== false && $fallback !== "") {
  2660. $result .= $fallback;
  2661. continue;
  2662. }
  2663. $result .= "?";
  2664. }
  2665. return $result;
  2666. }
  2667. function pdfEscapeText($text)
  2668. {
  2669. $text = str_replace("\\", "\\\\", $text);
  2670. $text = str_replace("(", "\(", $text);
  2671. $text = str_replace(")", "\)", $text);
  2672. return preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', "", $text);
  2673. }
  2674. function pdfWrapAnsiText($text, $maxChars)
  2675. {
  2676. $lines = [];
  2677. $paragraphs = explode("\n", str_replace("\r", "", (string) $text));
  2678. foreach ($paragraphs as $paragraph) {
  2679. $normalized = trim(preg_replace("/\s+/", " ", $paragraph));
  2680. if ($normalized === "") {
  2681. $lines[] = "";
  2682. continue;
  2683. }
  2684. $words = explode(" ", $normalized);
  2685. $current = "";
  2686. foreach ($words as $word) {
  2687. if ($word === "") {
  2688. continue;
  2689. }
  2690. if (strlen($word) > $maxChars) {
  2691. if ($current !== "") {
  2692. $lines[] = $current;
  2693. $current = "";
  2694. }
  2695. $parts = str_split($word, $maxChars);
  2696. $lastIndex = count($parts) - 1;
  2697. for ($i = 0; $i < $lastIndex; $i++) {
  2698. $lines[] = $parts[$i];
  2699. }
  2700. $current = $parts[$lastIndex];
  2701. continue;
  2702. }
  2703. $candidate = $current === "" ? $word : $current . " " . $word;
  2704. if (strlen($candidate) <= $maxChars) {
  2705. $current = $candidate;
  2706. } else {
  2707. if ($current !== "") {
  2708. $lines[] = $current;
  2709. }
  2710. $current = $word;
  2711. }
  2712. }
  2713. if ($current !== "") {
  2714. $lines[] = $current;
  2715. }
  2716. }
  2717. if (empty($lines)) {
  2718. $lines[] = "";
  2719. }
  2720. return $lines;
  2721. }
  2722. function prepareOrderForDocument(array $order): array
  2723. {
  2724. $items = [];
  2725. foreach ($order["items"] ?? [] as $item) {
  2726. if (!is_array($item)) {
  2727. continue;
  2728. }
  2729. $items[] = [
  2730. "product_name" => trim((string) ($item["product_name"] ?? "")),
  2731. "size" => trim((string) ($item["size"] ?? "")),
  2732. "availability_label" => trim(
  2733. (string) ($item["availability_label"] ?? ""),
  2734. ),
  2735. ];
  2736. }
  2737. return [
  2738. "id" => trim((string) ($order["id"] ?? "")),
  2739. "created_at" => trim((string) ($order["created_at"] ?? "")),
  2740. "customer_name" => trim((string) ($order["customer_name"] ?? "")),
  2741. "customer_email" => trim((string) ($order["customer_email"] ?? "")),
  2742. "organization_label" => trim(
  2743. (string) ($order["organization_label"] ?? ""),
  2744. ),
  2745. "comment" => (string) ($order["comment"] ?? ""),
  2746. "items" => $items,
  2747. ];
  2748. }
  2749. function renderOrderPdf(array $order): string
  2750. {
  2751. return generateOrderPdf(prepareOrderForDocument($order));
  2752. }
  2753. function streamOrderPdf(
  2754. array $order,
  2755. string $filename,
  2756. bool $inline = true,
  2757. ): void {
  2758. $pdf = renderOrderPdf($order);
  2759. $safeFilename = preg_replace('/[^A-Za-z0-9._-]+/', "-", $filename) ?: "bestellung.pdf";
  2760. $disposition = $inline ? "inline" : "attachment";
  2761. header("Content-Type: application/pdf");
  2762. header(
  2763. 'Content-Disposition: ' .
  2764. $disposition .
  2765. '; filename="' .
  2766. $safeFilename .
  2767. '"',
  2768. );
  2769. header("Content-Length: " . strlen($pdf));
  2770. echo $pdf;
  2771. exit();
  2772. }
  2773. function generateOrderPdf($order)
  2774. {
  2775. $pageWidth = 595;
  2776. $pageHeight = 842;
  2777. $leftMargin = 45;
  2778. $topY = 800;
  2779. $bottomY = 60;
  2780. $lineHeight = 14;
  2781. $itemLineHeight = 16;
  2782. $pages = [];
  2783. $pageContent = "";
  2784. $y = $topY;
  2785. $pageNumber = 0;
  2786. $encodeText = function ($text) {
  2787. return pdfEncodeWinAnsi((string) $text);
  2788. };
  2789. $orderId = $encodeText($order["id"]);
  2790. $createdAt = $encodeText(formatDate($order["created_at"]));
  2791. $customerName = $encodeText($order["customer_name"]);
  2792. $customerEmail = $encodeText($order["customer_email"]);
  2793. $organization = $encodeText($order["organization_label"]);
  2794. $commentRaw = (string) $order["comment"];
  2795. $writeText = function ($x, $y, $encodedText, $fontSize = 12) use (&$pageContent) {
  2796. $pageContent .=
  2797. "BT\n/F1 " .
  2798. $fontSize .
  2799. " Tf\n1 0 0 1 " .
  2800. number_format($x, 2, ".", "") .
  2801. " " .
  2802. number_format($y, 2, ".", "") .
  2803. " Tm\n(" .
  2804. pdfEscapeText($encodedText) .
  2805. ") Tj\nET\n";
  2806. };
  2807. $startPage = function () use (
  2808. &$pages,
  2809. &$pageContent,
  2810. &$y,
  2811. &$pageNumber,
  2812. $topY,
  2813. $leftMargin,
  2814. $lineHeight,
  2815. $orderId,
  2816. $createdAt,
  2817. $writeText,
  2818. $encodeText
  2819. ) {
  2820. if ($pageContent !== "") {
  2821. $pages[] = $pageContent;
  2822. }
  2823. $pageNumber++;
  2824. $pageContent = "";
  2825. $y = $topY;
  2826. $headerLine = "Bestellung: " . $orderId;
  2827. if ($pageNumber > 1) {
  2828. $headerLine .= " | Seite " . $encodeText((string) $pageNumber);
  2829. }
  2830. $writeText($leftMargin, $y, $headerLine, 14);
  2831. $y -= 19;
  2832. $writeText($leftMargin, $y, "Erstellt am: " . $createdAt, 11);
  2833. $y -= 20;
  2834. };
  2835. $ensureSpace = function ($requiredHeight) use (&$y, $bottomY, $startPage) {
  2836. if ($y - $requiredHeight < $bottomY) {
  2837. $startPage();
  2838. }
  2839. };
  2840. $writeWrapped = function (
  2841. $encodedText,
  2842. $maxChars,
  2843. $fontSize = 11,
  2844. $x = null,
  2845. $spacing = null
  2846. ) use (&$y, $lineHeight, $leftMargin, $writeText, $ensureSpace) {
  2847. $targetX = $x === null ? $leftMargin : $x;
  2848. $step = $spacing === null ? $lineHeight : $spacing;
  2849. $lines = pdfWrapAnsiText($encodedText, $maxChars);
  2850. foreach ($lines as $line) {
  2851. $ensureSpace($step);
  2852. $writeText($targetX, $y, $line, $fontSize);
  2853. $y -= $step;
  2854. }
  2855. };
  2856. $writeSectionTitle = function ($titleText, $fontSize = 13) use (
  2857. &$y,
  2858. $leftMargin,
  2859. $writeText,
  2860. $ensureSpace,
  2861. $encodeText
  2862. ) {
  2863. $ensureSpace(24);
  2864. $writeText($leftMargin, $y, $encodeText($titleText), $fontSize);
  2865. $y -= 18;
  2866. };
  2867. $startPage();
  2868. $writeSectionTitle("Gehört zu");
  2869. $writeWrapped("Name: " . $customerName, 80);
  2870. $writeWrapped("Organisation: " . $organization, 80);
  2871. $writeWrapped("E-Mail: " . $customerEmail, 80);
  2872. $y -= 6;
  2873. $writeSectionTitle("Artikelliste", 15);
  2874. $itemNumber = 1;
  2875. if (empty($order["items"])) {
  2876. $writeWrapped($encodeText("Keine Artikel"), 80, 12);
  2877. } else {
  2878. foreach ($order["items"] as $item) {
  2879. $itemName = $encodeText($item["product_name"]);
  2880. $sizeLabel = $encodeText($item["size"]);
  2881. $hintLabel = $encodeText(
  2882. preg_replace("/\s+/", " ", (string) $item["availability_label"]),
  2883. );
  2884. $writeWrapped(
  2885. $encodeText($itemNumber . ". ") . $itemName,
  2886. 68,
  2887. 14,
  2888. null,
  2889. $itemLineHeight,
  2890. );
  2891. if ($sizeLabel !== "") {
  2892. $writeWrapped(
  2893. $encodeText(" Größe: ") . $sizeLabel,
  2894. 66,
  2895. 12,
  2896. null,
  2897. $itemLineHeight,
  2898. );
  2899. }
  2900. if ($hintLabel !== "") {
  2901. $writeWrapped(
  2902. $encodeText(" Hinweis: ") . $hintLabel,
  2903. 66,
  2904. 12,
  2905. null,
  2906. $itemLineHeight,
  2907. );
  2908. }
  2909. $ensureSpace(40);
  2910. $y -= 40;
  2911. $itemNumber++;
  2912. }
  2913. }
  2914. $y -= 4;
  2915. $writeSectionTitle("Kommentar");
  2916. if (trim($commentRaw) === "") {
  2917. $writeWrapped($encodeText("Kein Kommentar"), 80);
  2918. } else {
  2919. foreach (preg_split('/\r\n|\r|\n/', $commentRaw) as $commentLine) {
  2920. $writeWrapped($encodeText($commentLine), 82);
  2921. }
  2922. }
  2923. $y -= 6;
  2924. $writeSectionTitle("Lagerbearbeitung");
  2925. $warehouseLines = [
  2926. "Ausgegeben am / durch: __________________________________________________",
  2927. "[ ] Vollständig ausgegeben",
  2928. "[ ] Teilweise ausgegeben",
  2929. ];
  2930. foreach ($warehouseLines as $line) {
  2931. $writeWrapped($encodeText($line), 80);
  2932. }
  2933. if ($pageContent !== "") {
  2934. $pages[] = $pageContent;
  2935. }
  2936. if (empty($pages)) {
  2937. $pages[] = "";
  2938. }
  2939. $fontObjectNumber = 3;
  2940. $objects = [];
  2941. $objects[1] = "1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n";
  2942. $objects[
  2943. $fontObjectNumber
  2944. ] = "3 0 obj\n<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>\nendobj\n";
  2945. $kids = [];
  2946. $nextObjectNumber = 4;
  2947. foreach ($pages as $pageStream) {
  2948. $pageObjectNumber = $nextObjectNumber++;
  2949. $contentObjectNumber = $nextObjectNumber++;
  2950. $kids[] = $pageObjectNumber . " 0 R";
  2951. $objects[$pageObjectNumber] =
  2952. $pageObjectNumber .
  2953. " 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 " .
  2954. $pageWidth .
  2955. " " .
  2956. $pageHeight .
  2957. "] /Contents " .
  2958. $contentObjectNumber .
  2959. " 0 R /Resources << /Font << /F1 " .
  2960. $fontObjectNumber .
  2961. " 0 R >> >> >>\nendobj\n";
  2962. $objects[$contentObjectNumber] =
  2963. $contentObjectNumber .
  2964. " 0 obj\n<< /Length " .
  2965. strlen($pageStream) .
  2966. " >>\nstream\n" .
  2967. $pageStream .
  2968. "\nendstream\nendobj\n";
  2969. }
  2970. $objects[2] =
  2971. "2 0 obj\n<< /Type /Pages /Kids [" .
  2972. implode(" ", $kids) .
  2973. "] /Count " .
  2974. count($kids) .
  2975. " >>\nendobj\n";
  2976. ksort($objects);
  2977. $pdf = "%PDF-1.4\n";
  2978. $offsets = [0];
  2979. foreach ($objects as $number => $objectContent) {
  2980. $offsets[$number] = strlen($pdf);
  2981. $pdf .= $objectContent;
  2982. }
  2983. $lastObjectNumber = (int) max(array_keys($objects));
  2984. $xrefOffset = strlen($pdf);
  2985. $pdf .= "xref\n0 " . ($lastObjectNumber + 1) . "\n";
  2986. $pdf .= "0000000000 65535 f \n";
  2987. for ($i = 1; $i <= $lastObjectNumber; $i++) {
  2988. if (isset($offsets[$i])) {
  2989. $pdf .= sprintf("%010d 00000 n \n", $offsets[$i]);
  2990. } else {
  2991. $pdf .= "0000000000 00000 f \n";
  2992. }
  2993. }
  2994. $pdf .= "trailer\n<< /Size " . ($lastObjectNumber + 1) . " /Root 1 0 R >>\n";
  2995. $pdf .= "startxref\n" . $xrefOffset . "\n%%EOF";
  2996. return $pdf;
  2997. }
  2998. /**
  2999. * Input Validation Class
  3000. */
  3001. class Validator
  3002. {
  3003. private $errors = [];
  3004. private $data = [];
  3005. public function __construct($data)
  3006. {
  3007. $this->data = $data;
  3008. }
  3009. public function required($field, $label = null)
  3010. {
  3011. $value = $this->get($field);
  3012. if (empty(trim($value ?? ""))) {
  3013. $this->errors[] = ($label ?? $field) . " ist erforderlich.";
  3014. }
  3015. return $this;
  3016. }
  3017. public function email($field, $label = null)
  3018. {
  3019. $value = $this->get($field);
  3020. if (!empty($value) && !filter_var($value, FILTER_VALIDATE_EMAIL)) {
  3021. $this->errors[] =
  3022. ($label ?? $field) . " muss eine gültige E-Mail-Adresse sein.";
  3023. }
  3024. return $this;
  3025. }
  3026. public function minLength($field, $min, $label = null)
  3027. {
  3028. $value = $this->get($field);
  3029. if (!empty($value) && strlen($value) < $min) {
  3030. $this->errors[] =
  3031. ($label ?? $field) .
  3032. " muss mindestens " .
  3033. $min .
  3034. " Zeichen lang sein.";
  3035. }
  3036. return $this;
  3037. }
  3038. public function maxLength($field, $max, $label = null)
  3039. {
  3040. $value = $this->get($field);
  3041. if (!empty($value) && strlen($value) > $max) {
  3042. $this->errors[] =
  3043. ($label ?? $field) .
  3044. " darf maximal " .
  3045. $max .
  3046. " Zeichen lang sein.";
  3047. }
  3048. return $this;
  3049. }
  3050. public function inArray($field, $allowed, $label = null)
  3051. {
  3052. $value = $this->get($field);
  3053. if (!empty($value) && !in_array($value, $allowed, true)) {
  3054. $this->errors[] = ($label ?? $field) . " ist ungültig.";
  3055. }
  3056. return $this;
  3057. }
  3058. public function get($field)
  3059. {
  3060. return $this->data[$field] ?? null;
  3061. }
  3062. public function addError(string $message): self
  3063. {
  3064. $message = trim($message);
  3065. if ($message !== "") {
  3066. $this->errors[] = $message;
  3067. }
  3068. return $this;
  3069. }
  3070. public function getErrors()
  3071. {
  3072. return $this->errors;
  3073. }
  3074. public function isValid()
  3075. {
  3076. return empty($this->errors);
  3077. }
  3078. }
  3079. /**
  3080. * Error Logging Functions
  3081. */
  3082. if (!defined("LOG_DIR")) {
  3083. define("LOG_DIR", DATA_DIR . "logs/");
  3084. }
  3085. if (!defined("ERROR_LOG_FILE")) {
  3086. define("ERROR_LOG_FILE", LOG_DIR . "error.log");
  3087. }
  3088. if (!defined("ACCESS_LOG_FILE")) {
  3089. define("ACCESS_LOG_FILE", LOG_DIR . "access.log");
  3090. }
  3091. if (!defined("LOG_MAX_BYTES")) {
  3092. define("LOG_MAX_BYTES", 1048576);
  3093. }
  3094. if (!defined("LOG_KEEP_FILES")) {
  3095. define("LOG_KEEP_FILES", 5);
  3096. }
  3097. if (!defined("LOG_MAX_AGE_SECONDS")) {
  3098. define("LOG_MAX_AGE_SECONDS", 2592000);
  3099. }
  3100. function initLogging()
  3101. {
  3102. if (!is_dir(LOG_DIR)) {
  3103. mkdir(LOG_DIR, 02775, true);
  3104. @chmod(LOG_DIR, 02775);
  3105. }
  3106. }
  3107. function rotateLogFileIfNeeded(string $logFile): void
  3108. {
  3109. $maxBytes = max(1024, (int) LOG_MAX_BYTES);
  3110. $keepFiles = max(1, (int) LOG_KEEP_FILES);
  3111. $maxAgeSeconds = max(0, (int) LOG_MAX_AGE_SECONDS);
  3112. $now = time();
  3113. $rotatedFiles = glob($logFile . ".*") ?: [];
  3114. foreach ($rotatedFiles as $rotatedFile) {
  3115. if (preg_match('/\.(\d+)$/', $rotatedFile, $matches) !== 1) {
  3116. continue;
  3117. }
  3118. $index = (int) $matches[1];
  3119. $isTooOld =
  3120. $maxAgeSeconds > 0 &&
  3121. is_file($rotatedFile) &&
  3122. ($now - (int) filemtime($rotatedFile)) > $maxAgeSeconds;
  3123. if ($index > $keepFiles || $isTooOld) {
  3124. @unlink($rotatedFile);
  3125. }
  3126. }
  3127. if (!is_file($logFile) || (filesize($logFile) ?: 0) < $maxBytes) {
  3128. return;
  3129. }
  3130. for ($i = $keepFiles; $i >= 1; $i--) {
  3131. $source = $i === 1 ? $logFile : $logFile . "." . ($i - 1);
  3132. $target = $logFile . "." . $i;
  3133. if (!is_file($source)) {
  3134. continue;
  3135. }
  3136. if ($i === $keepFiles && is_file($target)) {
  3137. @unlink($target);
  3138. }
  3139. @rename($source, $target);
  3140. }
  3141. }
  3142. function logError($message, $context = [], $level = "ERROR")
  3143. {
  3144. initLogging();
  3145. rotateLogFileIfNeeded(ERROR_LOG_FILE);
  3146. $entry = [
  3147. "timestamp" => date("Y-m-d H:i:s.u"),
  3148. "level" => $level,
  3149. "message" => $message,
  3150. "context" => $context,
  3151. "ip" => $_SERVER["REMOTE_ADDR"] ?? "unknown",
  3152. "user_agent" => $_SERVER["HTTP_USER_AGENT"] ?? "unknown",
  3153. "request_uri" => $_SERVER["REQUEST_URI"] ?? "unknown",
  3154. "session_id" => session_id()
  3155. ? substr(session_id(), 0, 8) . "..."
  3156. : "none",
  3157. ];
  3158. $logLine = json_encode($entry, JSON_UNESCAPED_UNICODE) . PHP_EOL;
  3159. file_put_contents(ERROR_LOG_FILE, $logLine, FILE_APPEND | LOCK_EX);
  3160. if (defined("DEVELOPMENT_MODE") && DEVELOPMENT_MODE) {
  3161. error_log(
  3162. "PSA Order: " . $message . " | Context: " . json_encode($context),
  3163. );
  3164. }
  3165. }
  3166. function logAccess($message, $context = [])
  3167. {
  3168. initLogging();
  3169. rotateLogFileIfNeeded(ACCESS_LOG_FILE);
  3170. $entry = [
  3171. "timestamp" => date("Y-m-d H:i:s.u"),
  3172. "message" => $message,
  3173. "context" => $context,
  3174. "ip" => $_SERVER["REMOTE_ADDR"] ?? "unknown",
  3175. "request_method" => $_SERVER["REQUEST_METHOD"] ?? "unknown",
  3176. "request_uri" => $_SERVER["REQUEST_URI"] ?? "unknown",
  3177. ];
  3178. $logLine = json_encode($entry, JSON_UNESCAPED_UNICODE) . PHP_EOL;
  3179. file_put_contents(ACCESS_LOG_FILE, $logLine, FILE_APPEND | LOCK_EX);
  3180. }
  3181. function handleException($exception)
  3182. {
  3183. logError(
  3184. "Uncaught exception: " . $exception->getMessage(),
  3185. [
  3186. "file" => $exception->getFile(),
  3187. "line" => $exception->getLine(),
  3188. "trace" => $exception->getTraceAsString(),
  3189. ],
  3190. "CRITICAL",
  3191. );
  3192. if (defined("DEVELOPMENT_MODE") && DEVELOPMENT_MODE) {
  3193. echo "<h1>Error</h1><pre>" .
  3194. escape($exception->getMessage()) .
  3195. "</pre>";
  3196. } else {
  3197. echo "<h1>Es ist ein Fehler aufgetreten</h1><p>Bitte versuchen Sie es später erneut.</p>";
  3198. }
  3199. exit();
  3200. }
  3201. set_exception_handler("handleException");
  3202. function handleError($errno, $errstr, $errfile, $errline)
  3203. {
  3204. if (!(error_reporting() & $errno)) {
  3205. return false;
  3206. }
  3207. logError(
  3208. "PHP Error: " . $errstr,
  3209. [
  3210. "type" => $errno,
  3211. "file" => $errfile,
  3212. "line" => $errline,
  3213. ],
  3214. "WARNING",
  3215. );
  3216. return true;
  3217. }
  3218. set_error_handler("handleError");