functions.php 80 KB

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