functions.php 96 KB

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