functions.php 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517
  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 buildOrderPdfLines($order)
  1900. {
  1901. $lines = [
  1902. SITE_FULL_NAME,
  1903. SITE_DEPARTMENT_NAME,
  1904. "",
  1905. SITE_SERVICE_HEADER,
  1906. "Bestellnummer: " . $order["id"],
  1907. "Erstellt am: " . formatDate($order["created_at"]),
  1908. "Name: " . $order["customer_name"],
  1909. "E-Mail: " . $order["customer_email"],
  1910. "Organisation: " . $order["organization_label"],
  1911. "",
  1912. "Artikel:",
  1913. ];
  1914. foreach ($order["items"] as $item) {
  1915. $line = "- " . $item["product_name"];
  1916. if ($item["size"] !== "") {
  1917. $line .= " | Größe: " . $item["size"];
  1918. }
  1919. if ($item["availability_label"] !== "") {
  1920. $line .=
  1921. " | Hinweis: " .
  1922. preg_replace("/\s+/", " ", $item["availability_label"]);
  1923. }
  1924. $lines[] = $line;
  1925. }
  1926. $lines[] = "";
  1927. $lines[] = "Kommentar:";
  1928. if ($order["comment"] !== "") {
  1929. foreach (
  1930. preg_split('/\r\n|\r|\n/', $order["comment"])
  1931. as $commentLine
  1932. ) {
  1933. $lines[] = $commentLine;
  1934. }
  1935. } else {
  1936. $lines[] = "Kein Kommentar";
  1937. }
  1938. return $lines;
  1939. }
  1940. function pdfEscapeText($text)
  1941. {
  1942. $text = str_replace("\\", "\\\\", $text);
  1943. $text = str_replace("(", "\(", $text);
  1944. $text = str_replace(")", "\)", $text);
  1945. $text = str_replace("\r", "", $text);
  1946. if (function_exists("iconv")) {
  1947. $converted = @iconv("UTF-8", "Windows-1252//TRANSLIT//IGNORE", $text);
  1948. if (is_string($converted)) {
  1949. $text = $converted;
  1950. }
  1951. }
  1952. return $text;
  1953. }
  1954. function generateOrderPdf($order)
  1955. {
  1956. $lines = buildOrderPdfLines($order);
  1957. $content = "BT\n/F1 12 Tf\n14 TL\n50 790 Td\n";
  1958. $first = true;
  1959. foreach ($lines as $line) {
  1960. if (!$first) {
  1961. $content .= "T*\n";
  1962. }
  1963. $first = false;
  1964. $content .= "(" . pdfEscapeText($line) . ") Tj\n";
  1965. }
  1966. $content .= "ET";
  1967. $length = strlen($content);
  1968. $objects = [];
  1969. $objects[] = "1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n";
  1970. $objects[] = "2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n";
  1971. $objects[] =
  1972. "3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>\nendobj\n";
  1973. $objects[] =
  1974. "4 0 obj\n<< /Length " .
  1975. $length .
  1976. " >>\nstream\n" .
  1977. $content .
  1978. "\nendstream\nendobj\n";
  1979. $objects[] =
  1980. "5 0 obj\n<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>\nendobj\n";
  1981. $pdf = "%PDF-1.4\n";
  1982. $offsets = [0];
  1983. foreach ($objects as $object) {
  1984. $offsets[] = strlen($pdf);
  1985. $pdf .= $object;
  1986. }
  1987. $xrefOffset = strlen($pdf);
  1988. $pdf .= "xref\n0 " . (count($objects) + 1) . "\n";
  1989. $pdf .= "0000000000 65535 f \n";
  1990. for ($i = 1; $i <= count($objects); $i++) {
  1991. $pdf .= sprintf("%010d 00000 n \n", $offsets[$i]);
  1992. }
  1993. $pdf .= "trailer\n<< /Size " . (count($objects) + 1) . " /Root 1 0 R >>\n";
  1994. $pdf .= "startxref\n" . $xrefOffset . "\n%%EOF";
  1995. return $pdf;
  1996. }
  1997. /**
  1998. * Input Validation Class
  1999. */
  2000. class Validator
  2001. {
  2002. private $errors = [];
  2003. private $data = [];
  2004. public function __construct($data)
  2005. {
  2006. $this->data = $data;
  2007. }
  2008. public function required($field, $label = null)
  2009. {
  2010. $value = $this->get($field);
  2011. if (empty(trim($value ?? ""))) {
  2012. $this->errors[] = ($label ?? $field) . " ist erforderlich.";
  2013. }
  2014. return $this;
  2015. }
  2016. public function email($field, $label = null)
  2017. {
  2018. $value = $this->get($field);
  2019. if (!empty($value) && !filter_var($value, FILTER_VALIDATE_EMAIL)) {
  2020. $this->errors[] =
  2021. ($label ?? $field) . " muss eine gültige E-Mail-Adresse sein.";
  2022. }
  2023. return $this;
  2024. }
  2025. public function minLength($field, $min, $label = null)
  2026. {
  2027. $value = $this->get($field);
  2028. if (!empty($value) && strlen($value) < $min) {
  2029. $this->errors[] =
  2030. ($label ?? $field) .
  2031. " muss mindestens " .
  2032. $min .
  2033. " Zeichen lang sein.";
  2034. }
  2035. return $this;
  2036. }
  2037. public function maxLength($field, $max, $label = null)
  2038. {
  2039. $value = $this->get($field);
  2040. if (!empty($value) && strlen($value) > $max) {
  2041. $this->errors[] =
  2042. ($label ?? $field) .
  2043. " darf maximal " .
  2044. $max .
  2045. " Zeichen lang sein.";
  2046. }
  2047. return $this;
  2048. }
  2049. public function inArray($field, $allowed, $label = null)
  2050. {
  2051. $value = $this->get($field);
  2052. if (!empty($value) && !in_array($value, $allowed, true)) {
  2053. $this->errors[] = ($label ?? $field) . " ist ungültig.";
  2054. }
  2055. return $this;
  2056. }
  2057. public function get($field)
  2058. {
  2059. return $this->data[$field] ?? null;
  2060. }
  2061. public function getErrors()
  2062. {
  2063. return $this->errors;
  2064. }
  2065. public function isValid()
  2066. {
  2067. return empty($this->errors);
  2068. }
  2069. }
  2070. /**
  2071. * Error Logging Functions
  2072. */
  2073. if (!defined("LOG_DIR")) {
  2074. define("LOG_DIR", DATA_DIR . "logs/");
  2075. }
  2076. if (!defined("ERROR_LOG_FILE")) {
  2077. define("ERROR_LOG_FILE", LOG_DIR . "error.log");
  2078. }
  2079. if (!defined("ACCESS_LOG_FILE")) {
  2080. define("ACCESS_LOG_FILE", LOG_DIR . "access.log");
  2081. }
  2082. function initLogging()
  2083. {
  2084. if (!is_dir(LOG_DIR)) {
  2085. mkdir(LOG_DIR, 02775, true);
  2086. @chmod(LOG_DIR, 02775);
  2087. }
  2088. }
  2089. function logError($message, $context = [], $level = "ERROR")
  2090. {
  2091. initLogging();
  2092. $entry = [
  2093. "timestamp" => date("Y-m-d H:i:s.u"),
  2094. "level" => $level,
  2095. "message" => $message,
  2096. "context" => $context,
  2097. "ip" => $_SERVER["REMOTE_ADDR"] ?? "unknown",
  2098. "user_agent" => $_SERVER["HTTP_USER_AGENT"] ?? "unknown",
  2099. "request_uri" => $_SERVER["REQUEST_URI"] ?? "unknown",
  2100. "session_id" => session_id()
  2101. ? substr(session_id(), 0, 8) . "..."
  2102. : "none",
  2103. ];
  2104. $logLine = json_encode($entry, JSON_UNESCAPED_UNICODE) . PHP_EOL;
  2105. file_put_contents(ERROR_LOG_FILE, $logLine, FILE_APPEND | LOCK_EX);
  2106. if (defined("DEVELOPMENT_MODE") && DEVELOPMENT_MODE) {
  2107. error_log(
  2108. "PSA Order: " . $message . " | Context: " . json_encode($context),
  2109. );
  2110. }
  2111. }
  2112. function logAccess($message, $context = [])
  2113. {
  2114. initLogging();
  2115. $entry = [
  2116. "timestamp" => date("Y-m-d H:i:s.u"),
  2117. "message" => $message,
  2118. "context" => $context,
  2119. "ip" => $_SERVER["REMOTE_ADDR"] ?? "unknown",
  2120. "request_method" => $_SERVER["REQUEST_METHOD"] ?? "unknown",
  2121. "request_uri" => $_SERVER["REQUEST_URI"] ?? "unknown",
  2122. ];
  2123. $logLine = json_encode($entry, JSON_UNESCAPED_UNICODE) . PHP_EOL;
  2124. file_put_contents(ACCESS_LOG_FILE, $logLine, FILE_APPEND | LOCK_EX);
  2125. }
  2126. function handleException($exception)
  2127. {
  2128. logError(
  2129. "Uncaught exception: " . $exception->getMessage(),
  2130. [
  2131. "file" => $exception->getFile(),
  2132. "line" => $exception->getLine(),
  2133. "trace" => $exception->getTraceAsString(),
  2134. ],
  2135. "CRITICAL",
  2136. );
  2137. if (defined("DEVELOPMENT_MODE") && DEVELOPMENT_MODE) {
  2138. echo "<h1>Error</h1><pre>" .
  2139. escape($exception->getMessage()) .
  2140. "</pre>";
  2141. } else {
  2142. echo "<h1>Es ist ein Fehler aufgetreten</h1><p>Bitte versuchen Sie es später erneut.</p>";
  2143. }
  2144. exit();
  2145. }
  2146. set_exception_handler("handleException");
  2147. function handleError($errno, $errstr, $errfile, $errline)
  2148. {
  2149. if (!(error_reporting() & $errno)) {
  2150. return false;
  2151. }
  2152. logError(
  2153. "PHP Error: " . $errstr,
  2154. [
  2155. "type" => $errno,
  2156. "file" => $errfile,
  2157. "line" => $errline,
  2158. ],
  2159. "WARNING",
  2160. );
  2161. return true;
  2162. }
  2163. set_error_handler("handleError");