functions.php 80 KB

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