functions.php 80 KB

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