functions.php 89 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495
  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. ];
  1102. }
  1103. function normalizeSystemSettings($settings)
  1104. {
  1105. $defaults = getDefaultSystemSettings();
  1106. if (!is_array($settings)) {
  1107. $settings = [];
  1108. }
  1109. $recipientEmail = normalizeAdminEmail(
  1110. $settings["order_recipient_email"] ??
  1111. $defaults["order_recipient_email"],
  1112. );
  1113. if (!isValidAdminEmail($recipientEmail)) {
  1114. $recipientEmail = $defaults["order_recipient_email"];
  1115. }
  1116. $startpageIntroText = trim(
  1117. (string) ($settings["startpage_intro_text"] ?? $defaults["startpage_intro_text"]),
  1118. );
  1119. return [
  1120. "order_recipient_email" => $recipientEmail,
  1121. "attach_order_pdf_to_admin_email" => !empty(
  1122. $settings["attach_order_pdf_to_admin_email"]
  1123. ),
  1124. "startpage_intro_text" => $startpageIntroText,
  1125. ];
  1126. }
  1127. function getSystemSettings()
  1128. {
  1129. $data = readJsonFile(SETTINGS_FILE);
  1130. return normalizeSystemSettings($data["settings"] ?? []);
  1131. }
  1132. function saveSystemSettings($settings)
  1133. {
  1134. return writeJsonFile(SETTINGS_FILE, [
  1135. "settings" => normalizeSystemSettings($settings),
  1136. ]);
  1137. }
  1138. function getOrderRecipientEmail()
  1139. {
  1140. $settings = getSystemSettings();
  1141. return $settings["order_recipient_email"];
  1142. }
  1143. function shouldAttachOrderPdfToAdminEmail()
  1144. {
  1145. $settings = getSystemSettings();
  1146. return !empty($settings["attach_order_pdf_to_admin_email"]);
  1147. }
  1148. function getStartpageIntroLines()
  1149. {
  1150. $settings = getSystemSettings();
  1151. $text = trim((string) ($settings["startpage_intro_text"] ?? ""));
  1152. if ($text === "") {
  1153. return [];
  1154. }
  1155. $lines = preg_split('/\R+/', $text) ?: [];
  1156. $lines = array_values(
  1157. array_filter(
  1158. array_map(function ($line) {
  1159. return trim((string) $line);
  1160. }, $lines),
  1161. function ($line) {
  1162. return $line !== "";
  1163. },
  1164. ),
  1165. );
  1166. return $lines;
  1167. }
  1168. function backorderStatusEmpty(): string
  1169. {
  1170. return "";
  1171. }
  1172. function backorderStatusToBeBackordered(): string
  1173. {
  1174. return "to_be_backordered";
  1175. }
  1176. function backorderStatusOrdered(): string
  1177. {
  1178. return "ordered";
  1179. }
  1180. /** Statuses persisted on order line items (load/save). */
  1181. function getBackorderStatusesForStorage(): array
  1182. {
  1183. return [
  1184. backorderStatusEmpty(),
  1185. backorderStatusToBeBackordered(),
  1186. backorderStatusOrdered(),
  1187. ];
  1188. }
  1189. /** Statuses settable from order detail (mark for external reorder). */
  1190. function getBackorderStatusesForAdminMarking(): array
  1191. {
  1192. return [backorderStatusEmpty(), backorderStatusToBeBackordered()];
  1193. }
  1194. function isValidBackorderStatusForStorage(string $status): bool
  1195. {
  1196. return in_array($status, getBackorderStatusesForStorage(), true);
  1197. }
  1198. function isValidBackorderStatusForAdminMarking(string $status): bool
  1199. {
  1200. return in_array($status, getBackorderStatusesForAdminMarking(), true);
  1201. }
  1202. function normalizeOrderItem($item)
  1203. {
  1204. if (!is_array($item)) {
  1205. return null;
  1206. }
  1207. $productId = isset($item["product_id"]) ? (int) $item["product_id"] : 0;
  1208. if ($productId <= 0) {
  1209. return null;
  1210. }
  1211. $product = getProductById($productId);
  1212. if ($product === null) {
  1213. return null;
  1214. }
  1215. $size = trim((string) ($item["size"] ?? ""));
  1216. $sizes = getProductSizes($product);
  1217. if (!empty($sizes)) {
  1218. if ($size === "" || !in_array($size, $sizes, true)) {
  1219. return null;
  1220. }
  1221. } else {
  1222. $size = "";
  1223. }
  1224. $backorderStatus = trim((string) ($item["backorder_status"] ?? ""));
  1225. if (!isValidBackorderStatusForStorage($backorderStatus)) {
  1226. $backorderStatus = backorderStatusEmpty();
  1227. }
  1228. return [
  1229. "product_id" => $productId,
  1230. "product_name" => $product["name"],
  1231. "size" => $size,
  1232. "availability_label" =>
  1233. $size !== "" ? getAvailabilityLabel($product, $size) : "",
  1234. "is_processed" => !empty($item["is_processed"]),
  1235. "backorder_status" => $backorderStatus,
  1236. "backordered_at" => trim((string) ($item["backordered_at"] ?? "")),
  1237. "ordered_at" => trim((string) ($item["ordered_at"] ?? "")),
  1238. ];
  1239. }
  1240. function normalizeOrderItems($items)
  1241. {
  1242. $normalized = [];
  1243. $seen = [];
  1244. if (!is_array($items)) {
  1245. return [];
  1246. }
  1247. foreach ($items as $item) {
  1248. $record = normalizeOrderItem($item);
  1249. if ($record === null) {
  1250. continue;
  1251. }
  1252. $key = $record["product_id"] . "|" . $record["size"];
  1253. if (isset($seen[$key])) {
  1254. continue;
  1255. }
  1256. $seen[$key] = true;
  1257. $normalized[] = $record;
  1258. }
  1259. return array_values($normalized);
  1260. }
  1261. function getOrders()
  1262. {
  1263. $data = readJsonFile(ORDERS_FILE);
  1264. $orders =
  1265. isset($data["orders"]) && is_array($data["orders"])
  1266. ? $data["orders"]
  1267. : [];
  1268. $normalized = [];
  1269. foreach ($orders as $order) {
  1270. $record = normalizeOrderRecord($order);
  1271. if ($record !== null) {
  1272. $normalized[] = $record;
  1273. }
  1274. }
  1275. return $normalized;
  1276. }
  1277. function saveOrders($orders)
  1278. {
  1279. $normalized = [];
  1280. foreach ($orders as $order) {
  1281. $record = normalizeOrderRecord($order);
  1282. if ($record !== null) {
  1283. $normalized[] = $record;
  1284. }
  1285. }
  1286. $result = writeJsonFile(ORDERS_FILE, [
  1287. "orders" => array_values($normalized),
  1288. ]);
  1289. if (!$result) {
  1290. logError("Failed to save orders", [
  1291. "file" => ORDERS_FILE,
  1292. "order_count" => count($normalized),
  1293. ]);
  1294. }
  1295. return (bool) $result;
  1296. }
  1297. function generateOrderId()
  1298. {
  1299. $orders = getOrders();
  1300. $year = date("Y");
  1301. $prefix = defined("ORDER_PREFIX") ? ORDER_PREFIX : "ORD";
  1302. $max = 0;
  1303. $pattern = "/^" . preg_quote($prefix, "/") . '-\d{4}-(\d+)$/';
  1304. foreach ($orders as $order) {
  1305. if (preg_match($pattern, (string) $order["id"], $matches) === 1) {
  1306. $number = (int) $matches[1];
  1307. if ($number > $max) {
  1308. $max = $number;
  1309. }
  1310. }
  1311. }
  1312. return sprintf("%s-%s-%03d", $prefix, $year, $max + 1);
  1313. }
  1314. function normalizeOrderRecord($order)
  1315. {
  1316. if (!is_array($order)) {
  1317. return null;
  1318. }
  1319. $id = trim((string) ($order["id"] ?? ""));
  1320. $customerName = trim((string) ($order["customer_name"] ?? ""));
  1321. $customerEmail = normalizeAdminEmail($order["customer_email"] ?? "");
  1322. $organizationId = normalizeOrganizationId($order["organization_id"] ?? "");
  1323. $organizationLabel = trim((string) ($order["organization_label"] ?? ""));
  1324. $items = normalizeOrderItems($order["items"] ?? []);
  1325. if (
  1326. $id === "" ||
  1327. $customerName === "" ||
  1328. !isValidAdminEmail($customerEmail) ||
  1329. $organizationId === "" ||
  1330. $organizationLabel === "" ||
  1331. empty($items)
  1332. ) {
  1333. return null;
  1334. }
  1335. $createdAt = trim((string) ($order["created_at"] ?? ""));
  1336. if ($createdAt === "") {
  1337. $createdAt = date("Y-m-d H:i:s");
  1338. }
  1339. $status = trim((string) ($order["status"] ?? "open"));
  1340. $allowedStatuses = ["open", "partial", "processed", "cancelled"];
  1341. if (!in_array($status, $allowedStatuses, true)) {
  1342. $status = "open";
  1343. }
  1344. $normalized = [
  1345. "id" => $id,
  1346. "customer_name" => $customerName,
  1347. "customer_email" => $customerEmail,
  1348. "organization_id" => $organizationId,
  1349. "organization_label" => $organizationLabel,
  1350. "comment" => trim((string) ($order["comment"] ?? "")),
  1351. "items" => $items,
  1352. "status" => $status,
  1353. "created_at" => $createdAt,
  1354. "updated_at" => trim((string) ($order["updated_at"] ?? $createdAt)),
  1355. "cancelled_at" => trim((string) ($order["cancelled_at"] ?? "")),
  1356. "cancelled_by" => trim((string) ($order["cancelled_by"] ?? "")),
  1357. "cancellation_reason" => trim(
  1358. (string) ($order["cancellation_reason"] ?? ""),
  1359. ),
  1360. "admin_notified_at" => trim(
  1361. (string) ($order["admin_notified_at"] ?? ""),
  1362. ),
  1363. ];
  1364. return refreshOrderState($normalized);
  1365. }
  1366. function refreshOrderState($order)
  1367. {
  1368. if (!is_array($order)) {
  1369. return null;
  1370. }
  1371. if (($order["status"] ?? "") === "cancelled") {
  1372. return $order;
  1373. }
  1374. $processedCount = 0;
  1375. foreach ($order["items"] as $item) {
  1376. if (!empty($item["is_processed"])) {
  1377. $processedCount++;
  1378. }
  1379. }
  1380. if ($processedCount <= 0) {
  1381. $order["status"] = "open";
  1382. } elseif ($processedCount >= count($order["items"])) {
  1383. $order["status"] = "processed";
  1384. } else {
  1385. $order["status"] = "partial";
  1386. }
  1387. return $order;
  1388. }
  1389. function getOrderById($orderId)
  1390. {
  1391. $orderId = trim((string) $orderId);
  1392. if ($orderId === "") {
  1393. return null;
  1394. }
  1395. foreach (getOrders() as $order) {
  1396. if ($order["id"] === $orderId) {
  1397. return $order;
  1398. }
  1399. }
  1400. return null;
  1401. }
  1402. function buildAbsoluteUrl($path)
  1403. {
  1404. $path = "/" . ltrim((string) $path, "/");
  1405. $siteUrl = defined("SITE_URL") ? trim((string) SITE_URL) : "";
  1406. if (strpos($siteUrl, "://") !== false) {
  1407. return rtrim($siteUrl, "/") . $path;
  1408. }
  1409. $basePath = trim($siteUrl);
  1410. if ($basePath !== "" && $basePath !== "/") {
  1411. $path = "/" . trim($basePath, "/") . $path;
  1412. }
  1413. $canonical = defined("SITE_CANONICAL_ORIGIN")
  1414. ? trim((string) SITE_CANONICAL_ORIGIN)
  1415. : "";
  1416. if (
  1417. $canonical !== "" &&
  1418. preg_match("#\Ahttps?://[^\s/]+#i", $canonical)
  1419. ) {
  1420. return rtrim($canonical, "/") . $path;
  1421. }
  1422. $scheme = isHttpsRequest() ? "https" : "http";
  1423. $host = $_SERVER["HTTP_HOST"] ?? "";
  1424. if ($host === "") {
  1425. return $path;
  1426. }
  1427. return $scheme . "://" . $host . $path;
  1428. }
  1429. function isHttpsRequest(): bool
  1430. {
  1431. if (
  1432. !empty($_SERVER["HTTPS"]) &&
  1433. strtolower((string) $_SERVER["HTTPS"]) !== "off"
  1434. ) {
  1435. return true;
  1436. }
  1437. if (
  1438. !empty($_SERVER["HTTP_X_FORWARDED_PROTO"]) &&
  1439. strtolower((string) $_SERVER["HTTP_X_FORWARDED_PROTO"]) === "https"
  1440. ) {
  1441. return true;
  1442. }
  1443. if (
  1444. !empty($_SERVER["SERVER_PORT"]) &&
  1445. (int) $_SERVER["SERVER_PORT"] === 443
  1446. ) {
  1447. return true;
  1448. }
  1449. return false;
  1450. }
  1451. function createOrder(
  1452. $customerName,
  1453. $customerEmail,
  1454. $organizationId,
  1455. $comment,
  1456. $items,
  1457. ) {
  1458. $customerName = sanitize($customerName);
  1459. $customerEmail = normalizeAdminEmail($customerEmail);
  1460. $organizationId = normalizeOrganizationId($organizationId);
  1461. $comment = trim((string) $comment);
  1462. $items = normalizeOrderItems($items);
  1463. if ($customerName === "") {
  1464. return [
  1465. "success" => false,
  1466. "message" => "Bitte geben Sie einen Namen ein.",
  1467. ];
  1468. }
  1469. if (!isValidAdminEmail($customerEmail)) {
  1470. return [
  1471. "success" => false,
  1472. "message" => "Bitte geben Sie eine gültige E-Mail-Adresse ein.",
  1473. ];
  1474. }
  1475. if (empty($items)) {
  1476. return [
  1477. "success" => false,
  1478. "message" =>
  1479. "Der Warenkorb ist leer oder enthält ungültige Positionen.",
  1480. ];
  1481. }
  1482. $organization = getOrganizationById($organizationId);
  1483. if ($organization === null || empty($organization["active"])) {
  1484. return [
  1485. "success" => false,
  1486. "message" => "Bitte wählen Sie eine gültige Organisation aus.",
  1487. ];
  1488. }
  1489. $now = date("Y-m-d H:i:s");
  1490. $order = [
  1491. "id" => generateOrderId(),
  1492. "customer_name" => $customerName,
  1493. "customer_email" => $customerEmail,
  1494. "organization_id" => $organization["id"],
  1495. "organization_label" => $organization["label"],
  1496. "comment" => $comment,
  1497. "items" => $items,
  1498. "status" => "open",
  1499. "created_at" => $now,
  1500. "updated_at" => $now,
  1501. "cancelled_at" => "",
  1502. "cancelled_by" => "",
  1503. "cancellation_reason" => "",
  1504. "admin_notified_at" => "",
  1505. ];
  1506. $orders = getOrders();
  1507. $orders[] = $order;
  1508. if (!saveOrders($orders)) {
  1509. return [
  1510. "success" => false,
  1511. "message" =>
  1512. "Die Bestellung konnte nicht gespeichert werden. Bitte versuchen Sie es erneut.",
  1513. ];
  1514. }
  1515. logAccess("Order created in createOrder", [
  1516. "order_id" => $order["id"],
  1517. "customer" => $customerEmail,
  1518. "organization" => $organization["label"],
  1519. ]);
  1520. $result = sendConfirmedOrderAdminNotification($order);
  1521. if ($result) {
  1522. markOrderAdminNotified($order["id"]);
  1523. $order = getOrderById($order["id"]);
  1524. }
  1525. sendOrderCreatedCustomerEmail($order);
  1526. return ["success" => true, "order" => $order];
  1527. }
  1528. function markOrderAdminNotified($orderId)
  1529. {
  1530. $orders = getOrders();
  1531. foreach ($orders as &$order) {
  1532. if ($order["id"] !== $orderId) {
  1533. continue;
  1534. }
  1535. $order["admin_notified_at"] = date("Y-m-d H:i:s");
  1536. $order["updated_at"] = date("Y-m-d H:i:s");
  1537. break;
  1538. }
  1539. unset($order);
  1540. saveOrders($orders);
  1541. }
  1542. function toggleOrderItemProcessed($orderId, $itemIndex)
  1543. {
  1544. $orders = getOrders();
  1545. $now = date("Y-m-d H:i:s");
  1546. foreach ($orders as &$order) {
  1547. if ($order["id"] !== $orderId) {
  1548. continue;
  1549. }
  1550. if ($order["status"] === "cancelled") {
  1551. return [
  1552. "success" => false,
  1553. "message" =>
  1554. "Stornierte Bestellungen können nicht mehr bearbeitet werden.",
  1555. ];
  1556. }
  1557. if (!isset($order["items"][$itemIndex])) {
  1558. return [
  1559. "success" => false,
  1560. "message" => "Position nicht gefunden.",
  1561. ];
  1562. }
  1563. $order["items"][$itemIndex]["is_processed"] = empty(
  1564. $order["items"][$itemIndex]["is_processed"]
  1565. );
  1566. $order["updated_at"] = $now;
  1567. $order = refreshOrderState($order);
  1568. saveOrders($orders);
  1569. return ["success" => true, "order" => $order];
  1570. }
  1571. unset($order);
  1572. return ["success" => false, "message" => "Bestellung nicht gefunden."];
  1573. }
  1574. function cancelOrder($orderId, $adminUsername, $reason = "")
  1575. {
  1576. $orders = getOrders();
  1577. $now = date("Y-m-d H:i:s");
  1578. $adminUsername = normalizeAdminUsername($adminUsername);
  1579. $reason = trim((string) $reason);
  1580. foreach ($orders as &$order) {
  1581. if ($order["id"] !== $orderId) {
  1582. continue;
  1583. }
  1584. if ($order["status"] === "cancelled") {
  1585. return [
  1586. "success" => false,
  1587. "message" => "Die Bestellung ist bereits storniert.",
  1588. ];
  1589. }
  1590. $order["status"] = "cancelled";
  1591. $order["cancelled_at"] = $now;
  1592. $order["cancelled_by"] = $adminUsername;
  1593. $order["cancellation_reason"] = $reason;
  1594. $order["updated_at"] = $now;
  1595. foreach ($order["items"] as &$item) {
  1596. $item["backorder_status"] = "";
  1597. $item["backordered_at"] = "";
  1598. $item["ordered_at"] = "";
  1599. }
  1600. unset($item);
  1601. saveOrders($orders);
  1602. return ["success" => true, "order" => $order];
  1603. }
  1604. unset($order);
  1605. return ["success" => false, "message" => "Bestellung nicht gefunden."];
  1606. }
  1607. function uncancelOrder($orderId)
  1608. {
  1609. $orders = getOrders();
  1610. $now = date("Y-m-d H:i:s");
  1611. foreach ($orders as &$order) {
  1612. if ($order["id"] !== $orderId) {
  1613. continue;
  1614. }
  1615. if ($order["status"] !== "cancelled") {
  1616. return [
  1617. "success" => false,
  1618. "message" => "Die Bestellung ist nicht storniert.",
  1619. ];
  1620. }
  1621. $order["cancelled_at"] = "";
  1622. $order["cancelled_by"] = "";
  1623. $order["cancellation_reason"] = "";
  1624. $order["status"] = "open";
  1625. $order["updated_at"] = $now;
  1626. $order = refreshOrderState($order);
  1627. saveOrders($orders);
  1628. return ["success" => true, "order" => $order];
  1629. }
  1630. unset($order);
  1631. return ["success" => false, "message" => "Bestellung nicht gefunden."];
  1632. }
  1633. function orderItemCanBeManaged($order)
  1634. {
  1635. if (($order["status"] ?? "") === "cancelled") {
  1636. return [
  1637. "success" => false,
  1638. "message" =>
  1639. "Stornierte Bestellungen können nicht mehr bearbeitet werden.",
  1640. ];
  1641. }
  1642. return ["success" => true];
  1643. }
  1644. function setOrderItemBackorderStatus($orderId, $itemIndex, $status)
  1645. {
  1646. if (!isValidBackorderStatusForAdminMarking($status)) {
  1647. return ["success" => false, "message" => "Ungültiger Nachbestellstatus."];
  1648. }
  1649. $orders = getOrders();
  1650. $now = date("Y-m-d H:i:s");
  1651. foreach ($orders as &$order) {
  1652. if ($order["id"] !== $orderId) {
  1653. continue;
  1654. }
  1655. $guard = orderItemCanBeManaged($order);
  1656. if (!$guard["success"]) {
  1657. return $guard;
  1658. }
  1659. if (!isset($order["items"][$itemIndex])) {
  1660. return [
  1661. "success" => false,
  1662. "message" => "Position nicht gefunden.",
  1663. ];
  1664. }
  1665. if ($status === backorderStatusToBeBackordered()) {
  1666. if (!empty($order["items"][$itemIndex]["is_processed"])) {
  1667. return [
  1668. "success" => false,
  1669. "message" =>
  1670. "Bearbeitete Positionen können nicht als Nachbestellung markiert werden.",
  1671. ];
  1672. }
  1673. $order["items"][$itemIndex]["backorder_status"] =
  1674. backorderStatusToBeBackordered();
  1675. $order["items"][$itemIndex]["backordered_at"] = $now;
  1676. $order["items"][$itemIndex]["ordered_at"] = "";
  1677. } else {
  1678. $order["items"][$itemIndex]["backorder_status"] = backorderStatusEmpty();
  1679. $order["items"][$itemIndex]["backordered_at"] = "";
  1680. $order["items"][$itemIndex]["ordered_at"] = "";
  1681. }
  1682. $order["updated_at"] = $now;
  1683. saveOrders($orders);
  1684. return ["success" => true, "order" => $order];
  1685. }
  1686. unset($order);
  1687. return ["success" => false, "message" => "Bestellung nicht gefunden."];
  1688. }
  1689. function toggleOrderItemBackorder($orderId, $itemIndex)
  1690. {
  1691. $orders = getOrders();
  1692. foreach ($orders as $order) {
  1693. if ($order["id"] !== $orderId) {
  1694. continue;
  1695. }
  1696. if (!isset($order["items"][$itemIndex])) {
  1697. return [
  1698. "success" => false,
  1699. "message" => "Position nicht gefunden.",
  1700. ];
  1701. }
  1702. $current = (string) ($order["items"][$itemIndex]["backorder_status"] ?? "");
  1703. $newStatus = $current === "to_be_backordered" ? "" : "to_be_backordered";
  1704. return setOrderItemBackorderStatus($orderId, $itemIndex, $newStatus);
  1705. }
  1706. return ["success" => false, "message" => "Bestellung nicht gefunden."];
  1707. }
  1708. function getManualBackorders()
  1709. {
  1710. $data = readJsonFile(MANUAL_BACKORDERS_FILE);
  1711. $entries =
  1712. isset($data["entries"]) && is_array($data["entries"])
  1713. ? $data["entries"]
  1714. : [];
  1715. $normalized = [];
  1716. foreach ($entries as $entry) {
  1717. if (!is_array($entry)) {
  1718. continue;
  1719. }
  1720. $id = trim((string) ($entry["id"] ?? ""));
  1721. $productId = (int) ($entry["product_id"] ?? 0);
  1722. $productName = trim((string) ($entry["product_name"] ?? ""));
  1723. $size = trim((string) ($entry["size"] ?? ""));
  1724. $status = trim((string) ($entry["backorder_status"] ?? ""));
  1725. if ($id === "" || $productId <= 0 || $productName === "" || $status === "") {
  1726. continue;
  1727. }
  1728. if (!in_array($status, ["to_be_backordered", "ordered"], true)) {
  1729. continue;
  1730. }
  1731. $normalized[] = [
  1732. "id" => $id,
  1733. "product_id" => $productId,
  1734. "product_name" => $productName,
  1735. "size" => $size,
  1736. "backorder_status" => $status,
  1737. "backordered_at" => trim((string) ($entry["backordered_at"] ?? "")),
  1738. "ordered_at" => trim((string) ($entry["ordered_at"] ?? "")),
  1739. "created_at" => trim((string) ($entry["created_at"] ?? "")),
  1740. ];
  1741. }
  1742. return $normalized;
  1743. }
  1744. function saveManualBackorders($entries)
  1745. {
  1746. return writeJsonFile(MANUAL_BACKORDERS_FILE, [
  1747. "entries" => array_values($entries),
  1748. ]);
  1749. }
  1750. function generateManualBackorderId()
  1751. {
  1752. return "mb-" . date("YmdHis") . "-" . bin2hex(random_bytes(4));
  1753. }
  1754. function addManualBackorderItems($productId, $size, $quantity)
  1755. {
  1756. $productId = (int) $productId;
  1757. $size = trim((string) $size);
  1758. $quantity = (int) $quantity;
  1759. if ($productId <= 0 || $quantity <= 0) {
  1760. return [
  1761. "success" => false,
  1762. "message" => "Ungültige Menge oder Artikel.",
  1763. ];
  1764. }
  1765. if ($quantity > 100) {
  1766. return [
  1767. "success" => false,
  1768. "message" => "Maximal 100 Positionen auf einmal.",
  1769. ];
  1770. }
  1771. $product = getProductById($productId);
  1772. if ($product === null) {
  1773. return ["success" => false, "message" => "Artikel nicht gefunden."];
  1774. }
  1775. $allowedSizes = getProductSizes($product);
  1776. if (empty($allowedSizes)) {
  1777. $allowedSizes = ["Standard"];
  1778. }
  1779. if (!in_array($size, $allowedSizes, true)) {
  1780. return ["success" => false, "message" => "Ungültige Größe für diesen Artikel."];
  1781. }
  1782. $entries = getManualBackorders();
  1783. $now = date("Y-m-d H:i:s");
  1784. for ($i = 0; $i < $quantity; $i++) {
  1785. $entries[] = [
  1786. "id" => generateManualBackorderId(),
  1787. "product_id" => $productId,
  1788. "product_name" => $product["name"],
  1789. "size" => $size,
  1790. "backorder_status" => "to_be_backordered",
  1791. "backordered_at" => $now,
  1792. "ordered_at" => "",
  1793. "created_at" => $now,
  1794. ];
  1795. }
  1796. if (!saveManualBackorders($entries)) {
  1797. return [
  1798. "success" => false,
  1799. "message" => "Nachbestellungen konnten nicht gespeichert werden.",
  1800. ];
  1801. }
  1802. return ["success" => true, "added" => $quantity];
  1803. }
  1804. function collectBackorderItemRefs()
  1805. {
  1806. $refs = [];
  1807. foreach (getManualBackorders() as $entry) {
  1808. $refs[] = [
  1809. "order_id" => "",
  1810. "item_index" => 0,
  1811. "manual_id" => $entry["id"],
  1812. "is_manual" => true,
  1813. "product_id" => $entry["product_id"],
  1814. "product_name" => $entry["product_name"],
  1815. "size" => $entry["size"],
  1816. "backorder_status" => $entry["backorder_status"],
  1817. "created_at" => $entry["created_at"] !== "" ? $entry["created_at"] : $entry["backordered_at"],
  1818. "sort_at" =>
  1819. $entry["backorder_status"] === "ordered"
  1820. ? ($entry["ordered_at"] !== ""
  1821. ? $entry["ordered_at"]
  1822. : $entry["created_at"])
  1823. : ($entry["backordered_at"] !== ""
  1824. ? $entry["backordered_at"]
  1825. : $entry["created_at"]),
  1826. ];
  1827. }
  1828. foreach (getOrders() as $order) {
  1829. if (($order["status"] ?? "") === "cancelled") {
  1830. continue;
  1831. }
  1832. foreach ($order["items"] as $itemIndex => $item) {
  1833. $status = (string) ($item["backorder_status"] ?? "");
  1834. if ($status === "") {
  1835. continue;
  1836. }
  1837. $refs[] = [
  1838. "order_id" => $order["id"],
  1839. "item_index" => (int) $itemIndex,
  1840. "product_id" => (int) $item["product_id"],
  1841. "product_name" => $item["product_name"],
  1842. "size" => $item["size"],
  1843. "backorder_status" => $status,
  1844. "created_at" => $order["created_at"],
  1845. "sort_at" =>
  1846. $status === "ordered"
  1847. ? ($item["ordered_at"] !== ""
  1848. ? $item["ordered_at"]
  1849. : $order["created_at"])
  1850. : ($item["backordered_at"] !== ""
  1851. ? $item["backordered_at"]
  1852. : $order["created_at"]),
  1853. ];
  1854. }
  1855. }
  1856. return $refs;
  1857. }
  1858. function compareBackorderRefs(array $left, array $right): int
  1859. {
  1860. $cmp = strcmp((string) ($left["sort_at"] ?? ""), (string) ($right["sort_at"] ?? ""));
  1861. if ($cmp !== 0) {
  1862. return $cmp;
  1863. }
  1864. $cmp = strcmp((string) ($left["order_id"] ?? ""), (string) ($right["order_id"] ?? ""));
  1865. if ($cmp !== 0) {
  1866. return $cmp;
  1867. }
  1868. return strcmp((string) ($left["manual_id"] ?? ""), (string) ($right["manual_id"] ?? ""));
  1869. }
  1870. function getBackorderGroups()
  1871. {
  1872. $refs = collectBackorderItemRefs();
  1873. $groups = [];
  1874. foreach ($refs as $ref) {
  1875. $key = $ref["product_id"] . "|" . $ref["size"];
  1876. if (!isset($groups[$key])) {
  1877. $groups[$key] = [
  1878. "product_id" => $ref["product_id"],
  1879. "product_name" => $ref["product_name"],
  1880. "size" => $ref["size"],
  1881. "to_be_backordered" => 0,
  1882. "ordered" => 0,
  1883. "items_to_be_backordered" => [],
  1884. "items_ordered" => [],
  1885. ];
  1886. }
  1887. if ($ref["backorder_status"] === "to_be_backordered") {
  1888. $groups[$key]["to_be_backordered"]++;
  1889. $groups[$key]["items_to_be_backordered"][] = $ref;
  1890. } elseif ($ref["backorder_status"] === "ordered") {
  1891. $groups[$key]["ordered"]++;
  1892. $groups[$key]["items_ordered"][] = $ref;
  1893. }
  1894. }
  1895. foreach ($groups as &$group) {
  1896. usort($group["items_to_be_backordered"], "compareBackorderRefs");
  1897. usort($group["items_ordered"], "compareBackorderRefs");
  1898. }
  1899. unset($group);
  1900. $result = array_values($groups);
  1901. usort($result, function ($left, $right) {
  1902. $cmp = strcmp($left["product_name"], $right["product_name"]);
  1903. if ($cmp !== 0) {
  1904. return $cmp;
  1905. }
  1906. return strcmp($left["size"], $right["size"]);
  1907. });
  1908. return $result;
  1909. }
  1910. function applyBackorderBulkUpdate($productId, $size, $fromStatus, $toStatus, $quantity)
  1911. {
  1912. $productId = (int) $productId;
  1913. $size = trim((string) $size);
  1914. $quantity = (int) $quantity;
  1915. if ($productId <= 0 || $quantity <= 0) {
  1916. return [
  1917. "success" => false,
  1918. "message" => "Ungültige Menge oder Artikel.",
  1919. ];
  1920. }
  1921. $refs = collectBackorderItemRefs();
  1922. $candidates = [];
  1923. foreach ($refs as $ref) {
  1924. if (
  1925. $ref["product_id"] !== $productId ||
  1926. $ref["size"] !== $size ||
  1927. $ref["backorder_status"] !== $fromStatus
  1928. ) {
  1929. continue;
  1930. }
  1931. $candidates[] = $ref;
  1932. }
  1933. usort($candidates, "compareBackorderRefs");
  1934. if ($quantity > count($candidates)) {
  1935. return [
  1936. "success" => false,
  1937. "message" =>
  1938. "Nur " .
  1939. count($candidates) .
  1940. " Position(en) verfügbar, " .
  1941. $quantity .
  1942. " angefordert.",
  1943. ];
  1944. }
  1945. $targets = array_slice($candidates, 0, $quantity);
  1946. $orders = getOrders();
  1947. $manualEntries = getManualBackorders();
  1948. $manualChanged = false;
  1949. $now = date("Y-m-d H:i:s");
  1950. $updated = 0;
  1951. foreach ($targets as $target) {
  1952. if (!empty($target["is_manual"])) {
  1953. $manualId = (string) ($target["manual_id"] ?? "");
  1954. foreach ($manualEntries as &$entry) {
  1955. if ($entry["id"] !== $manualId) {
  1956. continue;
  1957. }
  1958. if ($toStatus === "ordered") {
  1959. $entry["backorder_status"] = "ordered";
  1960. $entry["ordered_at"] = $now;
  1961. } else {
  1962. $entry["backorder_status"] = "";
  1963. $entry["ordered_at"] = "";
  1964. }
  1965. $manualChanged = true;
  1966. $updated++;
  1967. break;
  1968. }
  1969. unset($entry);
  1970. continue;
  1971. }
  1972. foreach ($orders as &$order) {
  1973. if ($order["id"] !== $target["order_id"]) {
  1974. continue;
  1975. }
  1976. $itemIndex = $target["item_index"];
  1977. if (!isset($order["items"][$itemIndex])) {
  1978. continue 2;
  1979. }
  1980. if ($toStatus === backorderStatusOrdered()) {
  1981. $order["items"][$itemIndex]["backorder_status"] = backorderStatusOrdered();
  1982. $order["items"][$itemIndex]["ordered_at"] = $now;
  1983. } else {
  1984. $order["items"][$itemIndex]["backorder_status"] = backorderStatusEmpty();
  1985. $order["items"][$itemIndex]["ordered_at"] = "";
  1986. }
  1987. $order["updated_at"] = $now;
  1988. $updated++;
  1989. break;
  1990. }
  1991. unset($order);
  1992. }
  1993. if ($updated === 0) {
  1994. return [
  1995. "success" => false,
  1996. "message" => "Keine Positionen aktualisiert.",
  1997. ];
  1998. }
  1999. if ($manualChanged) {
  2000. $manualEntries = array_values(
  2001. array_filter($manualEntries, function ($entry) {
  2002. return ($entry["backorder_status"] ?? "") !== "";
  2003. }),
  2004. );
  2005. if (!saveManualBackorders($manualEntries)) {
  2006. return [
  2007. "success" => false,
  2008. "message" => "Manuelle Nachbestellungen konnten nicht gespeichert werden.",
  2009. ];
  2010. }
  2011. }
  2012. saveOrders($orders);
  2013. return ["success" => true, "updated" => $updated];
  2014. }
  2015. function markBackorderItemsOrdered($productId, $size, $quantity)
  2016. {
  2017. return applyBackorderBulkUpdate(
  2018. $productId,
  2019. $size,
  2020. "to_be_backordered",
  2021. "ordered",
  2022. $quantity,
  2023. );
  2024. }
  2025. function markBackorderItemsDelivered($productId, $size, $quantity)
  2026. {
  2027. return applyBackorderBulkUpdate($productId, $size, "ordered", "", $quantity);
  2028. }
  2029. function orderHasBackorder($order)
  2030. {
  2031. if (!is_array($order["items"] ?? null)) {
  2032. return false;
  2033. }
  2034. foreach ($order["items"] as $item) {
  2035. if (($item["backorder_status"] ?? "") !== "") {
  2036. return true;
  2037. }
  2038. }
  2039. return false;
  2040. }
  2041. function getOrderOpenBackorderSummary($order)
  2042. {
  2043. $statuses = [];
  2044. if (!is_array($order["items"] ?? null)) {
  2045. return ["label" => "", "class" => ""];
  2046. }
  2047. foreach ($order["items"] as $item) {
  2048. if (!empty($item["is_processed"])) {
  2049. continue;
  2050. }
  2051. $status = trim((string) ($item["backorder_status"] ?? ""));
  2052. if ($status !== "") {
  2053. $statuses[$status] = true;
  2054. }
  2055. }
  2056. if ($statuses === []) {
  2057. return ["label" => "", "class" => ""];
  2058. }
  2059. if (count($statuses) > 1) {
  2060. return ["label" => "Gemischt", "class" => "status-backorder"];
  2061. }
  2062. $status = array_key_first($statuses);
  2063. return [
  2064. "label" => getBackorderStatusLabel($status),
  2065. "class" => getBackorderStatusClass($status),
  2066. ];
  2067. }
  2068. function getBackorderStatusLabel($status)
  2069. {
  2070. switch ((string) $status) {
  2071. case "to_be_backordered":
  2072. return "Nachzubestellen";
  2073. case "ordered":
  2074. return "Wartet auf Lieferung";
  2075. default:
  2076. return "-";
  2077. }
  2078. }
  2079. function getBackorderStatusClass($status)
  2080. {
  2081. switch ((string) $status) {
  2082. case "to_be_backordered":
  2083. return "status-backorder";
  2084. case "ordered":
  2085. return "status-backorder-waiting";
  2086. default:
  2087. return "";
  2088. }
  2089. }
  2090. function getOrderStatusLabel($order)
  2091. {
  2092. if (($order["status"] ?? "") === "cancelled") {
  2093. return "Storniert";
  2094. }
  2095. if (($order["status"] ?? "") === "processed") {
  2096. return "Bearbeitet";
  2097. }
  2098. if (($order["status"] ?? "") === "partial") {
  2099. return "Teilweise bearbeitet";
  2100. }
  2101. return "Offen";
  2102. }
  2103. function getOrderStatusClass($order)
  2104. {
  2105. if (($order["status"] ?? "") === "cancelled") {
  2106. return "status-cancelled";
  2107. }
  2108. if (($order["status"] ?? "") === "processed") {
  2109. return "status-processed";
  2110. }
  2111. if (($order["status"] ?? "") === "partial") {
  2112. return "status-partial";
  2113. }
  2114. return "status-open";
  2115. }
  2116. function formatDate($dateString)
  2117. {
  2118. $dateString = trim((string) $dateString);
  2119. if ($dateString === "") {
  2120. return "-";
  2121. }
  2122. try {
  2123. $date = new DateTimeImmutable($dateString);
  2124. return $date->format("d.m.Y H:i");
  2125. } catch (Exception $exception) {
  2126. return $dateString;
  2127. }
  2128. }
  2129. function getCart()
  2130. {
  2131. $cart = $_SESSION["cart"] ?? [];
  2132. if (!is_array($cart)) {
  2133. $cart = [];
  2134. }
  2135. $normalized = [];
  2136. foreach ($cart as $item) {
  2137. $productId = isset($item["product_id"]) ? (int) $item["product_id"] : 0;
  2138. $size = trim((string) ($item["size"] ?? ""));
  2139. $product = getProductById($productId);
  2140. if ($product === null) {
  2141. continue;
  2142. }
  2143. $sizes = getProductSizes($product);
  2144. if (!empty($sizes)) {
  2145. if ($size === "" || !in_array($size, $sizes, true)) {
  2146. continue;
  2147. }
  2148. } else {
  2149. $size = "";
  2150. }
  2151. if (isset($normalized[$productId])) {
  2152. unset($normalized[$productId]);
  2153. }
  2154. $normalized[$productId] = [
  2155. "product_id" => $productId,
  2156. "size" => $size,
  2157. ];
  2158. }
  2159. $_SESSION["cart"] = array_values($normalized);
  2160. return $_SESSION["cart"];
  2161. }
  2162. function addCartItem($productId, $size = "")
  2163. {
  2164. $productId = (int) $productId;
  2165. $size = trim((string) $size);
  2166. $product = getProductById($productId);
  2167. if ($product === null) {
  2168. return [
  2169. "success" => false,
  2170. "status" => "error",
  2171. ];
  2172. }
  2173. $sizes = getProductSizes($product);
  2174. if (!empty($sizes)) {
  2175. if ($size === "" || !in_array($size, $sizes, true)) {
  2176. return [
  2177. "success" => false,
  2178. "status" => "error",
  2179. ];
  2180. }
  2181. } else {
  2182. $size = "";
  2183. }
  2184. $cart = getCart();
  2185. foreach ($cart as $index => $item) {
  2186. if ((int) $item["product_id"] !== $productId) {
  2187. continue;
  2188. }
  2189. $existingSize = trim((string) ($item["size"] ?? ""));
  2190. if ($existingSize === $size) {
  2191. return [
  2192. "success" => true,
  2193. "status" => "unchanged",
  2194. "size" => $size,
  2195. ];
  2196. }
  2197. $cart[$index]["size"] = $size;
  2198. $_SESSION["cart"] = array_values($cart);
  2199. return [
  2200. "success" => true,
  2201. "status" => "replaced",
  2202. "size" => $size,
  2203. "previous_size" => $existingSize,
  2204. ];
  2205. }
  2206. $cart[] = [
  2207. "product_id" => $productId,
  2208. "size" => $size,
  2209. ];
  2210. $_SESSION["cart"] = array_values($cart);
  2211. return [
  2212. "success" => true,
  2213. "status" => "added",
  2214. "size" => $size,
  2215. ];
  2216. }
  2217. function removeCartItem($productId, $size)
  2218. {
  2219. $productId = (int) $productId;
  2220. $size = trim((string) $size);
  2221. $cart = getCart();
  2222. $filtered = [];
  2223. foreach ($cart as $item) {
  2224. $itemProductId = (int) ($item["product_id"] ?? 0);
  2225. $itemSize = trim((string) ($item["size"] ?? ""));
  2226. if ($itemProductId === $productId && $itemSize === $size) {
  2227. continue;
  2228. }
  2229. $filtered[] = $item;
  2230. }
  2231. $_SESSION["cart"] = array_values($filtered);
  2232. }
  2233. function clearCart()
  2234. {
  2235. $_SESSION["cart"] = [];
  2236. }
  2237. function getCartItemsDetailed()
  2238. {
  2239. $items = [];
  2240. foreach (getCart() as $cartItem) {
  2241. $product = getProductById($cartItem["product_id"]);
  2242. if ($product === null) {
  2243. continue;
  2244. }
  2245. $size = trim((string) ($cartItem["size"] ?? ""));
  2246. $items[] = [
  2247. "product" => $product,
  2248. "size" => $size,
  2249. "availability_label" =>
  2250. $size !== "" ? getAvailabilityLabel($product, $size) : "",
  2251. ];
  2252. }
  2253. return $items;
  2254. }
  2255. function buildOrderItemsFromCart()
  2256. {
  2257. $items = [];
  2258. foreach (getCart() as $cartItem) {
  2259. $product = getProductById($cartItem["product_id"]);
  2260. if ($product === null) {
  2261. continue;
  2262. }
  2263. $size = trim((string) ($cartItem["size"] ?? ""));
  2264. $items[] = [
  2265. "product_id" => $product["id"],
  2266. "size" => $size,
  2267. "is_processed" => false,
  2268. ];
  2269. }
  2270. return normalizeOrderItems($items);
  2271. }
  2272. function buildOrderItemsHtml($order)
  2273. {
  2274. $parts = [];
  2275. foreach ($order["items"] as $item) {
  2276. $label = "<strong>" . escape($item["product_name"]) . "</strong>";
  2277. if ($item["size"] !== "") {
  2278. $label .= " - Größe: " . escape($item["size"]);
  2279. }
  2280. if (!empty($item["availability_label"])) {
  2281. $label .=
  2282. "<br><small>" .
  2283. nl2br(escape($item["availability_label"])) .
  2284. "</small>";
  2285. }
  2286. $parts[] =
  2287. '<li style="margin: 0 0 0.75rem 0; padding: 0.9rem 1rem; background: #f8f4e7; border: 1px solid #d7ceb5; border-radius: 18px; color: #111111;">' .
  2288. $label .
  2289. "</li>";
  2290. }
  2291. return '<ul style="list-style: none; margin: 0; padding: 0;">' .
  2292. implode("", $parts) .
  2293. "</ul>";
  2294. }
  2295. function buildOrderSummaryHtml($order, $title, $introHtml, $extraHtml = "")
  2296. {
  2297. $itemsHtml = buildOrderItemsHtml($order);
  2298. return '
  2299. <html>
  2300. <head>
  2301. <meta charset="UTF-8">
  2302. </head>
  2303. <body style="font-family: \'Freising Sans\', Arial, sans-serif; line-height: 1.6; color: #111111; background: #f4efe1; padding: 1.5rem;">
  2304. <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);">
  2305. <p style="margin: 0 0 0.5rem; font-size: 0.8rem; letter-spacing: 0.08em; text-transform: uppercase; color: #5e5a4d;">' .
  2306. escape(SITE_DEPARTMENT_NAME) .
  2307. '</p>
  2308. <h1 style="margin: 0; font-size: 1.75rem; line-height: 1.2; color: #111111;">' .
  2309. escape(SITE_NAME) .
  2310. '</h1>
  2311. <p style="margin: 0.25rem 0 1.5rem; font-size: 1rem; color: #5e5a4d;">' .
  2312. escape(SITE_SERVICE_HEADER) .
  2313. '</p>
  2314. <div style="width: 80px; height: 6px; border-radius: 999px; background: #ffd71c; margin-bottom: 1.5rem;"></div>
  2315. <h2 style="color: #111111; margin-top: 0;">' .
  2316. escape($title) .
  2317. '</h2>
  2318. ' .
  2319. $introHtml .
  2320. '
  2321. <div style="background: #f8f4e7; border: 2px solid #ffd71c; padding: 1.5rem; margin: 1.5rem 0; border-radius: 20px;">
  2322. <h3 style="margin-top: 0;">Bestellnummer</h3>
  2323. <p style="margin: 0; color: #111111; font-family: monospace; font-size: 1.05rem;">' .
  2324. escape($order["id"]) .
  2325. '</p>
  2326. </div>
  2327. <p><strong>Name:</strong> ' .
  2328. escape($order["customer_name"]) .
  2329. '</p>
  2330. <p><strong>E-Mail:</strong> ' .
  2331. escape($order["customer_email"]) .
  2332. '</p>
  2333. <p><strong>Organisation:</strong> ' .
  2334. escape($order["organization_label"]) .
  2335. '</p>
  2336. <p><strong>Erstellt am:</strong> ' .
  2337. escape(formatDate($order["created_at"])) .
  2338. '</p>
  2339. <h3>Bestellte Artikel</h3>
  2340. <div style="background: #fffdf6; border: 1px solid #d7ceb5; border-left: 6px solid #ffd71c; border-radius: 20px; padding: 1rem;">' .
  2341. $itemsHtml .
  2342. '</div>
  2343. <p><strong>Kommentar:</strong><br>' .
  2344. ($order["comment"] !== ""
  2345. ? nl2br(escape($order["comment"]))
  2346. : "Kein Kommentar") .
  2347. '</p>
  2348. ' .
  2349. $extraHtml .
  2350. '
  2351. <p style="margin: 2rem 0 0; color: #5e5a4d; font-size: 0.9rem;">' .
  2352. escape(SITE_NAME) .
  2353. " | " .
  2354. escape(SITE_DEPARTMENT_NAME) .
  2355. "<br>" .
  2356. escape(SITE_ADDRESS_LINE) .
  2357. '</p>
  2358. </div>
  2359. </body>
  2360. </html>';
  2361. }
  2362. function sendOrderCreatedCustomerEmail($order)
  2363. {
  2364. $subject = SITE_SERVICE_NAME . ": Ihre Bestellung - " . $order["id"];
  2365. $intro =
  2366. "<p>Guten Tag " .
  2367. escape($order["customer_name"]) .
  2368. ",</p><p>Ihre Bestellung wurde erfasst und an " .
  2369. escape(SITE_DEPARTMENT_NAME) .
  2370. " weitergeleitet.</p>";
  2371. $message = buildOrderSummaryHtml($order, "Bestellung eingegangen", $intro);
  2372. return sendEmail($order["customer_email"], $subject, $message);
  2373. }
  2374. function sendConfirmedOrderAdminNotification($order)
  2375. {
  2376. $recipient = getOrderRecipientEmail();
  2377. if (!isValidAdminEmail($recipient)) {
  2378. return false;
  2379. }
  2380. $subject = SITE_SERVICE_NAME . ": Neue Bestellung - " . $order["id"];
  2381. $intro =
  2382. "<p>Eine neue PSA-Bestellung ist eingegangen und muss bearbeitet werden.</p>";
  2383. $message = buildOrderSummaryHtml($order, "Neue PSA-Bestellung", $intro);
  2384. $attachments = [];
  2385. if (shouldAttachOrderPdfToAdminEmail()) {
  2386. $attachments[] = [
  2387. "filename" => "bestellung-" . strtolower($order["id"]) . ".pdf",
  2388. "content_type" => "application/pdf",
  2389. "content" => renderOrderPdf($order),
  2390. ];
  2391. }
  2392. return sendEmail($recipient, $subject, $message, true, $attachments);
  2393. }
  2394. function sendEmail($to, $subject, $message, $isHtml = true, $attachments = [])
  2395. {
  2396. $headers = [];
  2397. $headers[] = "From: " . FROM_NAME . " <" . FROM_EMAIL . ">";
  2398. $headers[] = "Reply-To: " . FROM_EMAIL;
  2399. $headers[] = "X-Mailer: PHP/" . phpversion();
  2400. if (empty($attachments)) {
  2401. if ($isHtml) {
  2402. $headers[] = "MIME-Version: 1.0";
  2403. $headers[] = "Content-Type: text/html; charset=UTF-8";
  2404. } else {
  2405. $headers[] = "Content-Type: text/plain; charset=UTF-8";
  2406. }
  2407. return mail($to, $subject, $message, implode("\r\n", $headers));
  2408. }
  2409. $boundary = "=_Boundary_" . bin2hex(random_bytes(8));
  2410. $headers[] = "MIME-Version: 1.0";
  2411. $headers[] = 'Content-Type: multipart/mixed; boundary="' . $boundary . '"';
  2412. $body = [];
  2413. $body[] = "--" . $boundary;
  2414. $body[] =
  2415. "Content-Type: " .
  2416. ($isHtml ? "text/html" : "text/plain") .
  2417. "; charset=UTF-8";
  2418. $body[] = "Content-Transfer-Encoding: 8bit";
  2419. $body[] = "";
  2420. $body[] = $message;
  2421. foreach ($attachments as $attachment) {
  2422. if (!is_array($attachment)) {
  2423. continue;
  2424. }
  2425. $filename = trim(
  2426. (string) ($attachment["filename"] ?? "attachment.bin"),
  2427. );
  2428. $contentType = trim(
  2429. (string) ($attachment["content_type"] ??
  2430. "application/octet-stream"),
  2431. );
  2432. $content = isset($attachment["content"])
  2433. ? (string) $attachment["content"]
  2434. : "";
  2435. $body[] = "--" . $boundary;
  2436. $body[] =
  2437. "Content-Type: " . $contentType . '; name="' . $filename . '"';
  2438. $body[] = "Content-Transfer-Encoding: base64";
  2439. $body[] =
  2440. 'Content-Disposition: attachment; filename="' . $filename . '"';
  2441. $body[] = "";
  2442. $body[] = chunk_split(base64_encode($content));
  2443. }
  2444. $body[] = "--" . $boundary . "--";
  2445. $body[] = "";
  2446. return mail(
  2447. $to,
  2448. $subject,
  2449. implode("\r\n", $body),
  2450. implode("\r\n", $headers),
  2451. );
  2452. }
  2453. function pdfEncodeWinAnsi($text)
  2454. {
  2455. $text = str_replace("\r", "", (string) $text);
  2456. if (!function_exists("iconv")) {
  2457. return preg_replace('/[^\x09\x0A\x20-\x7E]/', "?", $text);
  2458. }
  2459. $chars = preg_split("//u", $text, -1, PREG_SPLIT_NO_EMPTY);
  2460. if (!is_array($chars)) {
  2461. $fallback = @iconv("UTF-8", "Windows-1252//TRANSLIT//IGNORE", $text);
  2462. return is_string($fallback) ? $fallback : $text;
  2463. }
  2464. $result = "";
  2465. foreach ($chars as $char) {
  2466. $converted = @iconv("UTF-8", "Windows-1252", $char);
  2467. if ($converted !== false) {
  2468. $result .= $converted;
  2469. continue;
  2470. }
  2471. $fallback = @iconv("UTF-8", "Windows-1252//TRANSLIT", $char);
  2472. if ($fallback !== false && $fallback !== "") {
  2473. $result .= $fallback;
  2474. continue;
  2475. }
  2476. $result .= "?";
  2477. }
  2478. return $result;
  2479. }
  2480. function pdfEscapeText($text)
  2481. {
  2482. $text = str_replace("\\", "\\\\", $text);
  2483. $text = str_replace("(", "\(", $text);
  2484. $text = str_replace(")", "\)", $text);
  2485. return preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', "", $text);
  2486. }
  2487. function pdfWrapAnsiText($text, $maxChars)
  2488. {
  2489. $lines = [];
  2490. $paragraphs = explode("\n", str_replace("\r", "", (string) $text));
  2491. foreach ($paragraphs as $paragraph) {
  2492. $normalized = trim(preg_replace("/\s+/", " ", $paragraph));
  2493. if ($normalized === "") {
  2494. $lines[] = "";
  2495. continue;
  2496. }
  2497. $words = explode(" ", $normalized);
  2498. $current = "";
  2499. foreach ($words as $word) {
  2500. if ($word === "") {
  2501. continue;
  2502. }
  2503. if (strlen($word) > $maxChars) {
  2504. if ($current !== "") {
  2505. $lines[] = $current;
  2506. $current = "";
  2507. }
  2508. $parts = str_split($word, $maxChars);
  2509. $lastIndex = count($parts) - 1;
  2510. for ($i = 0; $i < $lastIndex; $i++) {
  2511. $lines[] = $parts[$i];
  2512. }
  2513. $current = $parts[$lastIndex];
  2514. continue;
  2515. }
  2516. $candidate = $current === "" ? $word : $current . " " . $word;
  2517. if (strlen($candidate) <= $maxChars) {
  2518. $current = $candidate;
  2519. } else {
  2520. if ($current !== "") {
  2521. $lines[] = $current;
  2522. }
  2523. $current = $word;
  2524. }
  2525. }
  2526. if ($current !== "") {
  2527. $lines[] = $current;
  2528. }
  2529. }
  2530. if (empty($lines)) {
  2531. $lines[] = "";
  2532. }
  2533. return $lines;
  2534. }
  2535. function prepareOrderForDocument(array $order): array
  2536. {
  2537. $items = [];
  2538. foreach ($order["items"] ?? [] as $item) {
  2539. if (!is_array($item)) {
  2540. continue;
  2541. }
  2542. $items[] = [
  2543. "product_name" => trim((string) ($item["product_name"] ?? "")),
  2544. "size" => trim((string) ($item["size"] ?? "")),
  2545. "availability_label" => trim(
  2546. (string) ($item["availability_label"] ?? ""),
  2547. ),
  2548. ];
  2549. }
  2550. return [
  2551. "id" => trim((string) ($order["id"] ?? "")),
  2552. "created_at" => trim((string) ($order["created_at"] ?? "")),
  2553. "customer_name" => trim((string) ($order["customer_name"] ?? "")),
  2554. "customer_email" => trim((string) ($order["customer_email"] ?? "")),
  2555. "organization_label" => trim(
  2556. (string) ($order["organization_label"] ?? ""),
  2557. ),
  2558. "comment" => (string) ($order["comment"] ?? ""),
  2559. "items" => $items,
  2560. ];
  2561. }
  2562. function renderOrderPdf(array $order): string
  2563. {
  2564. return generateOrderPdf(prepareOrderForDocument($order));
  2565. }
  2566. function streamOrderPdf(
  2567. array $order,
  2568. string $filename,
  2569. bool $inline = true,
  2570. ): void {
  2571. $pdf = renderOrderPdf($order);
  2572. $safeFilename = preg_replace('/[^A-Za-z0-9._-]+/', "-", $filename) ?: "bestellung.pdf";
  2573. $disposition = $inline ? "inline" : "attachment";
  2574. header("Content-Type: application/pdf");
  2575. header(
  2576. 'Content-Disposition: ' .
  2577. $disposition .
  2578. '; filename="' .
  2579. $safeFilename .
  2580. '"',
  2581. );
  2582. header("Content-Length: " . strlen($pdf));
  2583. echo $pdf;
  2584. exit();
  2585. }
  2586. function generateOrderPdf($order)
  2587. {
  2588. $pageWidth = 595;
  2589. $pageHeight = 842;
  2590. $leftMargin = 45;
  2591. $topY = 800;
  2592. $bottomY = 60;
  2593. $lineHeight = 14;
  2594. $itemLineHeight = 16;
  2595. $pages = [];
  2596. $pageContent = "";
  2597. $y = $topY;
  2598. $pageNumber = 0;
  2599. $encodeText = function ($text) {
  2600. return pdfEncodeWinAnsi((string) $text);
  2601. };
  2602. $orderId = $encodeText($order["id"]);
  2603. $createdAt = $encodeText(formatDate($order["created_at"]));
  2604. $customerName = $encodeText($order["customer_name"]);
  2605. $customerEmail = $encodeText($order["customer_email"]);
  2606. $organization = $encodeText($order["organization_label"]);
  2607. $commentRaw = (string) $order["comment"];
  2608. $writeText = function ($x, $y, $encodedText, $fontSize = 12) use (&$pageContent) {
  2609. $pageContent .=
  2610. "BT\n/F1 " .
  2611. $fontSize .
  2612. " Tf\n1 0 0 1 " .
  2613. number_format($x, 2, ".", "") .
  2614. " " .
  2615. number_format($y, 2, ".", "") .
  2616. " Tm\n(" .
  2617. pdfEscapeText($encodedText) .
  2618. ") Tj\nET\n";
  2619. };
  2620. $startPage = function () use (
  2621. &$pages,
  2622. &$pageContent,
  2623. &$y,
  2624. &$pageNumber,
  2625. $topY,
  2626. $leftMargin,
  2627. $lineHeight,
  2628. $orderId,
  2629. $createdAt,
  2630. $writeText,
  2631. $encodeText
  2632. ) {
  2633. if ($pageContent !== "") {
  2634. $pages[] = $pageContent;
  2635. }
  2636. $pageNumber++;
  2637. $pageContent = "";
  2638. $y = $topY;
  2639. $headerLine = "Bestellung: " . $orderId;
  2640. if ($pageNumber > 1) {
  2641. $headerLine .= " | Seite " . $encodeText((string) $pageNumber);
  2642. }
  2643. $writeText($leftMargin, $y, $headerLine, 14);
  2644. $y -= 19;
  2645. $writeText($leftMargin, $y, "Erstellt am: " . $createdAt, 11);
  2646. $y -= 20;
  2647. };
  2648. $ensureSpace = function ($requiredHeight) use (&$y, $bottomY, $startPage) {
  2649. if ($y - $requiredHeight < $bottomY) {
  2650. $startPage();
  2651. }
  2652. };
  2653. $writeWrapped = function (
  2654. $encodedText,
  2655. $maxChars,
  2656. $fontSize = 11,
  2657. $x = null,
  2658. $spacing = null
  2659. ) use (&$y, $lineHeight, $leftMargin, $writeText, $ensureSpace) {
  2660. $targetX = $x === null ? $leftMargin : $x;
  2661. $step = $spacing === null ? $lineHeight : $spacing;
  2662. $lines = pdfWrapAnsiText($encodedText, $maxChars);
  2663. foreach ($lines as $line) {
  2664. $ensureSpace($step);
  2665. $writeText($targetX, $y, $line, $fontSize);
  2666. $y -= $step;
  2667. }
  2668. };
  2669. $writeSectionTitle = function ($titleText, $fontSize = 13) use (
  2670. &$y,
  2671. $leftMargin,
  2672. $writeText,
  2673. $ensureSpace,
  2674. $encodeText
  2675. ) {
  2676. $ensureSpace(24);
  2677. $writeText($leftMargin, $y, $encodeText($titleText), $fontSize);
  2678. $y -= 18;
  2679. };
  2680. $startPage();
  2681. $writeSectionTitle("Gehört zu");
  2682. $writeWrapped("Name: " . $customerName, 80);
  2683. $writeWrapped("Organisation: " . $organization, 80);
  2684. $writeWrapped("E-Mail: " . $customerEmail, 80);
  2685. $y -= 6;
  2686. $writeSectionTitle("Artikelliste", 15);
  2687. $itemNumber = 1;
  2688. if (empty($order["items"])) {
  2689. $writeWrapped($encodeText("Keine Artikel"), 80, 12);
  2690. } else {
  2691. foreach ($order["items"] as $item) {
  2692. $itemName = $encodeText($item["product_name"]);
  2693. $sizeLabel = $encodeText($item["size"]);
  2694. $hintLabel = $encodeText(
  2695. preg_replace("/\s+/", " ", (string) $item["availability_label"]),
  2696. );
  2697. $writeWrapped(
  2698. $encodeText($itemNumber . ". ") . $itemName,
  2699. 68,
  2700. 14,
  2701. null,
  2702. $itemLineHeight,
  2703. );
  2704. if ($sizeLabel !== "") {
  2705. $writeWrapped(
  2706. $encodeText(" Größe: ") . $sizeLabel,
  2707. 66,
  2708. 12,
  2709. null,
  2710. $itemLineHeight,
  2711. );
  2712. }
  2713. if ($hintLabel !== "") {
  2714. $writeWrapped(
  2715. $encodeText(" Hinweis: ") . $hintLabel,
  2716. 66,
  2717. 12,
  2718. null,
  2719. $itemLineHeight,
  2720. );
  2721. }
  2722. $ensureSpace(40);
  2723. $y -= 40;
  2724. $itemNumber++;
  2725. }
  2726. }
  2727. $y -= 4;
  2728. $writeSectionTitle("Kommentar");
  2729. if (trim($commentRaw) === "") {
  2730. $writeWrapped($encodeText("Kein Kommentar"), 80);
  2731. } else {
  2732. foreach (preg_split('/\r\n|\r|\n/', $commentRaw) as $commentLine) {
  2733. $writeWrapped($encodeText($commentLine), 82);
  2734. }
  2735. }
  2736. $y -= 6;
  2737. $writeSectionTitle("Lagerbearbeitung");
  2738. $warehouseLines = [
  2739. "Ausgegeben am / durch: __________________________________________________",
  2740. "[ ] Vollständig ausgegeben",
  2741. "[ ] Teilweise ausgegeben",
  2742. ];
  2743. foreach ($warehouseLines as $line) {
  2744. $writeWrapped($encodeText($line), 80);
  2745. }
  2746. if ($pageContent !== "") {
  2747. $pages[] = $pageContent;
  2748. }
  2749. if (empty($pages)) {
  2750. $pages[] = "";
  2751. }
  2752. $fontObjectNumber = 3;
  2753. $objects = [];
  2754. $objects[1] = "1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n";
  2755. $objects[
  2756. $fontObjectNumber
  2757. ] = "3 0 obj\n<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>\nendobj\n";
  2758. $kids = [];
  2759. $nextObjectNumber = 4;
  2760. foreach ($pages as $pageStream) {
  2761. $pageObjectNumber = $nextObjectNumber++;
  2762. $contentObjectNumber = $nextObjectNumber++;
  2763. $kids[] = $pageObjectNumber . " 0 R";
  2764. $objects[$pageObjectNumber] =
  2765. $pageObjectNumber .
  2766. " 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 " .
  2767. $pageWidth .
  2768. " " .
  2769. $pageHeight .
  2770. "] /Contents " .
  2771. $contentObjectNumber .
  2772. " 0 R /Resources << /Font << /F1 " .
  2773. $fontObjectNumber .
  2774. " 0 R >> >> >>\nendobj\n";
  2775. $objects[$contentObjectNumber] =
  2776. $contentObjectNumber .
  2777. " 0 obj\n<< /Length " .
  2778. strlen($pageStream) .
  2779. " >>\nstream\n" .
  2780. $pageStream .
  2781. "\nendstream\nendobj\n";
  2782. }
  2783. $objects[2] =
  2784. "2 0 obj\n<< /Type /Pages /Kids [" .
  2785. implode(" ", $kids) .
  2786. "] /Count " .
  2787. count($kids) .
  2788. " >>\nendobj\n";
  2789. ksort($objects);
  2790. $pdf = "%PDF-1.4\n";
  2791. $offsets = [0];
  2792. foreach ($objects as $number => $objectContent) {
  2793. $offsets[$number] = strlen($pdf);
  2794. $pdf .= $objectContent;
  2795. }
  2796. $lastObjectNumber = (int) max(array_keys($objects));
  2797. $xrefOffset = strlen($pdf);
  2798. $pdf .= "xref\n0 " . ($lastObjectNumber + 1) . "\n";
  2799. $pdf .= "0000000000 65535 f \n";
  2800. for ($i = 1; $i <= $lastObjectNumber; $i++) {
  2801. if (isset($offsets[$i])) {
  2802. $pdf .= sprintf("%010d 00000 n \n", $offsets[$i]);
  2803. } else {
  2804. $pdf .= "0000000000 00000 f \n";
  2805. }
  2806. }
  2807. $pdf .= "trailer\n<< /Size " . ($lastObjectNumber + 1) . " /Root 1 0 R >>\n";
  2808. $pdf .= "startxref\n" . $xrefOffset . "\n%%EOF";
  2809. return $pdf;
  2810. }
  2811. /**
  2812. * Input Validation Class
  2813. */
  2814. class Validator
  2815. {
  2816. private $errors = [];
  2817. private $data = [];
  2818. public function __construct($data)
  2819. {
  2820. $this->data = $data;
  2821. }
  2822. public function required($field, $label = null)
  2823. {
  2824. $value = $this->get($field);
  2825. if (empty(trim($value ?? ""))) {
  2826. $this->errors[] = ($label ?? $field) . " ist erforderlich.";
  2827. }
  2828. return $this;
  2829. }
  2830. public function email($field, $label = null)
  2831. {
  2832. $value = $this->get($field);
  2833. if (!empty($value) && !filter_var($value, FILTER_VALIDATE_EMAIL)) {
  2834. $this->errors[] =
  2835. ($label ?? $field) . " muss eine gültige E-Mail-Adresse sein.";
  2836. }
  2837. return $this;
  2838. }
  2839. public function minLength($field, $min, $label = null)
  2840. {
  2841. $value = $this->get($field);
  2842. if (!empty($value) && strlen($value) < $min) {
  2843. $this->errors[] =
  2844. ($label ?? $field) .
  2845. " muss mindestens " .
  2846. $min .
  2847. " Zeichen lang sein.";
  2848. }
  2849. return $this;
  2850. }
  2851. public function maxLength($field, $max, $label = null)
  2852. {
  2853. $value = $this->get($field);
  2854. if (!empty($value) && strlen($value) > $max) {
  2855. $this->errors[] =
  2856. ($label ?? $field) .
  2857. " darf maximal " .
  2858. $max .
  2859. " Zeichen lang sein.";
  2860. }
  2861. return $this;
  2862. }
  2863. public function inArray($field, $allowed, $label = null)
  2864. {
  2865. $value = $this->get($field);
  2866. if (!empty($value) && !in_array($value, $allowed, true)) {
  2867. $this->errors[] = ($label ?? $field) . " ist ungültig.";
  2868. }
  2869. return $this;
  2870. }
  2871. public function get($field)
  2872. {
  2873. return $this->data[$field] ?? null;
  2874. }
  2875. public function addError(string $message): self
  2876. {
  2877. $message = trim($message);
  2878. if ($message !== "") {
  2879. $this->errors[] = $message;
  2880. }
  2881. return $this;
  2882. }
  2883. public function getErrors()
  2884. {
  2885. return $this->errors;
  2886. }
  2887. public function isValid()
  2888. {
  2889. return empty($this->errors);
  2890. }
  2891. }
  2892. /**
  2893. * Error Logging Functions
  2894. */
  2895. if (!defined("LOG_DIR")) {
  2896. define("LOG_DIR", DATA_DIR . "logs/");
  2897. }
  2898. if (!defined("ERROR_LOG_FILE")) {
  2899. define("ERROR_LOG_FILE", LOG_DIR . "error.log");
  2900. }
  2901. if (!defined("ACCESS_LOG_FILE")) {
  2902. define("ACCESS_LOG_FILE", LOG_DIR . "access.log");
  2903. }
  2904. function initLogging()
  2905. {
  2906. if (!is_dir(LOG_DIR)) {
  2907. mkdir(LOG_DIR, 02775, true);
  2908. @chmod(LOG_DIR, 02775);
  2909. }
  2910. }
  2911. function logError($message, $context = [], $level = "ERROR")
  2912. {
  2913. initLogging();
  2914. $entry = [
  2915. "timestamp" => date("Y-m-d H:i:s.u"),
  2916. "level" => $level,
  2917. "message" => $message,
  2918. "context" => $context,
  2919. "ip" => $_SERVER["REMOTE_ADDR"] ?? "unknown",
  2920. "user_agent" => $_SERVER["HTTP_USER_AGENT"] ?? "unknown",
  2921. "request_uri" => $_SERVER["REQUEST_URI"] ?? "unknown",
  2922. "session_id" => session_id()
  2923. ? substr(session_id(), 0, 8) . "..."
  2924. : "none",
  2925. ];
  2926. $logLine = json_encode($entry, JSON_UNESCAPED_UNICODE) . PHP_EOL;
  2927. file_put_contents(ERROR_LOG_FILE, $logLine, FILE_APPEND | LOCK_EX);
  2928. if (defined("DEVELOPMENT_MODE") && DEVELOPMENT_MODE) {
  2929. error_log(
  2930. "PSA Order: " . $message . " | Context: " . json_encode($context),
  2931. );
  2932. }
  2933. }
  2934. function logAccess($message, $context = [])
  2935. {
  2936. initLogging();
  2937. $entry = [
  2938. "timestamp" => date("Y-m-d H:i:s.u"),
  2939. "message" => $message,
  2940. "context" => $context,
  2941. "ip" => $_SERVER["REMOTE_ADDR"] ?? "unknown",
  2942. "request_method" => $_SERVER["REQUEST_METHOD"] ?? "unknown",
  2943. "request_uri" => $_SERVER["REQUEST_URI"] ?? "unknown",
  2944. ];
  2945. $logLine = json_encode($entry, JSON_UNESCAPED_UNICODE) . PHP_EOL;
  2946. file_put_contents(ACCESS_LOG_FILE, $logLine, FILE_APPEND | LOCK_EX);
  2947. }
  2948. function handleException($exception)
  2949. {
  2950. logError(
  2951. "Uncaught exception: " . $exception->getMessage(),
  2952. [
  2953. "file" => $exception->getFile(),
  2954. "line" => $exception->getLine(),
  2955. "trace" => $exception->getTraceAsString(),
  2956. ],
  2957. "CRITICAL",
  2958. );
  2959. if (defined("DEVELOPMENT_MODE") && DEVELOPMENT_MODE) {
  2960. echo "<h1>Error</h1><pre>" .
  2961. escape($exception->getMessage()) .
  2962. "</pre>";
  2963. } else {
  2964. echo "<h1>Es ist ein Fehler aufgetreten</h1><p>Bitte versuchen Sie es später erneut.</p>";
  2965. }
  2966. exit();
  2967. }
  2968. set_exception_handler("handleException");
  2969. function handleError($errno, $errstr, $errfile, $errline)
  2970. {
  2971. if (!(error_reporting() & $errno)) {
  2972. return false;
  2973. }
  2974. logError(
  2975. "PHP Error: " . $errstr,
  2976. [
  2977. "type" => $errno,
  2978. "file" => $errfile,
  2979. "line" => $errline,
  2980. ],
  2981. "WARNING",
  2982. );
  2983. return true;
  2984. }
  2985. set_error_handler("handleError");