functions.php 88 KB

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