functions.php 77 KB

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