functions.php 62 KB

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