functions.php 74 KB

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