functions.php 82 KB

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