functions.php 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484
  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 generateCategoryIdFromLabel($label, $existingCategories = [])
  374. {
  375. $baseId = normalizeCategoryId($label);
  376. if ($baseId === "") {
  377. $baseId = "category";
  378. }
  379. $used = [];
  380. foreach (normalizeCategories($existingCategories) as $category) {
  381. $used[$category["id"]] = true;
  382. }
  383. $candidate = $baseId;
  384. $counter = 2;
  385. while (isset($used[$candidate])) {
  386. $candidate = $baseId . "-" . $counter;
  387. $counter++;
  388. }
  389. return $candidate;
  390. }
  391. function isCategoryInUse($categoryId)
  392. {
  393. foreach (getProducts() as $product) {
  394. if (productHasCategory($product, $categoryId)) {
  395. return true;
  396. }
  397. }
  398. return false;
  399. }
  400. function normalizeProductCategoryIds($categoryValue)
  401. {
  402. if (is_array($categoryValue)) {
  403. $rawIds = $categoryValue;
  404. } elseif ($categoryValue === null || $categoryValue === "") {
  405. $rawIds = [];
  406. } else {
  407. $rawIds = [$categoryValue];
  408. }
  409. $normalized = [];
  410. foreach ($rawIds as $categoryId) {
  411. $categoryId = normalizeCategoryId($categoryId);
  412. if ($categoryId !== "") {
  413. $normalized[$categoryId] = $categoryId;
  414. }
  415. }
  416. return array_values($normalized);
  417. }
  418. function getProductCategoryIds($product)
  419. {
  420. if (isset($product["categories"])) {
  421. return normalizeProductCategoryIds($product["categories"]);
  422. }
  423. return normalizeProductCategoryIds($product["category"] ?? []);
  424. }
  425. function productHasCategory($product, $categoryId)
  426. {
  427. $categoryId = normalizeCategoryId($categoryId);
  428. if ($categoryId === "") {
  429. return false;
  430. }
  431. return in_array($categoryId, getProductCategoryIds($product), true);
  432. }
  433. function getProductSizes($product)
  434. {
  435. if (isset($product["sizes"]) && is_array($product["sizes"])) {
  436. $sizes = $product["sizes"];
  437. } elseif (isset($product["sizes"]) && is_string($product["sizes"])) {
  438. $sizes = explode(",", $product["sizes"]);
  439. } else {
  440. $sizes = [];
  441. }
  442. $normalized = [];
  443. foreach ($sizes as $size) {
  444. $size = trim((string) $size);
  445. if ($size !== "") {
  446. $normalized[$size] = $size;
  447. }
  448. }
  449. return array_values($normalized);
  450. }
  451. function productUsesSizeStock($product)
  452. {
  453. return !empty(getProductSizes($product));
  454. }
  455. function normalizeAvailabilityLabels($sizes, $labels)
  456. {
  457. $result = [];
  458. if (!is_array($labels)) {
  459. $labels = [];
  460. }
  461. foreach ($sizes as $size) {
  462. $text = trim((string) ($labels[$size] ?? ""));
  463. $result[$size] = $text;
  464. }
  465. return $result;
  466. }
  467. function getAvailabilityLabel($product, $size)
  468. {
  469. $labels =
  470. isset($product["availability_labels"]) &&
  471. is_array($product["availability_labels"])
  472. ? $product["availability_labels"]
  473. : [];
  474. return trim((string) ($labels[$size] ?? ""));
  475. }
  476. function normalizeProductRecord($product, $defaultCategoryId = "")
  477. {
  478. if (!is_array($product)) {
  479. return null;
  480. }
  481. $productId = isset($product["id"]) ? (int) $product["id"] : 0;
  482. $name = trim((string) ($product["name"] ?? ""));
  483. if ($productId <= 0 || $name === "") {
  484. return null;
  485. }
  486. $sizes = getProductSizes($product);
  487. if (empty($sizes)) {
  488. $sizes = ["Standard"];
  489. }
  490. $categories = getProductCategoryIds($product);
  491. if (empty($categories) && $defaultCategoryId !== "") {
  492. $categories = [$defaultCategoryId];
  493. }
  494. $availabilityLabels = normalizeAvailabilityLabels(
  495. $sizes,
  496. isset($product["availability_labels"]) &&
  497. is_array($product["availability_labels"])
  498. ? $product["availability_labels"]
  499. : [],
  500. );
  501. return [
  502. "id" => $productId,
  503. "name" => $name,
  504. "description" => trim((string) ($product["description"] ?? "")),
  505. "image" => trim((string) ($product["image"] ?? "")),
  506. "categories" => $categories,
  507. "sizes" => implode(",", $sizes),
  508. "availability_labels" => $availabilityLabels,
  509. ];
  510. }
  511. function getProducts()
  512. {
  513. $data = readJsonFile(PRODUCTS_FILE);
  514. $rawProducts =
  515. isset($data["products"]) && is_array($data["products"])
  516. ? $data["products"]
  517. : [];
  518. $categories = getCategories();
  519. $defaultCategoryId = !empty($categories) ? $categories[0]["id"] : "apparel";
  520. $products = [];
  521. foreach ($rawProducts as $product) {
  522. $normalized = normalizeProductRecord($product, $defaultCategoryId);
  523. if ($normalized !== null) {
  524. $products[] = $normalized;
  525. }
  526. }
  527. usort($products, function ($left, $right) {
  528. return strcasecmp($left["name"], $right["name"]);
  529. });
  530. return $products;
  531. }
  532. function getProductById($id)
  533. {
  534. $id = (int) $id;
  535. foreach (getProducts() as $product) {
  536. if ((int) $product["id"] === $id) {
  537. return $product;
  538. }
  539. }
  540. return null;
  541. }
  542. function saveProducts($products)
  543. {
  544. $categories = getCategories();
  545. $defaultCategoryId = !empty($categories) ? $categories[0]["id"] : "apparel";
  546. $normalized = [];
  547. foreach ($products as $product) {
  548. $record = normalizeProductRecord($product, $defaultCategoryId);
  549. if ($record !== null) {
  550. $normalized[] = $record;
  551. }
  552. }
  553. return writeJsonFile(PRODUCTS_FILE, [
  554. "products" => array_values($normalized),
  555. ]);
  556. }
  557. function getFaqFilePath(): string
  558. {
  559. $dataDir = defined("DATA_DIR") ? DATA_DIR : dirname(__DIR__) . "/data/";
  560. $defaultPath = rtrim($dataDir, "/\\") . "/faq.json";
  561. if (!defined("FAQ_FILE") || !is_string(FAQ_FILE) || FAQ_FILE === "") {
  562. return $defaultPath;
  563. }
  564. $configuredPath = FAQ_FILE;
  565. $normalizedDataDir = str_replace("\\", "/", rtrim($dataDir, "/\\")) . "/";
  566. $normalizedConfigured = str_replace("\\", "/", $configuredPath);
  567. if (strpos($normalizedConfigured, $normalizedDataDir) !== 0) {
  568. return $defaultPath;
  569. }
  570. return $configuredPath;
  571. }
  572. function getFaqContent(): string
  573. {
  574. $defaultContent =
  575. "# FAQ\n\nHier kann der FAQ-Inhalt im Admin-Bereich bearbeitet werden.";
  576. $data = readJsonFile(getFaqFilePath());
  577. if (!isset($data["content"]) || !is_string($data["content"])) {
  578. return $defaultContent;
  579. }
  580. return $data["content"];
  581. }
  582. function saveFaqContent(string $markdown): bool
  583. {
  584. return writeJsonFile(getFaqFilePath(), ["content" => (string) $markdown]);
  585. }
  586. function renderFaqInlineMarkdown(string $text): string
  587. {
  588. $escaped = escape($text);
  589. $escaped = preg_replace_callback(
  590. '/\[([^\]]+)\]\(([^)\s]+)\)/',
  591. function ($matches) {
  592. $label = $matches[1];
  593. $url = trim(html_entity_decode($matches[2], ENT_QUOTES, "UTF-8"));
  594. if ($url === "") {
  595. return $matches[0];
  596. }
  597. $scheme = strtolower((string) parse_url($url, PHP_URL_SCHEME));
  598. if (!in_array($scheme, ["http", "https", "mailto"], true)) {
  599. return $matches[0];
  600. }
  601. return '<a href="' . escape($url) . '">' . $label . "</a>";
  602. },
  603. $escaped,
  604. );
  605. $escaped = preg_replace(
  606. "/\*\*(.+?)\*\*/s",
  607. '<strong>$1</strong>',
  608. $escaped,
  609. );
  610. $escaped = preg_replace(
  611. "/(?<!\*)\*(?!\s)(.+?)(?<!\s)\*(?!\*)/s",
  612. '<em>$1</em>',
  613. $escaped,
  614. );
  615. return $escaped;
  616. }
  617. function renderFaqMarkdown(string $markdown): string
  618. {
  619. $normalized = str_replace(["\r\n", "\r"], "\n", $markdown);
  620. $lines = explode("\n", $normalized);
  621. $htmlParts = [];
  622. $paragraphLines = [];
  623. $listType = "";
  624. $flushParagraph = function () use (&$paragraphLines, &$htmlParts): void {
  625. if (empty($paragraphLines)) {
  626. return;
  627. }
  628. $rendered = [];
  629. foreach ($paragraphLines as $line) {
  630. $rendered[] = renderFaqInlineMarkdown($line);
  631. }
  632. $htmlParts[] = "<p>" . implode("<br>\n", $rendered) . "</p>";
  633. $paragraphLines = [];
  634. };
  635. $closeList = function () use (&$listType, &$htmlParts): void {
  636. if ($listType !== "") {
  637. $htmlParts[] = "</" . $listType . ">";
  638. $listType = "";
  639. }
  640. };
  641. foreach ($lines as $line) {
  642. $line = rtrim($line);
  643. $trimmed = trim($line);
  644. if ($trimmed === "") {
  645. $flushParagraph();
  646. $closeList();
  647. continue;
  648. }
  649. if (preg_match('/^(#{1,3})\s+(.+)$/', $trimmed, $matches) === 1) {
  650. $flushParagraph();
  651. $closeList();
  652. $level = strlen($matches[1]);
  653. $htmlParts[] =
  654. "<h" .
  655. $level .
  656. ">" .
  657. renderFaqInlineMarkdown($matches[2]) .
  658. "</h" .
  659. $level .
  660. ">";
  661. continue;
  662. }
  663. if (preg_match('/^\s*[-*]\s+(.+)$/', $line, $matches) === 1) {
  664. $flushParagraph();
  665. if ($listType !== "ul") {
  666. $closeList();
  667. $listType = "ul";
  668. $htmlParts[] = "<ul>";
  669. }
  670. $htmlParts[] =
  671. "<li>" . renderFaqInlineMarkdown($matches[1]) . "</li>";
  672. continue;
  673. }
  674. if (preg_match('/^\s*\d+\.\s+(.+)$/', $line, $matches) === 1) {
  675. $flushParagraph();
  676. if ($listType !== "ol") {
  677. $closeList();
  678. $listType = "ol";
  679. $htmlParts[] = "<ol>";
  680. }
  681. $htmlParts[] =
  682. "<li>" . renderFaqInlineMarkdown($matches[1]) . "</li>";
  683. continue;
  684. }
  685. $closeList();
  686. $paragraphLines[] = $trimmed;
  687. }
  688. $flushParagraph();
  689. $closeList();
  690. return empty($htmlParts)
  691. ? "<p>Keine FAQ-Inhalte vorhanden.</p>"
  692. : implode("\n", $htmlParts);
  693. }
  694. function getDefaultOrganizations()
  695. {
  696. return [
  697. [
  698. "id" => "feuerwehr-freising",
  699. "label" => "Amt 32 - Feuerwehr Freising",
  700. "sort_order" => 10,
  701. "active" => true,
  702. ],
  703. ];
  704. }
  705. function normalizeOrganizationId($id)
  706. {
  707. return normalizeCategoryId($id);
  708. }
  709. function normalizeOrganizationLabel($label)
  710. {
  711. return trim((string) $label);
  712. }
  713. function isValidOrganizationLabel($label)
  714. {
  715. $label = normalizeOrganizationLabel($label);
  716. if ($label === "") {
  717. return false;
  718. }
  719. $length = function_exists("mb_strlen") ? mb_strlen($label) : strlen($label);
  720. return $length <= 120;
  721. }
  722. function normalizeOrganizations($organizations)
  723. {
  724. $normalized = [];
  725. if (!is_array($organizations)) {
  726. $organizations = [];
  727. }
  728. foreach ($organizations as $organization) {
  729. if (!is_array($organization)) {
  730. continue;
  731. }
  732. $id = normalizeOrganizationId($organization["id"] ?? "");
  733. $label = normalizeOrganizationLabel($organization["label"] ?? "");
  734. if ($id === "" || !isValidOrganizationLabel($label)) {
  735. continue;
  736. }
  737. $sortOrder = isset($organization["sort_order"])
  738. ? (int) $organization["sort_order"]
  739. : 0;
  740. $active =
  741. !isset($organization["active"]) || (bool) $organization["active"];
  742. $normalized[$id] = [
  743. "id" => $id,
  744. "label" => $label,
  745. "sort_order" => $sortOrder,
  746. "active" => $active,
  747. ];
  748. }
  749. if (empty($normalized)) {
  750. foreach (getDefaultOrganizations() as $organization) {
  751. $normalized[$organization["id"]] = $organization;
  752. }
  753. }
  754. uasort($normalized, function ($left, $right) {
  755. if ($left["sort_order"] === $right["sort_order"]) {
  756. return strcasecmp($left["label"], $right["label"]);
  757. }
  758. return $left["sort_order"] <=> $right["sort_order"];
  759. });
  760. return array_values($normalized);
  761. }
  762. function getOrganizations($onlyActive = false)
  763. {
  764. $data = readJsonFile(ORGANIZATIONS_FILE);
  765. $organizations = normalizeOrganizations($data["organizations"] ?? []);
  766. if ($onlyActive) {
  767. $organizations = array_values(
  768. array_filter($organizations, function ($organization) {
  769. return !empty($organization["active"]);
  770. }),
  771. );
  772. }
  773. return $organizations;
  774. }
  775. function saveOrganizations($organizations)
  776. {
  777. return writeJsonFile(ORGANIZATIONS_FILE, [
  778. "organizations" => normalizeOrganizations($organizations),
  779. ]);
  780. }
  781. function getOrganizationById($organizationId)
  782. {
  783. $organizationId = normalizeOrganizationId($organizationId);
  784. foreach (getOrganizations(false) as $organization) {
  785. if ($organization["id"] === $organizationId) {
  786. return $organization;
  787. }
  788. }
  789. return null;
  790. }
  791. function generateOrganizationIdFromLabel($label, $existingOrganizations = [])
  792. {
  793. $baseId = normalizeOrganizationId($label);
  794. if ($baseId === "") {
  795. $baseId = "organization";
  796. }
  797. $used = [];
  798. foreach (normalizeOrganizations($existingOrganizations) as $organization) {
  799. $used[$organization["id"]] = true;
  800. }
  801. $candidate = $baseId;
  802. $counter = 2;
  803. while (isset($used[$candidate])) {
  804. $candidate = $baseId . "-" . $counter;
  805. $counter++;
  806. }
  807. return $candidate;
  808. }
  809. function getDefaultSystemSettings()
  810. {
  811. $startpageIntroText = "";
  812. if (defined("DISCLAIMER_LINES") && is_array(DISCLAIMER_LINES)) {
  813. $lines = array_filter(
  814. array_map(function ($line) {
  815. return trim((string) $line);
  816. }, DISCLAIMER_LINES),
  817. function ($line) {
  818. return $line !== "";
  819. },
  820. );
  821. $startpageIntroText = implode("\n", $lines);
  822. }
  823. return [
  824. "order_recipient_email" => defined("ORDER_RECIPIENT_EMAIL")
  825. ? ORDER_RECIPIENT_EMAIL
  826. : getDefaultAdminEmail(),
  827. "order_confirmation_required" => defined("ORDER_CONFIRMATION_REQUIRED")
  828. ? (bool) ORDER_CONFIRMATION_REQUIRED
  829. : false,
  830. "order_confirmation_expiry_days" => defined(
  831. "ORDER_CONFIRMATION_EXPIRY_DAYS",
  832. )
  833. ? (int) ORDER_CONFIRMATION_EXPIRY_DAYS
  834. : 7,
  835. "attach_order_pdf_to_admin_email" => defined(
  836. "ATTACH_ORDER_PDF_TO_ADMIN_EMAIL",
  837. )
  838. ? (bool) ATTACH_ORDER_PDF_TO_ADMIN_EMAIL
  839. : true,
  840. "startpage_intro_text" => $startpageIntroText,
  841. ];
  842. }
  843. function normalizeSystemSettings($settings)
  844. {
  845. $defaults = getDefaultSystemSettings();
  846. if (!is_array($settings)) {
  847. $settings = [];
  848. }
  849. $recipientEmail = normalizeAdminEmail(
  850. $settings["order_recipient_email"] ??
  851. $defaults["order_recipient_email"],
  852. );
  853. if (!isValidAdminEmail($recipientEmail)) {
  854. $recipientEmail = $defaults["order_recipient_email"];
  855. }
  856. $expiryDays = isset($settings["order_confirmation_expiry_days"])
  857. ? (int) $settings["order_confirmation_expiry_days"]
  858. : $defaults["order_confirmation_expiry_days"];
  859. if ($expiryDays < 1) {
  860. $expiryDays = 7;
  861. }
  862. $startpageIntroText = trim(
  863. (string) ($settings["startpage_intro_text"] ?? $defaults["startpage_intro_text"]),
  864. );
  865. return [
  866. "order_recipient_email" => $recipientEmail,
  867. "order_confirmation_required" => !empty(
  868. $settings["order_confirmation_required"]
  869. ),
  870. "order_confirmation_expiry_days" => $expiryDays,
  871. "attach_order_pdf_to_admin_email" => !empty(
  872. $settings["attach_order_pdf_to_admin_email"]
  873. ),
  874. "startpage_intro_text" => $startpageIntroText,
  875. ];
  876. }
  877. function getSystemSettings()
  878. {
  879. $data = readJsonFile(SETTINGS_FILE);
  880. return normalizeSystemSettings($data["settings"] ?? []);
  881. }
  882. function saveSystemSettings($settings)
  883. {
  884. return writeJsonFile(SETTINGS_FILE, [
  885. "settings" => normalizeSystemSettings($settings),
  886. ]);
  887. }
  888. function getOrderRecipientEmail()
  889. {
  890. $settings = getSystemSettings();
  891. return $settings["order_recipient_email"];
  892. }
  893. function isOrderConfirmationRequired()
  894. {
  895. $settings = getSystemSettings();
  896. return !empty($settings["order_confirmation_required"]);
  897. }
  898. function getOrderConfirmationExpiryDays()
  899. {
  900. $settings = getSystemSettings();
  901. return max(1, (int) $settings["order_confirmation_expiry_days"]);
  902. }
  903. function shouldAttachOrderPdfToAdminEmail()
  904. {
  905. $settings = getSystemSettings();
  906. return !empty($settings["attach_order_pdf_to_admin_email"]);
  907. }
  908. function getStartpageIntroLines()
  909. {
  910. $settings = getSystemSettings();
  911. $text = trim((string) ($settings["startpage_intro_text"] ?? ""));
  912. if ($text === "") {
  913. return [];
  914. }
  915. $lines = preg_split('/\R+/', $text) ?: [];
  916. $lines = array_values(
  917. array_filter(
  918. array_map(function ($line) {
  919. return trim((string) $line);
  920. }, $lines),
  921. function ($line) {
  922. return $line !== "";
  923. },
  924. ),
  925. );
  926. return $lines;
  927. }
  928. function normalizeOrderItem($item)
  929. {
  930. if (!is_array($item)) {
  931. return null;
  932. }
  933. $productId = isset($item["product_id"]) ? (int) $item["product_id"] : 0;
  934. if ($productId <= 0) {
  935. return null;
  936. }
  937. $product = getProductById($productId);
  938. if ($product === null) {
  939. return null;
  940. }
  941. $size = trim((string) ($item["size"] ?? ""));
  942. $sizes = getProductSizes($product);
  943. if (!empty($sizes)) {
  944. if ($size === "" || !in_array($size, $sizes, true)) {
  945. return null;
  946. }
  947. } else {
  948. $size = "";
  949. }
  950. return [
  951. "product_id" => $productId,
  952. "product_name" => $product["name"],
  953. "size" => $size,
  954. "availability_label" =>
  955. $size !== "" ? getAvailabilityLabel($product, $size) : "",
  956. "is_processed" => !empty($item["is_processed"]),
  957. ];
  958. }
  959. function normalizeOrderItems($items)
  960. {
  961. $normalized = [];
  962. $seen = [];
  963. if (!is_array($items)) {
  964. return [];
  965. }
  966. foreach ($items as $item) {
  967. $record = normalizeOrderItem($item);
  968. if ($record === null) {
  969. continue;
  970. }
  971. $key = $record["product_id"] . "|" . $record["size"];
  972. if (isset($seen[$key])) {
  973. continue;
  974. }
  975. $seen[$key] = true;
  976. $normalized[] = $record;
  977. }
  978. return array_values($normalized);
  979. }
  980. function getOrders()
  981. {
  982. $data = readJsonFile(ORDERS_FILE);
  983. $orders =
  984. isset($data["orders"]) && is_array($data["orders"])
  985. ? $data["orders"]
  986. : [];
  987. $normalized = [];
  988. foreach ($orders as $order) {
  989. $record = normalizeOrderRecord($order);
  990. if ($record !== null) {
  991. $normalized[] = $record;
  992. }
  993. }
  994. return $normalized;
  995. }
  996. function saveOrders($orders)
  997. {
  998. $normalized = [];
  999. foreach ($orders as $order) {
  1000. $record = normalizeOrderRecord($order);
  1001. if ($record !== null) {
  1002. $normalized[] = $record;
  1003. }
  1004. }
  1005. $result = writeJsonFile(ORDERS_FILE, [
  1006. "orders" => array_values($normalized),
  1007. ]);
  1008. if (!$result) {
  1009. logError("Failed to save orders", [
  1010. "file" => ORDERS_FILE,
  1011. "order_count" => count($normalized),
  1012. ]);
  1013. }
  1014. return (bool) $result;
  1015. }
  1016. function generateOrderId()
  1017. {
  1018. $orders = getOrders();
  1019. $year = date("Y");
  1020. $prefix = defined("ORDER_PREFIX") ? ORDER_PREFIX : "ORD";
  1021. $max = 0;
  1022. $pattern = "/^" . preg_quote($prefix, "/") . '-\d{4}-(\d+)$/';
  1023. foreach ($orders as $order) {
  1024. if (preg_match($pattern, (string) $order["id"], $matches) === 1) {
  1025. $number = (int) $matches[1];
  1026. if ($number > $max) {
  1027. $max = $number;
  1028. }
  1029. }
  1030. }
  1031. return sprintf("%s-%s-%03d", $prefix, $year, $max + 1);
  1032. }
  1033. function normalizeOrderRecord($order)
  1034. {
  1035. if (!is_array($order)) {
  1036. return null;
  1037. }
  1038. $id = trim((string) ($order["id"] ?? ""));
  1039. $customerName = trim((string) ($order["customer_name"] ?? ""));
  1040. $customerEmail = normalizeAdminEmail($order["customer_email"] ?? "");
  1041. $organizationId = normalizeOrganizationId($order["organization_id"] ?? "");
  1042. $organizationLabel = trim((string) ($order["organization_label"] ?? ""));
  1043. $items = normalizeOrderItems($order["items"] ?? []);
  1044. if (
  1045. $id === "" ||
  1046. $customerName === "" ||
  1047. !isValidAdminEmail($customerEmail) ||
  1048. $organizationId === "" ||
  1049. $organizationLabel === "" ||
  1050. empty($items)
  1051. ) {
  1052. return null;
  1053. }
  1054. $createdAt = trim((string) ($order["created_at"] ?? ""));
  1055. if ($createdAt === "") {
  1056. $createdAt = date("Y-m-d H:i:s");
  1057. }
  1058. $confirmationStatus = trim(
  1059. (string) ($order["confirmation_status"] ?? "confirmed"),
  1060. );
  1061. $allowedConfirmationStatuses = [
  1062. "not_required",
  1063. "pending",
  1064. "confirmed",
  1065. "expired",
  1066. ];
  1067. if (!in_array($confirmationStatus, $allowedConfirmationStatuses, true)) {
  1068. $confirmationStatus = "confirmed";
  1069. }
  1070. $status = trim((string) ($order["status"] ?? "open"));
  1071. $allowedStatuses = ["open", "partial", "processed", "cancelled"];
  1072. if (!in_array($status, $allowedStatuses, true)) {
  1073. $status = "open";
  1074. }
  1075. $normalized = [
  1076. "id" => $id,
  1077. "customer_name" => $customerName,
  1078. "customer_email" => $customerEmail,
  1079. "organization_id" => $organizationId,
  1080. "organization_label" => $organizationLabel,
  1081. "comment" => trim((string) ($order["comment"] ?? "")),
  1082. "items" => $items,
  1083. "status" => $status,
  1084. "confirmation_status" => $confirmationStatus,
  1085. "confirmation_token" => trim(
  1086. (string) ($order["confirmation_token"] ?? ""),
  1087. ),
  1088. "confirmation_expires_at" => trim(
  1089. (string) ($order["confirmation_expires_at"] ?? ""),
  1090. ),
  1091. "confirmed_at" => trim((string) ($order["confirmed_at"] ?? "")),
  1092. "created_at" => $createdAt,
  1093. "updated_at" => trim((string) ($order["updated_at"] ?? $createdAt)),
  1094. "cancelled_at" => trim((string) ($order["cancelled_at"] ?? "")),
  1095. "cancelled_by" => trim((string) ($order["cancelled_by"] ?? "")),
  1096. "cancellation_reason" => trim(
  1097. (string) ($order["cancellation_reason"] ?? ""),
  1098. ),
  1099. "admin_notified_at" => trim(
  1100. (string) ($order["admin_notified_at"] ?? ""),
  1101. ),
  1102. ];
  1103. return refreshOrderState($normalized);
  1104. }
  1105. function refreshOrderState($order)
  1106. {
  1107. if (!is_array($order)) {
  1108. return null;
  1109. }
  1110. if (($order["status"] ?? "") === "cancelled") {
  1111. return $order;
  1112. }
  1113. if (
  1114. ($order["confirmation_status"] ?? "") === "pending" &&
  1115. !empty($order["confirmation_expires_at"])
  1116. ) {
  1117. $expiresAt = strtotime((string) $order["confirmation_expires_at"]);
  1118. if ($expiresAt !== false && time() > $expiresAt) {
  1119. $order["confirmation_status"] = "expired";
  1120. }
  1121. }
  1122. $processedCount = 0;
  1123. foreach ($order["items"] as $item) {
  1124. if (!empty($item["is_processed"])) {
  1125. $processedCount++;
  1126. }
  1127. }
  1128. if ($processedCount <= 0) {
  1129. $order["status"] = "open";
  1130. } elseif ($processedCount >= count($order["items"])) {
  1131. $order["status"] = "processed";
  1132. } else {
  1133. $order["status"] = "partial";
  1134. }
  1135. return $order;
  1136. }
  1137. function expirePendingOrders()
  1138. {
  1139. $orders = getOrders();
  1140. $changed = false;
  1141. foreach ($orders as &$order) {
  1142. $updated = refreshOrderState($order);
  1143. if ($updated !== $order) {
  1144. $order = $updated;
  1145. $changed = true;
  1146. }
  1147. }
  1148. unset($order);
  1149. if ($changed) {
  1150. saveOrders($orders);
  1151. }
  1152. }
  1153. function getOrderById($orderId)
  1154. {
  1155. $orderId = trim((string) $orderId);
  1156. if ($orderId === "") {
  1157. return null;
  1158. }
  1159. foreach (getOrders() as $order) {
  1160. if ($order["id"] === $orderId) {
  1161. return $order;
  1162. }
  1163. }
  1164. return null;
  1165. }
  1166. function findOrderByConfirmationToken($token)
  1167. {
  1168. $token = trim((string) $token);
  1169. if ($token === "") {
  1170. return null;
  1171. }
  1172. foreach (getOrders() as $order) {
  1173. if (($order["confirmation_token"] ?? "") === $token) {
  1174. return $order;
  1175. }
  1176. }
  1177. return null;
  1178. }
  1179. function buildOrderConfirmationUrl($token)
  1180. {
  1181. $path = "/order-confirm.php?token=" . urlencode($token);
  1182. return buildAbsoluteUrl($path);
  1183. }
  1184. function buildAbsoluteUrl($path)
  1185. {
  1186. $path = "/" . ltrim((string) $path, "/");
  1187. $siteUrl = defined("SITE_URL") ? trim((string) SITE_URL) : "";
  1188. if (strpos($siteUrl, "://") !== false) {
  1189. return rtrim($siteUrl, "/") . $path;
  1190. }
  1191. $basePath = trim($siteUrl);
  1192. if ($basePath !== "" && $basePath !== "/") {
  1193. $path = "/" . trim($basePath, "/") . $path;
  1194. }
  1195. $scheme = isHttpsRequest() ? "https" : "http";
  1196. $host = $_SERVER["HTTP_HOST"] ?? "";
  1197. if ($host === "") {
  1198. return $path;
  1199. }
  1200. return $scheme . "://" . $host . $path;
  1201. }
  1202. function isHttpsRequest(): bool
  1203. {
  1204. if (
  1205. !empty($_SERVER["HTTPS"]) &&
  1206. strtolower((string) $_SERVER["HTTPS"]) !== "off"
  1207. ) {
  1208. return true;
  1209. }
  1210. if (
  1211. !empty($_SERVER["HTTP_X_FORWARDED_PROTO"]) &&
  1212. strtolower((string) $_SERVER["HTTP_X_FORWARDED_PROTO"]) === "https"
  1213. ) {
  1214. return true;
  1215. }
  1216. if (
  1217. !empty($_SERVER["SERVER_PORT"]) &&
  1218. (int) $_SERVER["SERVER_PORT"] === 443
  1219. ) {
  1220. return true;
  1221. }
  1222. return false;
  1223. }
  1224. function createOrder(
  1225. $customerName,
  1226. $customerEmail,
  1227. $organizationId,
  1228. $comment,
  1229. $items,
  1230. ) {
  1231. $customerName = sanitize($customerName);
  1232. $customerEmail = normalizeAdminEmail($customerEmail);
  1233. $organizationId = normalizeOrganizationId($organizationId);
  1234. $comment = trim((string) $comment);
  1235. $items = normalizeOrderItems($items);
  1236. if ($customerName === "") {
  1237. return [
  1238. "success" => false,
  1239. "message" => "Bitte geben Sie einen Namen ein.",
  1240. ];
  1241. }
  1242. if (!isValidAdminEmail($customerEmail)) {
  1243. return [
  1244. "success" => false,
  1245. "message" => "Bitte geben Sie eine gültige E-Mail-Adresse ein.",
  1246. ];
  1247. }
  1248. if (empty($items)) {
  1249. return [
  1250. "success" => false,
  1251. "message" =>
  1252. "Der Warenkorb ist leer oder enthält ungültige Positionen.",
  1253. ];
  1254. }
  1255. $organization = getOrganizationById($organizationId);
  1256. if ($organization === null || empty($organization["active"])) {
  1257. return [
  1258. "success" => false,
  1259. "message" => "Bitte wählen Sie eine gültige Organisation aus.",
  1260. ];
  1261. }
  1262. $now = date("Y-m-d H:i:s");
  1263. $requiresConfirmation = isOrderConfirmationRequired();
  1264. $confirmationToken = $requiresConfirmation ? bin2hex(random_bytes(24)) : "";
  1265. $confirmationExpiresAt = "";
  1266. if ($requiresConfirmation) {
  1267. $expires = new DateTimeImmutable();
  1268. $expires = $expires->modify(
  1269. "+" . getOrderConfirmationExpiryDays() . " days",
  1270. );
  1271. $confirmationExpiresAt = $expires->format("Y-m-d H:i:s");
  1272. }
  1273. $order = [
  1274. "id" => generateOrderId(),
  1275. "customer_name" => $customerName,
  1276. "customer_email" => $customerEmail,
  1277. "organization_id" => $organization["id"],
  1278. "organization_label" => $organization["label"],
  1279. "comment" => $comment,
  1280. "items" => $items,
  1281. "status" => "open",
  1282. "confirmation_status" => $requiresConfirmation
  1283. ? "pending"
  1284. : "not_required",
  1285. "confirmation_token" => $confirmationToken,
  1286. "confirmation_expires_at" => $confirmationExpiresAt,
  1287. "confirmed_at" => $requiresConfirmation ? "" : $now,
  1288. "created_at" => $now,
  1289. "updated_at" => $now,
  1290. "cancelled_at" => "",
  1291. "cancelled_by" => "",
  1292. "cancellation_reason" => "",
  1293. "admin_notified_at" => "",
  1294. ];
  1295. $orders = getOrders();
  1296. $orders[] = $order;
  1297. saveOrders($orders);
  1298. logAccess("Order created in createOrder", [
  1299. "order_id" => $order["id"],
  1300. "customer" => $customerEmail,
  1301. "organization" => $organization["label"],
  1302. ]);
  1303. if ($requiresConfirmation) {
  1304. sendOrderConfirmationRequestEmail($order);
  1305. } else {
  1306. $result = sendConfirmedOrderAdminNotification($order);
  1307. if ($result) {
  1308. markOrderAdminNotified($order["id"]);
  1309. $order = getOrderById($order["id"]);
  1310. }
  1311. sendOrderCreatedCustomerEmail($order);
  1312. }
  1313. return ["success" => true, "order" => $order];
  1314. }
  1315. function markOrderAdminNotified($orderId)
  1316. {
  1317. $orders = getOrders();
  1318. foreach ($orders as &$order) {
  1319. if ($order["id"] !== $orderId) {
  1320. continue;
  1321. }
  1322. $order["admin_notified_at"] = date("Y-m-d H:i:s");
  1323. $order["updated_at"] = date("Y-m-d H:i:s");
  1324. break;
  1325. }
  1326. unset($order);
  1327. saveOrders($orders);
  1328. }
  1329. function confirmOrderByToken($token)
  1330. {
  1331. $orders = getOrders();
  1332. $now = date("Y-m-d H:i:s");
  1333. foreach ($orders as &$order) {
  1334. if (($order["confirmation_token"] ?? "") !== $token) {
  1335. continue;
  1336. }
  1337. $order = refreshOrderState($order);
  1338. if ($order["status"] === "cancelled") {
  1339. return [
  1340. "success" => false,
  1341. "message" =>
  1342. "Diese Bestellung wurde storniert und kann nicht mehr bestätigt werden.",
  1343. ];
  1344. }
  1345. if ($order["confirmation_status"] === "confirmed") {
  1346. return [
  1347. "success" => false,
  1348. "message" => "Diese Bestellung wurde bereits bestätigt.",
  1349. ];
  1350. }
  1351. if ($order["confirmation_status"] === "expired") {
  1352. return [
  1353. "success" => false,
  1354. "message" => "Der Bestätigungslink ist abgelaufen.",
  1355. ];
  1356. }
  1357. if ($order["confirmation_status"] !== "pending") {
  1358. return [
  1359. "success" => false,
  1360. "message" =>
  1361. "Für diese Bestellung ist keine Bestätigung erforderlich.",
  1362. ];
  1363. }
  1364. $expiresAt = strtotime((string) $order["confirmation_expires_at"]);
  1365. if ($expiresAt !== false && time() > $expiresAt) {
  1366. $order["confirmation_status"] = "expired";
  1367. $order["updated_at"] = $now;
  1368. saveOrders($orders);
  1369. return [
  1370. "success" => false,
  1371. "message" => "Der Bestätigungslink ist abgelaufen.",
  1372. ];
  1373. }
  1374. $order["confirmation_status"] = "confirmed";
  1375. $order["confirmed_at"] = $now;
  1376. $order["updated_at"] = $now;
  1377. saveOrders($orders);
  1378. $sent = sendConfirmedOrderAdminNotification($order);
  1379. if ($sent) {
  1380. markOrderAdminNotified($order["id"]);
  1381. }
  1382. sendOrderConfirmedCustomerEmail(getOrderById($order["id"]));
  1383. return ["success" => true, "order" => getOrderById($order["id"])];
  1384. }
  1385. unset($order);
  1386. return ["success" => false, "message" => "Bestellung nicht gefunden."];
  1387. }
  1388. function toggleOrderItemProcessed($orderId, $itemIndex)
  1389. {
  1390. $orders = getOrders();
  1391. $now = date("Y-m-d H:i:s");
  1392. foreach ($orders as &$order) {
  1393. if ($order["id"] !== $orderId) {
  1394. continue;
  1395. }
  1396. if ($order["status"] === "cancelled") {
  1397. return [
  1398. "success" => false,
  1399. "message" =>
  1400. "Stornierte Bestellungen können nicht mehr bearbeitet werden.",
  1401. ];
  1402. }
  1403. if (($order["confirmation_status"] ?? "") === "pending") {
  1404. return [
  1405. "success" => false,
  1406. "message" =>
  1407. "Unbestätigte Bestellungen können noch nicht bearbeitet werden.",
  1408. ];
  1409. }
  1410. if (($order["confirmation_status"] ?? "") === "expired") {
  1411. return [
  1412. "success" => false,
  1413. "message" =>
  1414. "Abgelaufene unbestätigte Bestellungen können nicht bearbeitet werden.",
  1415. ];
  1416. }
  1417. if (!isset($order["items"][$itemIndex])) {
  1418. return [
  1419. "success" => false,
  1420. "message" => "Position nicht gefunden.",
  1421. ];
  1422. }
  1423. $order["items"][$itemIndex]["is_processed"] = empty(
  1424. $order["items"][$itemIndex]["is_processed"]
  1425. );
  1426. $order["updated_at"] = $now;
  1427. $order = refreshOrderState($order);
  1428. saveOrders($orders);
  1429. return ["success" => true, "order" => $order];
  1430. }
  1431. unset($order);
  1432. return ["success" => false, "message" => "Bestellung nicht gefunden."];
  1433. }
  1434. function cancelOrder($orderId, $adminUsername, $reason = "")
  1435. {
  1436. $orders = getOrders();
  1437. $now = date("Y-m-d H:i:s");
  1438. $adminUsername = normalizeAdminUsername($adminUsername);
  1439. $reason = trim((string) $reason);
  1440. foreach ($orders as &$order) {
  1441. if ($order["id"] !== $orderId) {
  1442. continue;
  1443. }
  1444. if ($order["status"] === "cancelled") {
  1445. return [
  1446. "success" => false,
  1447. "message" => "Die Bestellung ist bereits storniert.",
  1448. ];
  1449. }
  1450. $order["status"] = "cancelled";
  1451. $order["cancelled_at"] = $now;
  1452. $order["cancelled_by"] = $adminUsername;
  1453. $order["cancellation_reason"] = $reason;
  1454. $order["updated_at"] = $now;
  1455. saveOrders($orders);
  1456. return ["success" => true, "order" => $order];
  1457. }
  1458. unset($order);
  1459. return ["success" => false, "message" => "Bestellung nicht gefunden."];
  1460. }
  1461. function getOrderStatusLabel($order)
  1462. {
  1463. if (($order["status"] ?? "") === "cancelled") {
  1464. return "Storniert";
  1465. }
  1466. if (($order["confirmation_status"] ?? "") === "pending") {
  1467. return "Unbestätigt";
  1468. }
  1469. if (($order["confirmation_status"] ?? "") === "expired") {
  1470. return "Bestätigung abgelaufen";
  1471. }
  1472. if (($order["status"] ?? "") === "processed") {
  1473. return "Bearbeitet";
  1474. }
  1475. if (($order["status"] ?? "") === "partial") {
  1476. return "Teilweise bearbeitet";
  1477. }
  1478. return "Offen";
  1479. }
  1480. function getOrderStatusClass($order)
  1481. {
  1482. if (($order["status"] ?? "") === "cancelled") {
  1483. return "status-cancelled";
  1484. }
  1485. if (($order["confirmation_status"] ?? "") === "pending") {
  1486. return "status-unconfirmed";
  1487. }
  1488. if (($order["confirmation_status"] ?? "") === "expired") {
  1489. return "status-expired";
  1490. }
  1491. if (($order["status"] ?? "") === "processed") {
  1492. return "status-processed";
  1493. }
  1494. if (($order["status"] ?? "") === "partial") {
  1495. return "status-partial";
  1496. }
  1497. return "status-open";
  1498. }
  1499. function formatDate($dateString)
  1500. {
  1501. $dateString = trim((string) $dateString);
  1502. if ($dateString === "") {
  1503. return "-";
  1504. }
  1505. try {
  1506. $date = new DateTimeImmutable($dateString);
  1507. return $date->format("d.m.Y H:i");
  1508. } catch (Exception $exception) {
  1509. return $dateString;
  1510. }
  1511. }
  1512. function getCart()
  1513. {
  1514. $cart = $_SESSION["cart"] ?? [];
  1515. if (!is_array($cart)) {
  1516. $cart = [];
  1517. }
  1518. $normalized = [];
  1519. foreach ($cart as $item) {
  1520. $productId = isset($item["product_id"]) ? (int) $item["product_id"] : 0;
  1521. $size = trim((string) ($item["size"] ?? ""));
  1522. $product = getProductById($productId);
  1523. if ($product === null) {
  1524. continue;
  1525. }
  1526. $sizes = getProductSizes($product);
  1527. if (!empty($sizes)) {
  1528. if ($size === "" || !in_array($size, $sizes, true)) {
  1529. continue;
  1530. }
  1531. } else {
  1532. $size = "";
  1533. }
  1534. if (isset($normalized[$productId])) {
  1535. unset($normalized[$productId]);
  1536. }
  1537. $normalized[$productId] = [
  1538. "product_id" => $productId,
  1539. "size" => $size,
  1540. ];
  1541. }
  1542. $_SESSION["cart"] = array_values($normalized);
  1543. return $_SESSION["cart"];
  1544. }
  1545. function addCartItem($productId, $size = "")
  1546. {
  1547. $productId = (int) $productId;
  1548. $size = trim((string) $size);
  1549. $product = getProductById($productId);
  1550. if ($product === null) {
  1551. return [
  1552. "success" => false,
  1553. "status" => "error",
  1554. ];
  1555. }
  1556. $sizes = getProductSizes($product);
  1557. if (!empty($sizes)) {
  1558. if ($size === "" || !in_array($size, $sizes, true)) {
  1559. return [
  1560. "success" => false,
  1561. "status" => "error",
  1562. ];
  1563. }
  1564. } else {
  1565. $size = "";
  1566. }
  1567. $cart = getCart();
  1568. foreach ($cart as $index => $item) {
  1569. if ((int) $item["product_id"] !== $productId) {
  1570. continue;
  1571. }
  1572. $existingSize = trim((string) ($item["size"] ?? ""));
  1573. if ($existingSize === $size) {
  1574. return [
  1575. "success" => true,
  1576. "status" => "unchanged",
  1577. "size" => $size,
  1578. ];
  1579. }
  1580. $cart[$index]["size"] = $size;
  1581. $_SESSION["cart"] = array_values($cart);
  1582. return [
  1583. "success" => true,
  1584. "status" => "replaced",
  1585. "size" => $size,
  1586. "previous_size" => $existingSize,
  1587. ];
  1588. }
  1589. $cart[] = [
  1590. "product_id" => $productId,
  1591. "size" => $size,
  1592. ];
  1593. $_SESSION["cart"] = array_values($cart);
  1594. return [
  1595. "success" => true,
  1596. "status" => "added",
  1597. "size" => $size,
  1598. ];
  1599. }
  1600. function removeCartItemByIndex($index)
  1601. {
  1602. $cart = getCart();
  1603. if (isset($cart[$index])) {
  1604. unset($cart[$index]);
  1605. $_SESSION["cart"] = array_values($cart);
  1606. }
  1607. }
  1608. function clearCart()
  1609. {
  1610. $_SESSION["cart"] = [];
  1611. }
  1612. function getCartItemsDetailed()
  1613. {
  1614. $items = [];
  1615. foreach (getCart() as $index => $cartItem) {
  1616. $product = getProductById($cartItem["product_id"]);
  1617. if ($product === null) {
  1618. continue;
  1619. }
  1620. $size = trim((string) ($cartItem["size"] ?? ""));
  1621. $items[] = [
  1622. "cart_index" => $index,
  1623. "product" => $product,
  1624. "size" => $size,
  1625. "availability_label" =>
  1626. $size !== "" ? getAvailabilityLabel($product, $size) : "",
  1627. ];
  1628. }
  1629. return $items;
  1630. }
  1631. function buildOrderItemsFromCart()
  1632. {
  1633. $items = [];
  1634. foreach (getCart() as $cartItem) {
  1635. $product = getProductById($cartItem["product_id"]);
  1636. if ($product === null) {
  1637. continue;
  1638. }
  1639. $size = trim((string) ($cartItem["size"] ?? ""));
  1640. $items[] = [
  1641. "product_id" => $product["id"],
  1642. "size" => $size,
  1643. "is_processed" => false,
  1644. ];
  1645. }
  1646. return normalizeOrderItems($items);
  1647. }
  1648. function buildOrderItemsHtml($order)
  1649. {
  1650. $parts = [];
  1651. foreach ($order["items"] as $item) {
  1652. $label = "<strong>" . escape($item["product_name"]) . "</strong>";
  1653. if ($item["size"] !== "") {
  1654. $label .= " - Größe: " . escape($item["size"]);
  1655. }
  1656. if (!empty($item["availability_label"])) {
  1657. $label .=
  1658. "<br><small>" .
  1659. nl2br(escape($item["availability_label"])) .
  1660. "</small>";
  1661. }
  1662. $parts[] =
  1663. '<li style="margin: 0 0 0.75rem 0; padding: 0.9rem 1rem; background: #f8f4e7; border: 1px solid #d7ceb5; border-radius: 18px; color: #111111;">' .
  1664. $label .
  1665. "</li>";
  1666. }
  1667. return '<ul style="list-style: none; margin: 0; padding: 0;">' .
  1668. implode("", $parts) .
  1669. "</ul>";
  1670. }
  1671. function buildOrderSummaryHtml($order, $title, $introHtml, $extraHtml = "")
  1672. {
  1673. $itemsHtml = buildOrderItemsHtml($order);
  1674. return '
  1675. <html>
  1676. <head>
  1677. <meta charset="UTF-8">
  1678. </head>
  1679. <body style="font-family: \'Freising Sans\', Arial, sans-serif; line-height: 1.6; color: #111111; background: #f4efe1; padding: 1.5rem;">
  1680. <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);">
  1681. <p style="margin: 0 0 0.5rem; font-size: 0.8rem; letter-spacing: 0.08em; text-transform: uppercase; color: #5e5a4d;">' .
  1682. escape(SITE_DEPARTMENT_NAME) .
  1683. '</p>
  1684. <h1 style="margin: 0; font-size: 1.75rem; line-height: 1.2; color: #111111;">' .
  1685. escape(SITE_NAME) .
  1686. '</h1>
  1687. <p style="margin: 0.25rem 0 1.5rem; font-size: 1rem; color: #5e5a4d;">' .
  1688. escape(SITE_SERVICE_HEADER) .
  1689. '</p>
  1690. <div style="width: 80px; height: 6px; border-radius: 999px; background: #ffd71c; margin-bottom: 1.5rem;"></div>
  1691. <h2 style="color: #111111; margin-top: 0;">' .
  1692. escape($title) .
  1693. '</h2>
  1694. ' .
  1695. $introHtml .
  1696. '
  1697. <div style="background: #f8f4e7; border: 2px solid #ffd71c; padding: 1.5rem; margin: 1.5rem 0; border-radius: 20px;">
  1698. <h3 style="margin-top: 0;">Bestellnummer</h3>
  1699. <p style="margin: 0; color: #111111; font-family: monospace; font-size: 1.05rem;">' .
  1700. escape($order["id"]) .
  1701. '</p>
  1702. </div>
  1703. <p><strong>Name:</strong> ' .
  1704. escape($order["customer_name"]) .
  1705. '</p>
  1706. <p><strong>E-Mail:</strong> ' .
  1707. escape($order["customer_email"]) .
  1708. '</p>
  1709. <p><strong>Organisation:</strong> ' .
  1710. escape($order["organization_label"]) .
  1711. '</p>
  1712. <p><strong>Erstellt am:</strong> ' .
  1713. escape(formatDate($order["created_at"])) .
  1714. '</p>
  1715. <h3>Bestellte Artikel</h3>
  1716. <div style="background: #fffdf6; border: 1px solid #d7ceb5; border-left: 6px solid #ffd71c; border-radius: 20px; padding: 1rem;">' .
  1717. $itemsHtml .
  1718. '</div>
  1719. <p><strong>Kommentar:</strong><br>' .
  1720. ($order["comment"] !== ""
  1721. ? nl2br(escape($order["comment"]))
  1722. : "Kein Kommentar") .
  1723. '</p>
  1724. ' .
  1725. $extraHtml .
  1726. '
  1727. <p style="margin: 2rem 0 0; color: #5e5a4d; font-size: 0.9rem;">' .
  1728. escape(SITE_NAME) .
  1729. " | " .
  1730. escape(SITE_DEPARTMENT_NAME) .
  1731. "<br>" .
  1732. escape(SITE_ADDRESS_LINE) .
  1733. '</p>
  1734. </div>
  1735. </body>
  1736. </html>';
  1737. }
  1738. function sendOrderConfirmationRequestEmail($order)
  1739. {
  1740. $subject = SITE_SERVICE_NAME . ": Bestellung bestätigen - " . $order["id"];
  1741. $link = buildOrderConfirmationUrl($order["confirmation_token"]);
  1742. $expiryText = formatDate($order["confirmation_expires_at"]);
  1743. $intro =
  1744. "<p>Guten Tag " .
  1745. escape($order["customer_name"]) .
  1746. ",</p><p>bitte bestätigen Sie Ihre Bestellung im " .
  1747. escape(SITE_SERVICE_NAME) .
  1748. " der Stadt Freising über den folgenden Link.</p>";
  1749. $extra =
  1750. '
  1751. <p><a href="' .
  1752. escape($link) .
  1753. '" 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>
  1754. <p>Der Link ist gültig bis: <strong>' .
  1755. escape($expiryText) .
  1756. '</strong></p>
  1757. <p>Falls der Button nicht funktioniert, verwenden Sie bitte diesen Link:<br>' .
  1758. escape($link) .
  1759. "</p>";
  1760. $message = buildOrderSummaryHtml(
  1761. $order,
  1762. "Bestellung bestätigen",
  1763. $intro,
  1764. $extra,
  1765. );
  1766. return sendEmail($order["customer_email"], $subject, $message);
  1767. }
  1768. function sendOrderCreatedCustomerEmail($order)
  1769. {
  1770. $subject = SITE_SERVICE_NAME . ": Ihre Bestellung - " . $order["id"];
  1771. $intro =
  1772. "<p>Guten Tag " .
  1773. escape($order["customer_name"]) .
  1774. ",</p><p>Ihre Bestellung wurde erfasst und an " .
  1775. escape(SITE_DEPARTMENT_NAME) .
  1776. " weitergeleitet.</p>";
  1777. $message = buildOrderSummaryHtml($order, "Bestellung eingegangen", $intro);
  1778. return sendEmail($order["customer_email"], $subject, $message);
  1779. }
  1780. function sendOrderConfirmedCustomerEmail($order)
  1781. {
  1782. $subject = SITE_SERVICE_NAME . ": Bestellung bestätigt - " . $order["id"];
  1783. $intro =
  1784. "<p>Guten Tag " .
  1785. escape($order["customer_name"]) .
  1786. ",</p><p>Ihre Bestellung wurde bestätigt und an " .
  1787. escape(SITE_DEPARTMENT_NAME) .
  1788. " weitergeleitet.</p>";
  1789. $message = buildOrderSummaryHtml($order, "Bestellung bestätigt", $intro);
  1790. return sendEmail($order["customer_email"], $subject, $message);
  1791. }
  1792. function sendConfirmedOrderAdminNotification($order)
  1793. {
  1794. $recipient = getOrderRecipientEmail();
  1795. if (!isValidAdminEmail($recipient)) {
  1796. return false;
  1797. }
  1798. $subject = SITE_SERVICE_NAME . ": Neue Bestellung - " . $order["id"];
  1799. $intro =
  1800. "<p>Eine neue PSA-Bestellung wurde freigegeben und muss bearbeitet werden.</p>";
  1801. $message = buildOrderSummaryHtml($order, "Neue PSA-Bestellung", $intro);
  1802. $attachments = [];
  1803. if (shouldAttachOrderPdfToAdminEmail()) {
  1804. $attachments[] = [
  1805. "filename" => "bestellung-" . strtolower($order["id"]) . ".pdf",
  1806. "content_type" => "application/pdf",
  1807. "content" => generateOrderPdf($order),
  1808. ];
  1809. }
  1810. return sendEmail($recipient, $subject, $message, true, $attachments);
  1811. }
  1812. function sendEmail($to, $subject, $message, $isHtml = true, $attachments = [])
  1813. {
  1814. $headers = [];
  1815. $headers[] = "From: " . FROM_NAME . " <" . FROM_EMAIL . ">";
  1816. $headers[] = "Reply-To: " . FROM_EMAIL;
  1817. $headers[] = "X-Mailer: PHP/" . phpversion();
  1818. if (empty($attachments)) {
  1819. if ($isHtml) {
  1820. $headers[] = "MIME-Version: 1.0";
  1821. $headers[] = "Content-Type: text/html; charset=UTF-8";
  1822. } else {
  1823. $headers[] = "Content-Type: text/plain; charset=UTF-8";
  1824. }
  1825. return mail($to, $subject, $message, implode("\r\n", $headers));
  1826. }
  1827. $boundary = "=_Boundary_" . bin2hex(random_bytes(8));
  1828. $headers[] = "MIME-Version: 1.0";
  1829. $headers[] = 'Content-Type: multipart/mixed; boundary="' . $boundary . '"';
  1830. $body = [];
  1831. $body[] = "--" . $boundary;
  1832. $body[] =
  1833. "Content-Type: " .
  1834. ($isHtml ? "text/html" : "text/plain") .
  1835. "; charset=UTF-8";
  1836. $body[] = "Content-Transfer-Encoding: 8bit";
  1837. $body[] = "";
  1838. $body[] = $message;
  1839. foreach ($attachments as $attachment) {
  1840. if (!is_array($attachment)) {
  1841. continue;
  1842. }
  1843. $filename = trim(
  1844. (string) ($attachment["filename"] ?? "attachment.bin"),
  1845. );
  1846. $contentType = trim(
  1847. (string) ($attachment["content_type"] ??
  1848. "application/octet-stream"),
  1849. );
  1850. $content = isset($attachment["content"])
  1851. ? (string) $attachment["content"]
  1852. : "";
  1853. $body[] = "--" . $boundary;
  1854. $body[] =
  1855. "Content-Type: " . $contentType . '; name="' . $filename . '"';
  1856. $body[] = "Content-Transfer-Encoding: base64";
  1857. $body[] =
  1858. 'Content-Disposition: attachment; filename="' . $filename . '"';
  1859. $body[] = "";
  1860. $body[] = chunk_split(base64_encode($content));
  1861. }
  1862. $body[] = "--" . $boundary . "--";
  1863. $body[] = "";
  1864. return mail(
  1865. $to,
  1866. $subject,
  1867. implode("\r\n", $body),
  1868. implode("\r\n", $headers),
  1869. );
  1870. }
  1871. function buildOrderPdfLines($order)
  1872. {
  1873. $lines = [
  1874. SITE_FULL_NAME,
  1875. SITE_DEPARTMENT_NAME,
  1876. "",
  1877. SITE_SERVICE_HEADER,
  1878. "Bestellnummer: " . $order["id"],
  1879. "Erstellt am: " . formatDate($order["created_at"]),
  1880. "Name: " . $order["customer_name"],
  1881. "E-Mail: " . $order["customer_email"],
  1882. "Organisation: " . $order["organization_label"],
  1883. "",
  1884. "Artikel:",
  1885. ];
  1886. foreach ($order["items"] as $item) {
  1887. $line = "- " . $item["product_name"];
  1888. if ($item["size"] !== "") {
  1889. $line .= " | Größe: " . $item["size"];
  1890. }
  1891. if ($item["availability_label"] !== "") {
  1892. $line .=
  1893. " | Hinweis: " .
  1894. preg_replace("/\s+/", " ", $item["availability_label"]);
  1895. }
  1896. $lines[] = $line;
  1897. }
  1898. $lines[] = "";
  1899. $lines[] = "Kommentar:";
  1900. if ($order["comment"] !== "") {
  1901. foreach (
  1902. preg_split('/\r\n|\r|\n/', $order["comment"])
  1903. as $commentLine
  1904. ) {
  1905. $lines[] = $commentLine;
  1906. }
  1907. } else {
  1908. $lines[] = "Kein Kommentar";
  1909. }
  1910. return $lines;
  1911. }
  1912. function pdfEscapeText($text)
  1913. {
  1914. $text = str_replace("\\", "\\\\", $text);
  1915. $text = str_replace("(", "\(", $text);
  1916. $text = str_replace(")", "\)", $text);
  1917. $text = str_replace("\r", "", $text);
  1918. if (function_exists("iconv")) {
  1919. $converted = @iconv("UTF-8", "Windows-1252//TRANSLIT//IGNORE", $text);
  1920. if (is_string($converted)) {
  1921. $text = $converted;
  1922. }
  1923. }
  1924. return $text;
  1925. }
  1926. function generateOrderPdf($order)
  1927. {
  1928. $lines = buildOrderPdfLines($order);
  1929. $content = "BT\n/F1 12 Tf\n14 TL\n50 790 Td\n";
  1930. $first = true;
  1931. foreach ($lines as $line) {
  1932. if (!$first) {
  1933. $content .= "T*\n";
  1934. }
  1935. $first = false;
  1936. $content .= "(" . pdfEscapeText($line) . ") Tj\n";
  1937. }
  1938. $content .= "ET";
  1939. $length = strlen($content);
  1940. $objects = [];
  1941. $objects[] = "1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n";
  1942. $objects[] = "2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n";
  1943. $objects[] =
  1944. "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";
  1945. $objects[] =
  1946. "4 0 obj\n<< /Length " .
  1947. $length .
  1948. " >>\nstream\n" .
  1949. $content .
  1950. "\nendstream\nendobj\n";
  1951. $objects[] =
  1952. "5 0 obj\n<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>\nendobj\n";
  1953. $pdf = "%PDF-1.4\n";
  1954. $offsets = [0];
  1955. foreach ($objects as $object) {
  1956. $offsets[] = strlen($pdf);
  1957. $pdf .= $object;
  1958. }
  1959. $xrefOffset = strlen($pdf);
  1960. $pdf .= "xref\n0 " . (count($objects) + 1) . "\n";
  1961. $pdf .= "0000000000 65535 f \n";
  1962. for ($i = 1; $i <= count($objects); $i++) {
  1963. $pdf .= sprintf("%010d 00000 n \n", $offsets[$i]);
  1964. }
  1965. $pdf .= "trailer\n<< /Size " . (count($objects) + 1) . " /Root 1 0 R >>\n";
  1966. $pdf .= "startxref\n" . $xrefOffset . "\n%%EOF";
  1967. return $pdf;
  1968. }
  1969. /**
  1970. * Input Validation Class
  1971. */
  1972. class Validator
  1973. {
  1974. private $errors = [];
  1975. private $data = [];
  1976. public function __construct($data)
  1977. {
  1978. $this->data = $data;
  1979. }
  1980. public function required($field, $label = null)
  1981. {
  1982. $value = $this->get($field);
  1983. if (empty(trim($value ?? ""))) {
  1984. $this->errors[] = ($label ?? $field) . " ist erforderlich.";
  1985. }
  1986. return $this;
  1987. }
  1988. public function email($field, $label = null)
  1989. {
  1990. $value = $this->get($field);
  1991. if (!empty($value) && !filter_var($value, FILTER_VALIDATE_EMAIL)) {
  1992. $this->errors[] =
  1993. ($label ?? $field) . " muss eine gültige E-Mail-Adresse sein.";
  1994. }
  1995. return $this;
  1996. }
  1997. public function minLength($field, $min, $label = null)
  1998. {
  1999. $value = $this->get($field);
  2000. if (!empty($value) && strlen($value) < $min) {
  2001. $this->errors[] =
  2002. ($label ?? $field) .
  2003. " muss mindestens " .
  2004. $min .
  2005. " Zeichen lang sein.";
  2006. }
  2007. return $this;
  2008. }
  2009. public function maxLength($field, $max, $label = null)
  2010. {
  2011. $value = $this->get($field);
  2012. if (!empty($value) && strlen($value) > $max) {
  2013. $this->errors[] =
  2014. ($label ?? $field) .
  2015. " darf maximal " .
  2016. $max .
  2017. " Zeichen lang sein.";
  2018. }
  2019. return $this;
  2020. }
  2021. public function inArray($field, $allowed, $label = null)
  2022. {
  2023. $value = $this->get($field);
  2024. if (!empty($value) && !in_array($value, $allowed, true)) {
  2025. $this->errors[] = ($label ?? $field) . " ist ungültig.";
  2026. }
  2027. return $this;
  2028. }
  2029. public function get($field)
  2030. {
  2031. return $this->data[$field] ?? null;
  2032. }
  2033. public function getErrors()
  2034. {
  2035. return $this->errors;
  2036. }
  2037. public function isValid()
  2038. {
  2039. return empty($this->errors);
  2040. }
  2041. }
  2042. /**
  2043. * Error Logging Functions
  2044. */
  2045. if (!defined("LOG_DIR")) {
  2046. define("LOG_DIR", DATA_DIR . "logs/");
  2047. }
  2048. if (!defined("ERROR_LOG_FILE")) {
  2049. define("ERROR_LOG_FILE", LOG_DIR . "error.log");
  2050. }
  2051. if (!defined("ACCESS_LOG_FILE")) {
  2052. define("ACCESS_LOG_FILE", LOG_DIR . "access.log");
  2053. }
  2054. function initLogging()
  2055. {
  2056. if (!is_dir(LOG_DIR)) {
  2057. mkdir(LOG_DIR, 02775, true);
  2058. @chmod(LOG_DIR, 02775);
  2059. }
  2060. }
  2061. function logError($message, $context = [], $level = "ERROR")
  2062. {
  2063. initLogging();
  2064. $entry = [
  2065. "timestamp" => date("Y-m-d H:i:s.u"),
  2066. "level" => $level,
  2067. "message" => $message,
  2068. "context" => $context,
  2069. "ip" => $_SERVER["REMOTE_ADDR"] ?? "unknown",
  2070. "user_agent" => $_SERVER["HTTP_USER_AGENT"] ?? "unknown",
  2071. "request_uri" => $_SERVER["REQUEST_URI"] ?? "unknown",
  2072. "session_id" => session_id()
  2073. ? substr(session_id(), 0, 8) . "..."
  2074. : "none",
  2075. ];
  2076. $logLine = json_encode($entry, JSON_UNESCAPED_UNICODE) . PHP_EOL;
  2077. file_put_contents(ERROR_LOG_FILE, $logLine, FILE_APPEND | LOCK_EX);
  2078. if (defined("DEVELOPMENT_MODE") && DEVELOPMENT_MODE) {
  2079. error_log(
  2080. "PSA Order: " . $message . " | Context: " . json_encode($context),
  2081. );
  2082. }
  2083. }
  2084. function logAccess($message, $context = [])
  2085. {
  2086. initLogging();
  2087. $entry = [
  2088. "timestamp" => date("Y-m-d H:i:s.u"),
  2089. "message" => $message,
  2090. "context" => $context,
  2091. "ip" => $_SERVER["REMOTE_ADDR"] ?? "unknown",
  2092. "request_method" => $_SERVER["REQUEST_METHOD"] ?? "unknown",
  2093. "request_uri" => $_SERVER["REQUEST_URI"] ?? "unknown",
  2094. ];
  2095. $logLine = json_encode($entry, JSON_UNESCAPED_UNICODE) . PHP_EOL;
  2096. file_put_contents(ACCESS_LOG_FILE, $logLine, FILE_APPEND | LOCK_EX);
  2097. }
  2098. function handleException($exception)
  2099. {
  2100. logError(
  2101. "Uncaught exception: " . $exception->getMessage(),
  2102. [
  2103. "file" => $exception->getFile(),
  2104. "line" => $exception->getLine(),
  2105. "trace" => $exception->getTraceAsString(),
  2106. ],
  2107. "CRITICAL",
  2108. );
  2109. if (defined("DEVELOPMENT_MODE") && DEVELOPMENT_MODE) {
  2110. echo "<h1>Error</h1><pre>" .
  2111. escape($exception->getMessage()) .
  2112. "</pre>";
  2113. } else {
  2114. echo "<h1>Es ist ein Fehler aufgetreten</h1><p>Bitte versuchen Sie es später erneut.</p>";
  2115. }
  2116. exit();
  2117. }
  2118. set_exception_handler("handleException");
  2119. function handleError($errno, $errstr, $errfile, $errline)
  2120. {
  2121. if (!(error_reporting() & $errno)) {
  2122. return false;
  2123. }
  2124. logError(
  2125. "PHP Error: " . $errstr,
  2126. [
  2127. "type" => $errno,
  2128. "file" => $errfile,
  2129. "line" => $errline,
  2130. ],
  2131. "WARNING",
  2132. );
  2133. return true;
  2134. }
  2135. set_error_handler("handleError");