functions.php 90 KB

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