functions.php 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758
  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. "order_confirmation_required" => defined("ORDER_CONFIRMATION_REQUIRED")
  856. ? (bool) ORDER_CONFIRMATION_REQUIRED
  857. : false,
  858. "order_confirmation_expiry_days" => defined(
  859. "ORDER_CONFIRMATION_EXPIRY_DAYS",
  860. )
  861. ? (int) ORDER_CONFIRMATION_EXPIRY_DAYS
  862. : 7,
  863. "attach_order_pdf_to_admin_email" => defined(
  864. "ATTACH_ORDER_PDF_TO_ADMIN_EMAIL",
  865. )
  866. ? (bool) ATTACH_ORDER_PDF_TO_ADMIN_EMAIL
  867. : true,
  868. "startpage_intro_text" => $startpageIntroText,
  869. ];
  870. }
  871. function normalizeSystemSettings($settings)
  872. {
  873. $defaults = getDefaultSystemSettings();
  874. if (!is_array($settings)) {
  875. $settings = [];
  876. }
  877. $recipientEmail = normalizeAdminEmail(
  878. $settings["order_recipient_email"] ??
  879. $defaults["order_recipient_email"],
  880. );
  881. if (!isValidAdminEmail($recipientEmail)) {
  882. $recipientEmail = $defaults["order_recipient_email"];
  883. }
  884. $expiryDays = isset($settings["order_confirmation_expiry_days"])
  885. ? (int) $settings["order_confirmation_expiry_days"]
  886. : $defaults["order_confirmation_expiry_days"];
  887. if ($expiryDays < 1) {
  888. $expiryDays = 7;
  889. }
  890. $startpageIntroText = trim(
  891. (string) ($settings["startpage_intro_text"] ?? $defaults["startpage_intro_text"]),
  892. );
  893. return [
  894. "order_recipient_email" => $recipientEmail,
  895. "order_confirmation_required" => !empty(
  896. $settings["order_confirmation_required"]
  897. ),
  898. "order_confirmation_expiry_days" => $expiryDays,
  899. "attach_order_pdf_to_admin_email" => !empty(
  900. $settings["attach_order_pdf_to_admin_email"]
  901. ),
  902. "startpage_intro_text" => $startpageIntroText,
  903. ];
  904. }
  905. function getSystemSettings()
  906. {
  907. $data = readJsonFile(SETTINGS_FILE);
  908. return normalizeSystemSettings($data["settings"] ?? []);
  909. }
  910. function saveSystemSettings($settings)
  911. {
  912. return writeJsonFile(SETTINGS_FILE, [
  913. "settings" => normalizeSystemSettings($settings),
  914. ]);
  915. }
  916. function getOrderRecipientEmail()
  917. {
  918. $settings = getSystemSettings();
  919. return $settings["order_recipient_email"];
  920. }
  921. function isOrderConfirmationRequired()
  922. {
  923. $settings = getSystemSettings();
  924. return !empty($settings["order_confirmation_required"]);
  925. }
  926. function getOrderConfirmationExpiryDays()
  927. {
  928. $settings = getSystemSettings();
  929. return max(1, (int) $settings["order_confirmation_expiry_days"]);
  930. }
  931. function shouldAttachOrderPdfToAdminEmail()
  932. {
  933. $settings = getSystemSettings();
  934. return !empty($settings["attach_order_pdf_to_admin_email"]);
  935. }
  936. function getStartpageIntroLines()
  937. {
  938. $settings = getSystemSettings();
  939. $text = trim((string) ($settings["startpage_intro_text"] ?? ""));
  940. if ($text === "") {
  941. return [];
  942. }
  943. $lines = preg_split('/\R+/', $text) ?: [];
  944. $lines = array_values(
  945. array_filter(
  946. array_map(function ($line) {
  947. return trim((string) $line);
  948. }, $lines),
  949. function ($line) {
  950. return $line !== "";
  951. },
  952. ),
  953. );
  954. return $lines;
  955. }
  956. function normalizeOrderItem($item)
  957. {
  958. if (!is_array($item)) {
  959. return null;
  960. }
  961. $productId = isset($item["product_id"]) ? (int) $item["product_id"] : 0;
  962. if ($productId <= 0) {
  963. return null;
  964. }
  965. $product = getProductById($productId);
  966. if ($product === null) {
  967. return null;
  968. }
  969. $size = trim((string) ($item["size"] ?? ""));
  970. $sizes = getProductSizes($product);
  971. if (!empty($sizes)) {
  972. if ($size === "" || !in_array($size, $sizes, true)) {
  973. return null;
  974. }
  975. } else {
  976. $size = "";
  977. }
  978. return [
  979. "product_id" => $productId,
  980. "product_name" => $product["name"],
  981. "size" => $size,
  982. "availability_label" =>
  983. $size !== "" ? getAvailabilityLabel($product, $size) : "",
  984. "is_processed" => !empty($item["is_processed"]),
  985. ];
  986. }
  987. function normalizeOrderItems($items)
  988. {
  989. $normalized = [];
  990. $seen = [];
  991. if (!is_array($items)) {
  992. return [];
  993. }
  994. foreach ($items as $item) {
  995. $record = normalizeOrderItem($item);
  996. if ($record === null) {
  997. continue;
  998. }
  999. $key = $record["product_id"] . "|" . $record["size"];
  1000. if (isset($seen[$key])) {
  1001. continue;
  1002. }
  1003. $seen[$key] = true;
  1004. $normalized[] = $record;
  1005. }
  1006. return array_values($normalized);
  1007. }
  1008. function getOrders()
  1009. {
  1010. $data = readJsonFile(ORDERS_FILE);
  1011. $orders =
  1012. isset($data["orders"]) && is_array($data["orders"])
  1013. ? $data["orders"]
  1014. : [];
  1015. $normalized = [];
  1016. foreach ($orders as $order) {
  1017. $record = normalizeOrderRecord($order);
  1018. if ($record !== null) {
  1019. $normalized[] = $record;
  1020. }
  1021. }
  1022. return $normalized;
  1023. }
  1024. function saveOrders($orders)
  1025. {
  1026. $normalized = [];
  1027. foreach ($orders as $order) {
  1028. $record = normalizeOrderRecord($order);
  1029. if ($record !== null) {
  1030. $normalized[] = $record;
  1031. }
  1032. }
  1033. $result = writeJsonFile(ORDERS_FILE, [
  1034. "orders" => array_values($normalized),
  1035. ]);
  1036. if (!$result) {
  1037. logError("Failed to save orders", [
  1038. "file" => ORDERS_FILE,
  1039. "order_count" => count($normalized),
  1040. ]);
  1041. }
  1042. return (bool) $result;
  1043. }
  1044. function generateOrderId()
  1045. {
  1046. $orders = getOrders();
  1047. $year = date("Y");
  1048. $prefix = defined("ORDER_PREFIX") ? ORDER_PREFIX : "ORD";
  1049. $max = 0;
  1050. $pattern = "/^" . preg_quote($prefix, "/") . '-\d{4}-(\d+)$/';
  1051. foreach ($orders as $order) {
  1052. if (preg_match($pattern, (string) $order["id"], $matches) === 1) {
  1053. $number = (int) $matches[1];
  1054. if ($number > $max) {
  1055. $max = $number;
  1056. }
  1057. }
  1058. }
  1059. return sprintf("%s-%s-%03d", $prefix, $year, $max + 1);
  1060. }
  1061. function normalizeOrderRecord($order)
  1062. {
  1063. if (!is_array($order)) {
  1064. return null;
  1065. }
  1066. $id = trim((string) ($order["id"] ?? ""));
  1067. $customerName = trim((string) ($order["customer_name"] ?? ""));
  1068. $customerEmail = normalizeAdminEmail($order["customer_email"] ?? "");
  1069. $organizationId = normalizeOrganizationId($order["organization_id"] ?? "");
  1070. $organizationLabel = trim((string) ($order["organization_label"] ?? ""));
  1071. $items = normalizeOrderItems($order["items"] ?? []);
  1072. if (
  1073. $id === "" ||
  1074. $customerName === "" ||
  1075. !isValidAdminEmail($customerEmail) ||
  1076. $organizationId === "" ||
  1077. $organizationLabel === "" ||
  1078. empty($items)
  1079. ) {
  1080. return null;
  1081. }
  1082. $createdAt = trim((string) ($order["created_at"] ?? ""));
  1083. if ($createdAt === "") {
  1084. $createdAt = date("Y-m-d H:i:s");
  1085. }
  1086. $confirmationStatus = trim(
  1087. (string) ($order["confirmation_status"] ?? "confirmed"),
  1088. );
  1089. $allowedConfirmationStatuses = [
  1090. "not_required",
  1091. "pending",
  1092. "confirmed",
  1093. "expired",
  1094. ];
  1095. if (!in_array($confirmationStatus, $allowedConfirmationStatuses, true)) {
  1096. $confirmationStatus = "confirmed";
  1097. }
  1098. $status = trim((string) ($order["status"] ?? "open"));
  1099. $allowedStatuses = ["open", "partial", "processed", "cancelled"];
  1100. if (!in_array($status, $allowedStatuses, true)) {
  1101. $status = "open";
  1102. }
  1103. $normalized = [
  1104. "id" => $id,
  1105. "customer_name" => $customerName,
  1106. "customer_email" => $customerEmail,
  1107. "organization_id" => $organizationId,
  1108. "organization_label" => $organizationLabel,
  1109. "comment" => trim((string) ($order["comment"] ?? "")),
  1110. "items" => $items,
  1111. "status" => $status,
  1112. "confirmation_status" => $confirmationStatus,
  1113. "confirmation_token" => trim(
  1114. (string) ($order["confirmation_token"] ?? ""),
  1115. ),
  1116. "confirmation_expires_at" => trim(
  1117. (string) ($order["confirmation_expires_at"] ?? ""),
  1118. ),
  1119. "confirmed_at" => trim((string) ($order["confirmed_at"] ?? "")),
  1120. "created_at" => $createdAt,
  1121. "updated_at" => trim((string) ($order["updated_at"] ?? $createdAt)),
  1122. "cancelled_at" => trim((string) ($order["cancelled_at"] ?? "")),
  1123. "cancelled_by" => trim((string) ($order["cancelled_by"] ?? "")),
  1124. "cancellation_reason" => trim(
  1125. (string) ($order["cancellation_reason"] ?? ""),
  1126. ),
  1127. "admin_notified_at" => trim(
  1128. (string) ($order["admin_notified_at"] ?? ""),
  1129. ),
  1130. ];
  1131. return refreshOrderState($normalized);
  1132. }
  1133. function refreshOrderState($order)
  1134. {
  1135. if (!is_array($order)) {
  1136. return null;
  1137. }
  1138. if (($order["status"] ?? "") === "cancelled") {
  1139. return $order;
  1140. }
  1141. if (
  1142. ($order["confirmation_status"] ?? "") === "pending" &&
  1143. !empty($order["confirmation_expires_at"])
  1144. ) {
  1145. $expiresAt = strtotime((string) $order["confirmation_expires_at"]);
  1146. if ($expiresAt !== false && time() > $expiresAt) {
  1147. $order["confirmation_status"] = "expired";
  1148. }
  1149. }
  1150. $processedCount = 0;
  1151. foreach ($order["items"] as $item) {
  1152. if (!empty($item["is_processed"])) {
  1153. $processedCount++;
  1154. }
  1155. }
  1156. if ($processedCount <= 0) {
  1157. $order["status"] = "open";
  1158. } elseif ($processedCount >= count($order["items"])) {
  1159. $order["status"] = "processed";
  1160. } else {
  1161. $order["status"] = "partial";
  1162. }
  1163. return $order;
  1164. }
  1165. function expirePendingOrders()
  1166. {
  1167. $orders = getOrders();
  1168. $changed = false;
  1169. foreach ($orders as &$order) {
  1170. $updated = refreshOrderState($order);
  1171. if ($updated !== $order) {
  1172. $order = $updated;
  1173. $changed = true;
  1174. }
  1175. }
  1176. unset($order);
  1177. if ($changed) {
  1178. saveOrders($orders);
  1179. }
  1180. }
  1181. function getOrderById($orderId)
  1182. {
  1183. $orderId = trim((string) $orderId);
  1184. if ($orderId === "") {
  1185. return null;
  1186. }
  1187. foreach (getOrders() as $order) {
  1188. if ($order["id"] === $orderId) {
  1189. return $order;
  1190. }
  1191. }
  1192. return null;
  1193. }
  1194. function findOrderByConfirmationToken($token)
  1195. {
  1196. $token = trim((string) $token);
  1197. if ($token === "") {
  1198. return null;
  1199. }
  1200. foreach (getOrders() as $order) {
  1201. if (($order["confirmation_token"] ?? "") === $token) {
  1202. return $order;
  1203. }
  1204. }
  1205. return null;
  1206. }
  1207. function buildOrderConfirmationUrl($token)
  1208. {
  1209. $path = "/order-confirm.php?token=" . urlencode($token);
  1210. return buildAbsoluteUrl($path);
  1211. }
  1212. function buildAbsoluteUrl($path)
  1213. {
  1214. $path = "/" . ltrim((string) $path, "/");
  1215. $siteUrl = defined("SITE_URL") ? trim((string) SITE_URL) : "";
  1216. if (strpos($siteUrl, "://") !== false) {
  1217. return rtrim($siteUrl, "/") . $path;
  1218. }
  1219. $basePath = trim($siteUrl);
  1220. if ($basePath !== "" && $basePath !== "/") {
  1221. $path = "/" . trim($basePath, "/") . $path;
  1222. }
  1223. $scheme = isHttpsRequest() ? "https" : "http";
  1224. $host = $_SERVER["HTTP_HOST"] ?? "";
  1225. if ($host === "") {
  1226. return $path;
  1227. }
  1228. return $scheme . "://" . $host . $path;
  1229. }
  1230. function isHttpsRequest(): bool
  1231. {
  1232. if (
  1233. !empty($_SERVER["HTTPS"]) &&
  1234. strtolower((string) $_SERVER["HTTPS"]) !== "off"
  1235. ) {
  1236. return true;
  1237. }
  1238. if (
  1239. !empty($_SERVER["HTTP_X_FORWARDED_PROTO"]) &&
  1240. strtolower((string) $_SERVER["HTTP_X_FORWARDED_PROTO"]) === "https"
  1241. ) {
  1242. return true;
  1243. }
  1244. if (
  1245. !empty($_SERVER["SERVER_PORT"]) &&
  1246. (int) $_SERVER["SERVER_PORT"] === 443
  1247. ) {
  1248. return true;
  1249. }
  1250. return false;
  1251. }
  1252. function createOrder(
  1253. $customerName,
  1254. $customerEmail,
  1255. $organizationId,
  1256. $comment,
  1257. $items,
  1258. ) {
  1259. $customerName = sanitize($customerName);
  1260. $customerEmail = normalizeAdminEmail($customerEmail);
  1261. $organizationId = normalizeOrganizationId($organizationId);
  1262. $comment = trim((string) $comment);
  1263. $items = normalizeOrderItems($items);
  1264. if ($customerName === "") {
  1265. return [
  1266. "success" => false,
  1267. "message" => "Bitte geben Sie einen Namen ein.",
  1268. ];
  1269. }
  1270. if (!isValidAdminEmail($customerEmail)) {
  1271. return [
  1272. "success" => false,
  1273. "message" => "Bitte geben Sie eine gültige E-Mail-Adresse ein.",
  1274. ];
  1275. }
  1276. if (empty($items)) {
  1277. return [
  1278. "success" => false,
  1279. "message" =>
  1280. "Der Warenkorb ist leer oder enthält ungültige Positionen.",
  1281. ];
  1282. }
  1283. $organization = getOrganizationById($organizationId);
  1284. if ($organization === null || empty($organization["active"])) {
  1285. return [
  1286. "success" => false,
  1287. "message" => "Bitte wählen Sie eine gültige Organisation aus.",
  1288. ];
  1289. }
  1290. $now = date("Y-m-d H:i:s");
  1291. $requiresConfirmation = isOrderConfirmationRequired();
  1292. $confirmationToken = $requiresConfirmation ? bin2hex(random_bytes(24)) : "";
  1293. $confirmationExpiresAt = "";
  1294. if ($requiresConfirmation) {
  1295. $expires = new DateTimeImmutable();
  1296. $expires = $expires->modify(
  1297. "+" . getOrderConfirmationExpiryDays() . " days",
  1298. );
  1299. $confirmationExpiresAt = $expires->format("Y-m-d H:i:s");
  1300. }
  1301. $order = [
  1302. "id" => generateOrderId(),
  1303. "customer_name" => $customerName,
  1304. "customer_email" => $customerEmail,
  1305. "organization_id" => $organization["id"],
  1306. "organization_label" => $organization["label"],
  1307. "comment" => $comment,
  1308. "items" => $items,
  1309. "status" => "open",
  1310. "confirmation_status" => $requiresConfirmation
  1311. ? "pending"
  1312. : "not_required",
  1313. "confirmation_token" => $confirmationToken,
  1314. "confirmation_expires_at" => $confirmationExpiresAt,
  1315. "confirmed_at" => $requiresConfirmation ? "" : $now,
  1316. "created_at" => $now,
  1317. "updated_at" => $now,
  1318. "cancelled_at" => "",
  1319. "cancelled_by" => "",
  1320. "cancellation_reason" => "",
  1321. "admin_notified_at" => "",
  1322. ];
  1323. $orders = getOrders();
  1324. $orders[] = $order;
  1325. saveOrders($orders);
  1326. logAccess("Order created in createOrder", [
  1327. "order_id" => $order["id"],
  1328. "customer" => $customerEmail,
  1329. "organization" => $organization["label"],
  1330. ]);
  1331. if ($requiresConfirmation) {
  1332. sendOrderConfirmationRequestEmail($order);
  1333. } else {
  1334. $result = sendConfirmedOrderAdminNotification($order);
  1335. if ($result) {
  1336. markOrderAdminNotified($order["id"]);
  1337. $order = getOrderById($order["id"]);
  1338. }
  1339. sendOrderCreatedCustomerEmail($order);
  1340. }
  1341. return ["success" => true, "order" => $order];
  1342. }
  1343. function markOrderAdminNotified($orderId)
  1344. {
  1345. $orders = getOrders();
  1346. foreach ($orders as &$order) {
  1347. if ($order["id"] !== $orderId) {
  1348. continue;
  1349. }
  1350. $order["admin_notified_at"] = date("Y-m-d H:i:s");
  1351. $order["updated_at"] = date("Y-m-d H:i:s");
  1352. break;
  1353. }
  1354. unset($order);
  1355. saveOrders($orders);
  1356. }
  1357. function confirmOrderByToken($token)
  1358. {
  1359. $orders = getOrders();
  1360. $now = date("Y-m-d H:i:s");
  1361. foreach ($orders as &$order) {
  1362. if (($order["confirmation_token"] ?? "") !== $token) {
  1363. continue;
  1364. }
  1365. $order = refreshOrderState($order);
  1366. if ($order["status"] === "cancelled") {
  1367. return [
  1368. "success" => false,
  1369. "message" =>
  1370. "Diese Bestellung wurde storniert und kann nicht mehr bestätigt werden.",
  1371. ];
  1372. }
  1373. if ($order["confirmation_status"] === "confirmed") {
  1374. return [
  1375. "success" => false,
  1376. "message" => "Diese Bestellung wurde bereits bestätigt.",
  1377. ];
  1378. }
  1379. if ($order["confirmation_status"] === "expired") {
  1380. return [
  1381. "success" => false,
  1382. "message" => "Der Bestätigungslink ist abgelaufen.",
  1383. ];
  1384. }
  1385. if ($order["confirmation_status"] !== "pending") {
  1386. return [
  1387. "success" => false,
  1388. "message" =>
  1389. "Für diese Bestellung ist keine Bestätigung erforderlich.",
  1390. ];
  1391. }
  1392. $expiresAt = strtotime((string) $order["confirmation_expires_at"]);
  1393. if ($expiresAt !== false && time() > $expiresAt) {
  1394. $order["confirmation_status"] = "expired";
  1395. $order["updated_at"] = $now;
  1396. saveOrders($orders);
  1397. return [
  1398. "success" => false,
  1399. "message" => "Der Bestätigungslink ist abgelaufen.",
  1400. ];
  1401. }
  1402. $order["confirmation_status"] = "confirmed";
  1403. $order["confirmed_at"] = $now;
  1404. $order["updated_at"] = $now;
  1405. saveOrders($orders);
  1406. $sent = sendConfirmedOrderAdminNotification($order);
  1407. if ($sent) {
  1408. markOrderAdminNotified($order["id"]);
  1409. }
  1410. sendOrderConfirmedCustomerEmail(getOrderById($order["id"]));
  1411. return ["success" => true, "order" => getOrderById($order["id"])];
  1412. }
  1413. unset($order);
  1414. return ["success" => false, "message" => "Bestellung nicht gefunden."];
  1415. }
  1416. function toggleOrderItemProcessed($orderId, $itemIndex)
  1417. {
  1418. $orders = getOrders();
  1419. $now = date("Y-m-d H:i:s");
  1420. foreach ($orders as &$order) {
  1421. if ($order["id"] !== $orderId) {
  1422. continue;
  1423. }
  1424. if ($order["status"] === "cancelled") {
  1425. return [
  1426. "success" => false,
  1427. "message" =>
  1428. "Stornierte Bestellungen können nicht mehr bearbeitet werden.",
  1429. ];
  1430. }
  1431. if (($order["confirmation_status"] ?? "") === "pending") {
  1432. return [
  1433. "success" => false,
  1434. "message" =>
  1435. "Unbestätigte Bestellungen können noch nicht bearbeitet werden.",
  1436. ];
  1437. }
  1438. if (($order["confirmation_status"] ?? "") === "expired") {
  1439. return [
  1440. "success" => false,
  1441. "message" =>
  1442. "Abgelaufene unbestätigte Bestellungen können nicht bearbeitet werden.",
  1443. ];
  1444. }
  1445. if (!isset($order["items"][$itemIndex])) {
  1446. return [
  1447. "success" => false,
  1448. "message" => "Position nicht gefunden.",
  1449. ];
  1450. }
  1451. $order["items"][$itemIndex]["is_processed"] = empty(
  1452. $order["items"][$itemIndex]["is_processed"]
  1453. );
  1454. $order["updated_at"] = $now;
  1455. $order = refreshOrderState($order);
  1456. saveOrders($orders);
  1457. return ["success" => true, "order" => $order];
  1458. }
  1459. unset($order);
  1460. return ["success" => false, "message" => "Bestellung nicht gefunden."];
  1461. }
  1462. function cancelOrder($orderId, $adminUsername, $reason = "")
  1463. {
  1464. $orders = getOrders();
  1465. $now = date("Y-m-d H:i:s");
  1466. $adminUsername = normalizeAdminUsername($adminUsername);
  1467. $reason = trim((string) $reason);
  1468. foreach ($orders as &$order) {
  1469. if ($order["id"] !== $orderId) {
  1470. continue;
  1471. }
  1472. if ($order["status"] === "cancelled") {
  1473. return [
  1474. "success" => false,
  1475. "message" => "Die Bestellung ist bereits storniert.",
  1476. ];
  1477. }
  1478. $order["status"] = "cancelled";
  1479. $order["cancelled_at"] = $now;
  1480. $order["cancelled_by"] = $adminUsername;
  1481. $order["cancellation_reason"] = $reason;
  1482. $order["updated_at"] = $now;
  1483. saveOrders($orders);
  1484. return ["success" => true, "order" => $order];
  1485. }
  1486. unset($order);
  1487. return ["success" => false, "message" => "Bestellung nicht gefunden."];
  1488. }
  1489. function getOrderStatusLabel($order)
  1490. {
  1491. if (($order["status"] ?? "") === "cancelled") {
  1492. return "Storniert";
  1493. }
  1494. if (($order["confirmation_status"] ?? "") === "pending") {
  1495. return "Unbestätigt";
  1496. }
  1497. if (($order["confirmation_status"] ?? "") === "expired") {
  1498. return "Bestätigung abgelaufen";
  1499. }
  1500. if (($order["status"] ?? "") === "processed") {
  1501. return "Bearbeitet";
  1502. }
  1503. if (($order["status"] ?? "") === "partial") {
  1504. return "Teilweise bearbeitet";
  1505. }
  1506. return "Offen";
  1507. }
  1508. function getOrderStatusClass($order)
  1509. {
  1510. if (($order["status"] ?? "") === "cancelled") {
  1511. return "status-cancelled";
  1512. }
  1513. if (($order["confirmation_status"] ?? "") === "pending") {
  1514. return "status-unconfirmed";
  1515. }
  1516. if (($order["confirmation_status"] ?? "") === "expired") {
  1517. return "status-expired";
  1518. }
  1519. if (($order["status"] ?? "") === "processed") {
  1520. return "status-processed";
  1521. }
  1522. if (($order["status"] ?? "") === "partial") {
  1523. return "status-partial";
  1524. }
  1525. return "status-open";
  1526. }
  1527. function formatDate($dateString)
  1528. {
  1529. $dateString = trim((string) $dateString);
  1530. if ($dateString === "") {
  1531. return "-";
  1532. }
  1533. try {
  1534. $date = new DateTimeImmutable($dateString);
  1535. return $date->format("d.m.Y H:i");
  1536. } catch (Exception $exception) {
  1537. return $dateString;
  1538. }
  1539. }
  1540. function getCart()
  1541. {
  1542. $cart = $_SESSION["cart"] ?? [];
  1543. if (!is_array($cart)) {
  1544. $cart = [];
  1545. }
  1546. $normalized = [];
  1547. foreach ($cart as $item) {
  1548. $productId = isset($item["product_id"]) ? (int) $item["product_id"] : 0;
  1549. $size = trim((string) ($item["size"] ?? ""));
  1550. $product = getProductById($productId);
  1551. if ($product === null) {
  1552. continue;
  1553. }
  1554. $sizes = getProductSizes($product);
  1555. if (!empty($sizes)) {
  1556. if ($size === "" || !in_array($size, $sizes, true)) {
  1557. continue;
  1558. }
  1559. } else {
  1560. $size = "";
  1561. }
  1562. if (isset($normalized[$productId])) {
  1563. unset($normalized[$productId]);
  1564. }
  1565. $normalized[$productId] = [
  1566. "product_id" => $productId,
  1567. "size" => $size,
  1568. ];
  1569. }
  1570. $_SESSION["cart"] = array_values($normalized);
  1571. return $_SESSION["cart"];
  1572. }
  1573. function addCartItem($productId, $size = "")
  1574. {
  1575. $productId = (int) $productId;
  1576. $size = trim((string) $size);
  1577. $product = getProductById($productId);
  1578. if ($product === null) {
  1579. return [
  1580. "success" => false,
  1581. "status" => "error",
  1582. ];
  1583. }
  1584. $sizes = getProductSizes($product);
  1585. if (!empty($sizes)) {
  1586. if ($size === "" || !in_array($size, $sizes, true)) {
  1587. return [
  1588. "success" => false,
  1589. "status" => "error",
  1590. ];
  1591. }
  1592. } else {
  1593. $size = "";
  1594. }
  1595. $cart = getCart();
  1596. foreach ($cart as $index => $item) {
  1597. if ((int) $item["product_id"] !== $productId) {
  1598. continue;
  1599. }
  1600. $existingSize = trim((string) ($item["size"] ?? ""));
  1601. if ($existingSize === $size) {
  1602. return [
  1603. "success" => true,
  1604. "status" => "unchanged",
  1605. "size" => $size,
  1606. ];
  1607. }
  1608. $cart[$index]["size"] = $size;
  1609. $_SESSION["cart"] = array_values($cart);
  1610. return [
  1611. "success" => true,
  1612. "status" => "replaced",
  1613. "size" => $size,
  1614. "previous_size" => $existingSize,
  1615. ];
  1616. }
  1617. $cart[] = [
  1618. "product_id" => $productId,
  1619. "size" => $size,
  1620. ];
  1621. $_SESSION["cart"] = array_values($cart);
  1622. return [
  1623. "success" => true,
  1624. "status" => "added",
  1625. "size" => $size,
  1626. ];
  1627. }
  1628. function removeCartItemByIndex($index)
  1629. {
  1630. $cart = getCart();
  1631. if (isset($cart[$index])) {
  1632. unset($cart[$index]);
  1633. $_SESSION["cart"] = array_values($cart);
  1634. }
  1635. }
  1636. function clearCart()
  1637. {
  1638. $_SESSION["cart"] = [];
  1639. }
  1640. function getCartItemsDetailed()
  1641. {
  1642. $items = [];
  1643. foreach (getCart() as $index => $cartItem) {
  1644. $product = getProductById($cartItem["product_id"]);
  1645. if ($product === null) {
  1646. continue;
  1647. }
  1648. $size = trim((string) ($cartItem["size"] ?? ""));
  1649. $items[] = [
  1650. "cart_index" => $index,
  1651. "product" => $product,
  1652. "size" => $size,
  1653. "availability_label" =>
  1654. $size !== "" ? getAvailabilityLabel($product, $size) : "",
  1655. ];
  1656. }
  1657. return $items;
  1658. }
  1659. function buildOrderItemsFromCart()
  1660. {
  1661. $items = [];
  1662. foreach (getCart() as $cartItem) {
  1663. $product = getProductById($cartItem["product_id"]);
  1664. if ($product === null) {
  1665. continue;
  1666. }
  1667. $size = trim((string) ($cartItem["size"] ?? ""));
  1668. $items[] = [
  1669. "product_id" => $product["id"],
  1670. "size" => $size,
  1671. "is_processed" => false,
  1672. ];
  1673. }
  1674. return normalizeOrderItems($items);
  1675. }
  1676. function buildOrderItemsHtml($order)
  1677. {
  1678. $parts = [];
  1679. foreach ($order["items"] as $item) {
  1680. $label = "<strong>" . escape($item["product_name"]) . "</strong>";
  1681. if ($item["size"] !== "") {
  1682. $label .= " - Größe: " . escape($item["size"]);
  1683. }
  1684. if (!empty($item["availability_label"])) {
  1685. $label .=
  1686. "<br><small>" .
  1687. nl2br(escape($item["availability_label"])) .
  1688. "</small>";
  1689. }
  1690. $parts[] =
  1691. '<li style="margin: 0 0 0.75rem 0; padding: 0.9rem 1rem; background: #f8f4e7; border: 1px solid #d7ceb5; border-radius: 18px; color: #111111;">' .
  1692. $label .
  1693. "</li>";
  1694. }
  1695. return '<ul style="list-style: none; margin: 0; padding: 0;">' .
  1696. implode("", $parts) .
  1697. "</ul>";
  1698. }
  1699. function buildOrderSummaryHtml($order, $title, $introHtml, $extraHtml = "")
  1700. {
  1701. $itemsHtml = buildOrderItemsHtml($order);
  1702. return '
  1703. <html>
  1704. <head>
  1705. <meta charset="UTF-8">
  1706. </head>
  1707. <body style="font-family: \'Freising Sans\', Arial, sans-serif; line-height: 1.6; color: #111111; background: #f4efe1; padding: 1.5rem;">
  1708. <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);">
  1709. <p style="margin: 0 0 0.5rem; font-size: 0.8rem; letter-spacing: 0.08em; text-transform: uppercase; color: #5e5a4d;">' .
  1710. escape(SITE_DEPARTMENT_NAME) .
  1711. '</p>
  1712. <h1 style="margin: 0; font-size: 1.75rem; line-height: 1.2; color: #111111;">' .
  1713. escape(SITE_NAME) .
  1714. '</h1>
  1715. <p style="margin: 0.25rem 0 1.5rem; font-size: 1rem; color: #5e5a4d;">' .
  1716. escape(SITE_SERVICE_HEADER) .
  1717. '</p>
  1718. <div style="width: 80px; height: 6px; border-radius: 999px; background: #ffd71c; margin-bottom: 1.5rem;"></div>
  1719. <h2 style="color: #111111; margin-top: 0;">' .
  1720. escape($title) .
  1721. '</h2>
  1722. ' .
  1723. $introHtml .
  1724. '
  1725. <div style="background: #f8f4e7; border: 2px solid #ffd71c; padding: 1.5rem; margin: 1.5rem 0; border-radius: 20px;">
  1726. <h3 style="margin-top: 0;">Bestellnummer</h3>
  1727. <p style="margin: 0; color: #111111; font-family: monospace; font-size: 1.05rem;">' .
  1728. escape($order["id"]) .
  1729. '</p>
  1730. </div>
  1731. <p><strong>Name:</strong> ' .
  1732. escape($order["customer_name"]) .
  1733. '</p>
  1734. <p><strong>E-Mail:</strong> ' .
  1735. escape($order["customer_email"]) .
  1736. '</p>
  1737. <p><strong>Organisation:</strong> ' .
  1738. escape($order["organization_label"]) .
  1739. '</p>
  1740. <p><strong>Erstellt am:</strong> ' .
  1741. escape(formatDate($order["created_at"])) .
  1742. '</p>
  1743. <h3>Bestellte Artikel</h3>
  1744. <div style="background: #fffdf6; border: 1px solid #d7ceb5; border-left: 6px solid #ffd71c; border-radius: 20px; padding: 1rem;">' .
  1745. $itemsHtml .
  1746. '</div>
  1747. <p><strong>Kommentar:</strong><br>' .
  1748. ($order["comment"] !== ""
  1749. ? nl2br(escape($order["comment"]))
  1750. : "Kein Kommentar") .
  1751. '</p>
  1752. ' .
  1753. $extraHtml .
  1754. '
  1755. <p style="margin: 2rem 0 0; color: #5e5a4d; font-size: 0.9rem;">' .
  1756. escape(SITE_NAME) .
  1757. " | " .
  1758. escape(SITE_DEPARTMENT_NAME) .
  1759. "<br>" .
  1760. escape(SITE_ADDRESS_LINE) .
  1761. '</p>
  1762. </div>
  1763. </body>
  1764. </html>';
  1765. }
  1766. function sendOrderConfirmationRequestEmail($order)
  1767. {
  1768. $subject = SITE_SERVICE_NAME . ": Bestellung bestätigen - " . $order["id"];
  1769. $link = buildOrderConfirmationUrl($order["confirmation_token"]);
  1770. $expiryText = formatDate($order["confirmation_expires_at"]);
  1771. $intro =
  1772. "<p>Guten Tag " .
  1773. escape($order["customer_name"]) .
  1774. ",</p><p>bitte bestätigen Sie Ihre Bestellung im " .
  1775. escape(SITE_SERVICE_NAME) .
  1776. " der Stadt Freising über den folgenden Link.</p>";
  1777. $extra =
  1778. '
  1779. <p><a href="' .
  1780. escape($link) .
  1781. '" style="display: inline-block; padding: 0.75rem 1.5rem; background: #ffd71c; color: #111111; text-decoration: none; border: 2px solid #ffd71c; border-radius: 14px; font-weight: 700;">Bestellung bestätigen</a></p>
  1782. <p>Der Link ist gültig bis: <strong>' .
  1783. escape($expiryText) .
  1784. '</strong></p>
  1785. <p>Falls der Button nicht funktioniert, verwenden Sie bitte diesen Link:<br>' .
  1786. escape($link) .
  1787. "</p>";
  1788. $message = buildOrderSummaryHtml(
  1789. $order,
  1790. "Bestellung bestätigen",
  1791. $intro,
  1792. $extra,
  1793. );
  1794. return sendEmail($order["customer_email"], $subject, $message);
  1795. }
  1796. function sendOrderCreatedCustomerEmail($order)
  1797. {
  1798. $subject = SITE_SERVICE_NAME . ": Ihre Bestellung - " . $order["id"];
  1799. $intro =
  1800. "<p>Guten Tag " .
  1801. escape($order["customer_name"]) .
  1802. ",</p><p>Ihre Bestellung wurde erfasst und an " .
  1803. escape(SITE_DEPARTMENT_NAME) .
  1804. " weitergeleitet.</p>";
  1805. $message = buildOrderSummaryHtml($order, "Bestellung eingegangen", $intro);
  1806. return sendEmail($order["customer_email"], $subject, $message);
  1807. }
  1808. function sendOrderConfirmedCustomerEmail($order)
  1809. {
  1810. $subject = SITE_SERVICE_NAME . ": Bestellung bestätigt - " . $order["id"];
  1811. $intro =
  1812. "<p>Guten Tag " .
  1813. escape($order["customer_name"]) .
  1814. ",</p><p>Ihre Bestellung wurde bestätigt und an " .
  1815. escape(SITE_DEPARTMENT_NAME) .
  1816. " weitergeleitet.</p>";
  1817. $message = buildOrderSummaryHtml($order, "Bestellung bestätigt", $intro);
  1818. return sendEmail($order["customer_email"], $subject, $message);
  1819. }
  1820. function sendConfirmedOrderAdminNotification($order)
  1821. {
  1822. $recipient = getOrderRecipientEmail();
  1823. if (!isValidAdminEmail($recipient)) {
  1824. return false;
  1825. }
  1826. $subject = SITE_SERVICE_NAME . ": Neue Bestellung - " . $order["id"];
  1827. $intro =
  1828. "<p>Eine neue PSA-Bestellung wurde freigegeben und muss bearbeitet werden.</p>";
  1829. $message = buildOrderSummaryHtml($order, "Neue PSA-Bestellung", $intro);
  1830. $attachments = [];
  1831. if (shouldAttachOrderPdfToAdminEmail()) {
  1832. $attachments[] = [
  1833. "filename" => "bestellung-" . strtolower($order["id"]) . ".pdf",
  1834. "content_type" => "application/pdf",
  1835. "content" => generateOrderPdf($order),
  1836. ];
  1837. }
  1838. return sendEmail($recipient, $subject, $message, true, $attachments);
  1839. }
  1840. function sendEmail($to, $subject, $message, $isHtml = true, $attachments = [])
  1841. {
  1842. $headers = [];
  1843. $headers[] = "From: " . FROM_NAME . " <" . FROM_EMAIL . ">";
  1844. $headers[] = "Reply-To: " . FROM_EMAIL;
  1845. $headers[] = "X-Mailer: PHP/" . phpversion();
  1846. if (empty($attachments)) {
  1847. if ($isHtml) {
  1848. $headers[] = "MIME-Version: 1.0";
  1849. $headers[] = "Content-Type: text/html; charset=UTF-8";
  1850. } else {
  1851. $headers[] = "Content-Type: text/plain; charset=UTF-8";
  1852. }
  1853. return mail($to, $subject, $message, implode("\r\n", $headers));
  1854. }
  1855. $boundary = "=_Boundary_" . bin2hex(random_bytes(8));
  1856. $headers[] = "MIME-Version: 1.0";
  1857. $headers[] = 'Content-Type: multipart/mixed; boundary="' . $boundary . '"';
  1858. $body = [];
  1859. $body[] = "--" . $boundary;
  1860. $body[] =
  1861. "Content-Type: " .
  1862. ($isHtml ? "text/html" : "text/plain") .
  1863. "; charset=UTF-8";
  1864. $body[] = "Content-Transfer-Encoding: 8bit";
  1865. $body[] = "";
  1866. $body[] = $message;
  1867. foreach ($attachments as $attachment) {
  1868. if (!is_array($attachment)) {
  1869. continue;
  1870. }
  1871. $filename = trim(
  1872. (string) ($attachment["filename"] ?? "attachment.bin"),
  1873. );
  1874. $contentType = trim(
  1875. (string) ($attachment["content_type"] ??
  1876. "application/octet-stream"),
  1877. );
  1878. $content = isset($attachment["content"])
  1879. ? (string) $attachment["content"]
  1880. : "";
  1881. $body[] = "--" . $boundary;
  1882. $body[] =
  1883. "Content-Type: " . $contentType . '; name="' . $filename . '"';
  1884. $body[] = "Content-Transfer-Encoding: base64";
  1885. $body[] =
  1886. 'Content-Disposition: attachment; filename="' . $filename . '"';
  1887. $body[] = "";
  1888. $body[] = chunk_split(base64_encode($content));
  1889. }
  1890. $body[] = "--" . $boundary . "--";
  1891. $body[] = "";
  1892. return mail(
  1893. $to,
  1894. $subject,
  1895. implode("\r\n", $body),
  1896. implode("\r\n", $headers),
  1897. );
  1898. }
  1899. function pdfEncodeWinAnsi($text)
  1900. {
  1901. $text = str_replace("\r", "", (string) $text);
  1902. if (!function_exists("iconv")) {
  1903. return preg_replace('/[^\x09\x0A\x20-\x7E]/', "?", $text);
  1904. }
  1905. $chars = preg_split("//u", $text, -1, PREG_SPLIT_NO_EMPTY);
  1906. if (!is_array($chars)) {
  1907. $fallback = @iconv("UTF-8", "Windows-1252//TRANSLIT//IGNORE", $text);
  1908. return is_string($fallback) ? $fallback : $text;
  1909. }
  1910. $result = "";
  1911. foreach ($chars as $char) {
  1912. $converted = @iconv("UTF-8", "Windows-1252", $char);
  1913. if ($converted !== false) {
  1914. $result .= $converted;
  1915. continue;
  1916. }
  1917. $fallback = @iconv("UTF-8", "Windows-1252//TRANSLIT", $char);
  1918. if ($fallback !== false && $fallback !== "") {
  1919. $result .= $fallback;
  1920. continue;
  1921. }
  1922. $result .= "?";
  1923. }
  1924. return $result;
  1925. }
  1926. function pdfEscapeText($text)
  1927. {
  1928. $text = str_replace("\\", "\\\\", $text);
  1929. $text = str_replace("(", "\(", $text);
  1930. $text = str_replace(")", "\)", $text);
  1931. return preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', "", $text);
  1932. }
  1933. function pdfWrapAnsiText($text, $maxChars)
  1934. {
  1935. $lines = [];
  1936. $paragraphs = explode("\n", str_replace("\r", "", (string) $text));
  1937. foreach ($paragraphs as $paragraph) {
  1938. $normalized = trim(preg_replace("/\s+/", " ", $paragraph));
  1939. if ($normalized === "") {
  1940. $lines[] = "";
  1941. continue;
  1942. }
  1943. $words = explode(" ", $normalized);
  1944. $current = "";
  1945. foreach ($words as $word) {
  1946. if ($word === "") {
  1947. continue;
  1948. }
  1949. if (strlen($word) > $maxChars) {
  1950. if ($current !== "") {
  1951. $lines[] = $current;
  1952. $current = "";
  1953. }
  1954. $parts = str_split($word, $maxChars);
  1955. $lastIndex = count($parts) - 1;
  1956. for ($i = 0; $i < $lastIndex; $i++) {
  1957. $lines[] = $parts[$i];
  1958. }
  1959. $current = $parts[$lastIndex];
  1960. continue;
  1961. }
  1962. $candidate = $current === "" ? $word : $current . " " . $word;
  1963. if (strlen($candidate) <= $maxChars) {
  1964. $current = $candidate;
  1965. } else {
  1966. if ($current !== "") {
  1967. $lines[] = $current;
  1968. }
  1969. $current = $word;
  1970. }
  1971. }
  1972. if ($current !== "") {
  1973. $lines[] = $current;
  1974. }
  1975. }
  1976. if (empty($lines)) {
  1977. $lines[] = "";
  1978. }
  1979. return $lines;
  1980. }
  1981. function generateOrderPdf($order)
  1982. {
  1983. $pageWidth = 595;
  1984. $pageHeight = 842;
  1985. $leftMargin = 45;
  1986. $topY = 800;
  1987. $bottomY = 60;
  1988. $lineHeight = 14;
  1989. $pages = [];
  1990. $pageContent = "";
  1991. $y = $topY;
  1992. $pageNumber = 0;
  1993. $encodeText = function ($text) {
  1994. return pdfEncodeWinAnsi((string) $text);
  1995. };
  1996. $siteName = $encodeText(SITE_FULL_NAME);
  1997. $orderId = $encodeText($order["id"]);
  1998. $createdAt = $encodeText(formatDate($order["created_at"]));
  1999. $customerName = $encodeText($order["customer_name"]);
  2000. $customerEmail = $encodeText($order["customer_email"]);
  2001. $organization = $encodeText($order["organization_label"]);
  2002. $commentRaw = (string) $order["comment"];
  2003. $writeText = function ($x, $y, $encodedText, $fontSize = 12) use (&$pageContent) {
  2004. $pageContent .=
  2005. "BT\n/F1 " .
  2006. $fontSize .
  2007. " Tf\n1 0 0 1 " .
  2008. number_format($x, 2, ".", "") .
  2009. " " .
  2010. number_format($y, 2, ".", "") .
  2011. " Tm\n(" .
  2012. pdfEscapeText($encodedText) .
  2013. ") Tj\nET\n";
  2014. };
  2015. $startPage = function () use (
  2016. &$pages,
  2017. &$pageContent,
  2018. &$y,
  2019. &$pageNumber,
  2020. $topY,
  2021. $leftMargin,
  2022. $lineHeight,
  2023. $siteName,
  2024. $orderId,
  2025. $createdAt,
  2026. $writeText,
  2027. $encodeText
  2028. ) {
  2029. if ($pageContent !== "") {
  2030. $pages[] = $pageContent;
  2031. }
  2032. $pageNumber++;
  2033. $pageContent = "";
  2034. $y = $topY;
  2035. foreach (pdfWrapAnsiText($siteName, 70) as $index => $line) {
  2036. $writeText($leftMargin, $y, $line, $index === 0 ? 15 : 11);
  2037. $y -= $index === 0 ? 19 : $lineHeight;
  2038. }
  2039. $headerLine = "Bestellung: " . $orderId;
  2040. if ($pageNumber > 1) {
  2041. $headerLine .= " | Seite " . $encodeText($pageNumber);
  2042. }
  2043. $writeText($leftMargin, $y, $headerLine, 12);
  2044. $y -= 17;
  2045. $writeText($leftMargin, $y, "Erstellt am: " . $createdAt, 11);
  2046. $y -= 20;
  2047. };
  2048. $ensureSpace = function ($requiredHeight) use (&$y, $bottomY, $startPage) {
  2049. if ($y - $requiredHeight < $bottomY) {
  2050. $startPage();
  2051. }
  2052. };
  2053. $writeWrapped = function (
  2054. $encodedText,
  2055. $maxChars,
  2056. $fontSize = 11,
  2057. $x = null
  2058. ) use (&$y, $lineHeight, $leftMargin, $writeText, $ensureSpace) {
  2059. $targetX = $x === null ? $leftMargin : $x;
  2060. $lines = pdfWrapAnsiText($encodedText, $maxChars);
  2061. foreach ($lines as $line) {
  2062. $ensureSpace($lineHeight);
  2063. $writeText($targetX, $y, $line, $fontSize);
  2064. $y -= $lineHeight;
  2065. }
  2066. };
  2067. $writeSectionTitle = function ($titleText) use (
  2068. &$y,
  2069. $leftMargin,
  2070. $writeText,
  2071. $ensureSpace,
  2072. $encodeText
  2073. ) {
  2074. $ensureSpace(24);
  2075. $writeText($leftMargin, $y, $encodeText($titleText), 13);
  2076. $y -= 18;
  2077. };
  2078. $startPage();
  2079. $writeSectionTitle("Gehört zu");
  2080. $writeWrapped("Name: " . $customerName, 80);
  2081. $writeWrapped("Organisation: " . $organization, 80);
  2082. $writeWrapped("E-Mail: " . $customerEmail, 80);
  2083. $y -= 6;
  2084. $writeSectionTitle("Artikelliste");
  2085. $itemNumber = 1;
  2086. if (empty($order["items"])) {
  2087. $writeWrapped($encodeText("Keine Artikel"), 80);
  2088. } else {
  2089. foreach ($order["items"] as $item) {
  2090. $itemName = $encodeText($item["product_name"]);
  2091. $sizeLabel = $encodeText($item["size"]);
  2092. $hintLabel = $encodeText(
  2093. preg_replace("/\s+/", " ", (string) $item["availability_label"]),
  2094. );
  2095. $writeWrapped($encodeText($itemNumber . ". ") . $itemName, 78);
  2096. if ($sizeLabel !== "") {
  2097. $writeWrapped($encodeText(" Größe: ") . $sizeLabel, 76);
  2098. }
  2099. if ($hintLabel !== "") {
  2100. $writeWrapped($encodeText(" Hinweis: ") . $hintLabel, 76);
  2101. }
  2102. $y -= 4;
  2103. $itemNumber++;
  2104. }
  2105. }
  2106. $y -= 4;
  2107. $writeSectionTitle("Kommentar");
  2108. if (trim($commentRaw) === "") {
  2109. $writeWrapped($encodeText("Kein Kommentar"), 80);
  2110. } else {
  2111. foreach (preg_split('/\r\n|\r|\n/', $commentRaw) as $commentLine) {
  2112. $writeWrapped($encodeText($commentLine), 82);
  2113. }
  2114. }
  2115. $y -= 6;
  2116. $writeSectionTitle("Lagerbearbeitung");
  2117. $warehouseLines = [
  2118. "Ausgegeben am: ________________________",
  2119. "Ausgegeben durch: _____________________",
  2120. "Unterschrift: _________________________",
  2121. "",
  2122. "[ ] Vollständig ausgegeben",
  2123. "[ ] Teilweise ausgegeben",
  2124. ];
  2125. foreach ($warehouseLines as $line) {
  2126. if ($line === "") {
  2127. $ensureSpace($lineHeight);
  2128. $y -= $lineHeight;
  2129. continue;
  2130. }
  2131. $writeWrapped($encodeText($line), 80);
  2132. }
  2133. if ($pageContent !== "") {
  2134. $pages[] = $pageContent;
  2135. }
  2136. if (empty($pages)) {
  2137. $pages[] = "";
  2138. }
  2139. $fontObjectNumber = 3;
  2140. $objects = [];
  2141. $objects[1] = "1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n";
  2142. $objects[
  2143. $fontObjectNumber
  2144. ] = "3 0 obj\n<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>\nendobj\n";
  2145. $kids = [];
  2146. $nextObjectNumber = 4;
  2147. foreach ($pages as $pageStream) {
  2148. $pageObjectNumber = $nextObjectNumber++;
  2149. $contentObjectNumber = $nextObjectNumber++;
  2150. $kids[] = $pageObjectNumber . " 0 R";
  2151. $objects[$pageObjectNumber] =
  2152. $pageObjectNumber .
  2153. " 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 " .
  2154. $pageWidth .
  2155. " " .
  2156. $pageHeight .
  2157. "] /Contents " .
  2158. $contentObjectNumber .
  2159. " 0 R /Resources << /Font << /F1 " .
  2160. $fontObjectNumber .
  2161. " 0 R >> >> >>\nendobj\n";
  2162. $objects[$contentObjectNumber] =
  2163. $contentObjectNumber .
  2164. " 0 obj\n<< /Length " .
  2165. strlen($pageStream) .
  2166. " >>\nstream\n" .
  2167. $pageStream .
  2168. "\nendstream\nendobj\n";
  2169. }
  2170. $objects[2] =
  2171. "2 0 obj\n<< /Type /Pages /Kids [" .
  2172. implode(" ", $kids) .
  2173. "] /Count " .
  2174. count($kids) .
  2175. " >>\nendobj\n";
  2176. ksort($objects);
  2177. $pdf = "%PDF-1.4\n";
  2178. $offsets = [0];
  2179. foreach ($objects as $number => $objectContent) {
  2180. $offsets[$number] = strlen($pdf);
  2181. $pdf .= $objectContent;
  2182. }
  2183. $lastObjectNumber = (int) max(array_keys($objects));
  2184. $xrefOffset = strlen($pdf);
  2185. $pdf .= "xref\n0 " . ($lastObjectNumber + 1) . "\n";
  2186. $pdf .= "0000000000 65535 f \n";
  2187. for ($i = 1; $i <= $lastObjectNumber; $i++) {
  2188. if (isset($offsets[$i])) {
  2189. $pdf .= sprintf("%010d 00000 n \n", $offsets[$i]);
  2190. } else {
  2191. $pdf .= "0000000000 00000 f \n";
  2192. }
  2193. }
  2194. $pdf .= "trailer\n<< /Size " . ($lastObjectNumber + 1) . " /Root 1 0 R >>\n";
  2195. $pdf .= "startxref\n" . $xrefOffset . "\n%%EOF";
  2196. return $pdf;
  2197. }
  2198. /**
  2199. * Input Validation Class
  2200. */
  2201. class Validator
  2202. {
  2203. private $errors = [];
  2204. private $data = [];
  2205. public function __construct($data)
  2206. {
  2207. $this->data = $data;
  2208. }
  2209. public function required($field, $label = null)
  2210. {
  2211. $value = $this->get($field);
  2212. if (empty(trim($value ?? ""))) {
  2213. $this->errors[] = ($label ?? $field) . " ist erforderlich.";
  2214. }
  2215. return $this;
  2216. }
  2217. public function email($field, $label = null)
  2218. {
  2219. $value = $this->get($field);
  2220. if (!empty($value) && !filter_var($value, FILTER_VALIDATE_EMAIL)) {
  2221. $this->errors[] =
  2222. ($label ?? $field) . " muss eine gültige E-Mail-Adresse sein.";
  2223. }
  2224. return $this;
  2225. }
  2226. public function minLength($field, $min, $label = null)
  2227. {
  2228. $value = $this->get($field);
  2229. if (!empty($value) && strlen($value) < $min) {
  2230. $this->errors[] =
  2231. ($label ?? $field) .
  2232. " muss mindestens " .
  2233. $min .
  2234. " Zeichen lang sein.";
  2235. }
  2236. return $this;
  2237. }
  2238. public function maxLength($field, $max, $label = null)
  2239. {
  2240. $value = $this->get($field);
  2241. if (!empty($value) && strlen($value) > $max) {
  2242. $this->errors[] =
  2243. ($label ?? $field) .
  2244. " darf maximal " .
  2245. $max .
  2246. " Zeichen lang sein.";
  2247. }
  2248. return $this;
  2249. }
  2250. public function inArray($field, $allowed, $label = null)
  2251. {
  2252. $value = $this->get($field);
  2253. if (!empty($value) && !in_array($value, $allowed, true)) {
  2254. $this->errors[] = ($label ?? $field) . " ist ungültig.";
  2255. }
  2256. return $this;
  2257. }
  2258. public function get($field)
  2259. {
  2260. return $this->data[$field] ?? null;
  2261. }
  2262. public function getErrors()
  2263. {
  2264. return $this->errors;
  2265. }
  2266. public function isValid()
  2267. {
  2268. return empty($this->errors);
  2269. }
  2270. }
  2271. /**
  2272. * Error Logging Functions
  2273. */
  2274. if (!defined("LOG_DIR")) {
  2275. define("LOG_DIR", DATA_DIR . "logs/");
  2276. }
  2277. if (!defined("ERROR_LOG_FILE")) {
  2278. define("ERROR_LOG_FILE", LOG_DIR . "error.log");
  2279. }
  2280. if (!defined("ACCESS_LOG_FILE")) {
  2281. define("ACCESS_LOG_FILE", LOG_DIR . "access.log");
  2282. }
  2283. function initLogging()
  2284. {
  2285. if (!is_dir(LOG_DIR)) {
  2286. mkdir(LOG_DIR, 02775, true);
  2287. @chmod(LOG_DIR, 02775);
  2288. }
  2289. }
  2290. function logError($message, $context = [], $level = "ERROR")
  2291. {
  2292. initLogging();
  2293. $entry = [
  2294. "timestamp" => date("Y-m-d H:i:s.u"),
  2295. "level" => $level,
  2296. "message" => $message,
  2297. "context" => $context,
  2298. "ip" => $_SERVER["REMOTE_ADDR"] ?? "unknown",
  2299. "user_agent" => $_SERVER["HTTP_USER_AGENT"] ?? "unknown",
  2300. "request_uri" => $_SERVER["REQUEST_URI"] ?? "unknown",
  2301. "session_id" => session_id()
  2302. ? substr(session_id(), 0, 8) . "..."
  2303. : "none",
  2304. ];
  2305. $logLine = json_encode($entry, JSON_UNESCAPED_UNICODE) . PHP_EOL;
  2306. file_put_contents(ERROR_LOG_FILE, $logLine, FILE_APPEND | LOCK_EX);
  2307. if (defined("DEVELOPMENT_MODE") && DEVELOPMENT_MODE) {
  2308. error_log(
  2309. "PSA Order: " . $message . " | Context: " . json_encode($context),
  2310. );
  2311. }
  2312. }
  2313. function logAccess($message, $context = [])
  2314. {
  2315. initLogging();
  2316. $entry = [
  2317. "timestamp" => date("Y-m-d H:i:s.u"),
  2318. "message" => $message,
  2319. "context" => $context,
  2320. "ip" => $_SERVER["REMOTE_ADDR"] ?? "unknown",
  2321. "request_method" => $_SERVER["REQUEST_METHOD"] ?? "unknown",
  2322. "request_uri" => $_SERVER["REQUEST_URI"] ?? "unknown",
  2323. ];
  2324. $logLine = json_encode($entry, JSON_UNESCAPED_UNICODE) . PHP_EOL;
  2325. file_put_contents(ACCESS_LOG_FILE, $logLine, FILE_APPEND | LOCK_EX);
  2326. }
  2327. function handleException($exception)
  2328. {
  2329. logError(
  2330. "Uncaught exception: " . $exception->getMessage(),
  2331. [
  2332. "file" => $exception->getFile(),
  2333. "line" => $exception->getLine(),
  2334. "trace" => $exception->getTraceAsString(),
  2335. ],
  2336. "CRITICAL",
  2337. );
  2338. if (defined("DEVELOPMENT_MODE") && DEVELOPMENT_MODE) {
  2339. echo "<h1>Error</h1><pre>" .
  2340. escape($exception->getMessage()) .
  2341. "</pre>";
  2342. } else {
  2343. echo "<h1>Es ist ein Fehler aufgetreten</h1><p>Bitte versuchen Sie es später erneut.</p>";
  2344. }
  2345. exit();
  2346. }
  2347. set_exception_handler("handleException");
  2348. function handleError($errno, $errstr, $errfile, $errline)
  2349. {
  2350. if (!(error_reporting() & $errno)) {
  2351. return false;
  2352. }
  2353. logError(
  2354. "PHP Error: " . $errstr,
  2355. [
  2356. "type" => $errno,
  2357. "file" => $errfile,
  2358. "line" => $errline,
  2359. ],
  2360. "WARNING",
  2361. );
  2362. return true;
  2363. }
  2364. set_error_handler("handleError");