functions.php 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681
  1. <?php
  2. require_once __DIR__ . '/../config.php';
  3. function readJsonFile($file) {
  4. if (!file_exists($file)) {
  5. return [];
  6. }
  7. $content = file_get_contents($file);
  8. if ($content === false || trim($content) === '') {
  9. return [];
  10. }
  11. $data = json_decode($content, true);
  12. return is_array($data) ? $data : [];
  13. }
  14. function writeJsonFile($file, $data) {
  15. $dir = dirname($file);
  16. if (!is_dir($dir)) {
  17. mkdir($dir, 0755, true);
  18. }
  19. file_put_contents($file, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
  20. }
  21. function sanitize($input) {
  22. return trim(strip_tags((string) $input));
  23. }
  24. function escape($value) {
  25. return htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8');
  26. }
  27. function normalizeAdminUsername($username) {
  28. return trim((string) $username);
  29. }
  30. function normalizeAdminDescription($description) {
  31. return trim((string) $description);
  32. }
  33. function normalizeAdminEmail($email) {
  34. return strtolower(trim((string) $email));
  35. }
  36. function isValidAdminUsername($username) {
  37. $username = normalizeAdminUsername($username);
  38. return preg_match('/^[A-Za-z0-9][A-Za-z0-9._-]{2,49}$/', $username) === 1;
  39. }
  40. function isValidAdminDescription($description) {
  41. $description = normalizeAdminDescription($description);
  42. if ($description === '') {
  43. return false;
  44. }
  45. $length = function_exists('mb_strlen') ? mb_strlen($description) : strlen($description);
  46. return $length <= 120;
  47. }
  48. function isValidAdminEmail($email) {
  49. $email = normalizeAdminEmail($email);
  50. return $email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
  51. }
  52. function getDefaultAdminDescription($username) {
  53. return 'Admin';
  54. }
  55. function getDefaultAdminEmail() {
  56. $email = defined('ADMIN_EMAIL') ? normalizeAdminEmail(ADMIN_EMAIL) : '';
  57. return isValidAdminEmail($email) ? $email : '';
  58. }
  59. function getAdminAccounts() {
  60. $data = readJsonFile(ADMINS_FILE);
  61. $records = isset($data['admins']) && is_array($data['admins']) ? $data['admins'] : [];
  62. $accounts = [];
  63. foreach ($records as $username => $record) {
  64. $username = normalizeAdminUsername($username);
  65. if ($username === '') {
  66. continue;
  67. }
  68. if (is_string($record)) {
  69. $record = [
  70. 'password_hash' => $record,
  71. 'description' => getDefaultAdminDescription($username),
  72. 'email' => getDefaultAdminEmail(),
  73. ];
  74. }
  75. if (!is_array($record)) {
  76. continue;
  77. }
  78. $hash = isset($record['password_hash']) ? (string) $record['password_hash'] : '';
  79. if ($hash === '') {
  80. continue;
  81. }
  82. $description = normalizeAdminDescription($record['description'] ?? getDefaultAdminDescription($username));
  83. if (!isValidAdminDescription($description)) {
  84. $description = getDefaultAdminDescription($username);
  85. }
  86. $email = normalizeAdminEmail($record['email'] ?? getDefaultAdminEmail());
  87. if (!isValidAdminEmail($email)) {
  88. $email = getDefaultAdminEmail();
  89. }
  90. $accounts[$username] = [
  91. 'password_hash' => $hash,
  92. 'description' => $description,
  93. 'email' => $email,
  94. ];
  95. }
  96. ksort($accounts);
  97. return $accounts;
  98. }
  99. function getAdminUsers() {
  100. $users = [];
  101. foreach (getAdminAccounts() as $username => $record) {
  102. $users[$username] = $record['password_hash'];
  103. }
  104. return $users;
  105. }
  106. function saveAdminAccounts($accounts) {
  107. $result = [];
  108. foreach ($accounts as $username => $record) {
  109. $username = normalizeAdminUsername($username);
  110. if ($username === '' || !is_array($record)) {
  111. continue;
  112. }
  113. $hash = isset($record['password_hash']) ? (string) $record['password_hash'] : '';
  114. if ($hash === '') {
  115. continue;
  116. }
  117. $description = normalizeAdminDescription($record['description'] ?? getDefaultAdminDescription($username));
  118. if (!isValidAdminDescription($description)) {
  119. $description = getDefaultAdminDescription($username);
  120. }
  121. $email = normalizeAdminEmail($record['email'] ?? getDefaultAdminEmail());
  122. if (!isValidAdminEmail($email)) {
  123. $email = getDefaultAdminEmail();
  124. }
  125. $result[$username] = [
  126. 'password_hash' => $hash,
  127. 'description' => $description,
  128. 'email' => $email,
  129. ];
  130. }
  131. ksort($result);
  132. writeJsonFile(ADMINS_FILE, ['admins' => $result]);
  133. }
  134. function getDefaultCategories() {
  135. return [
  136. ['id' => 'apparel', 'label' => 'Bekleidung'],
  137. ];
  138. }
  139. function normalizeCategoryId($id) {
  140. $id = trim((string) $id);
  141. if ($id === '') {
  142. return '';
  143. }
  144. if (function_exists('iconv')) {
  145. $converted = @iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $id);
  146. if (is_string($converted) && $converted !== '') {
  147. $id = $converted;
  148. }
  149. }
  150. $id = strtolower($id);
  151. $id = preg_replace('/[^a-z0-9]+/', '-', $id);
  152. return trim((string) $id, '-');
  153. }
  154. function normalizeCategoryLabel($label) {
  155. return trim((string) $label);
  156. }
  157. function isValidCategoryLabel($label) {
  158. $label = normalizeCategoryLabel($label);
  159. if ($label === '') {
  160. return false;
  161. }
  162. $length = function_exists('mb_strlen') ? mb_strlen($label) : strlen($label);
  163. return $length <= 80;
  164. }
  165. function normalizeCategories($categories) {
  166. $normalized = [];
  167. if (!is_array($categories)) {
  168. $categories = [];
  169. }
  170. foreach ($categories as $category) {
  171. if (!is_array($category)) {
  172. continue;
  173. }
  174. $id = normalizeCategoryId($category['id'] ?? '');
  175. $label = normalizeCategoryLabel($category['label'] ?? '');
  176. if ($id === '' || !isValidCategoryLabel($label)) {
  177. continue;
  178. }
  179. $normalized[$id] = [
  180. 'id' => $id,
  181. 'label' => $label,
  182. ];
  183. }
  184. if (empty($normalized)) {
  185. foreach (getDefaultCategories() as $category) {
  186. $normalized[$category['id']] = $category;
  187. }
  188. }
  189. uasort($normalized, function ($left, $right) {
  190. return strcasecmp($left['label'], $right['label']);
  191. });
  192. return array_values($normalized);
  193. }
  194. function getCategories() {
  195. $data = readJsonFile(CATEGORIES_FILE);
  196. return normalizeCategories($data['categories'] ?? []);
  197. }
  198. function saveCategories($categories) {
  199. writeJsonFile(CATEGORIES_FILE, ['categories' => normalizeCategories($categories)]);
  200. }
  201. function getCategoryById($categoryId) {
  202. $categoryId = normalizeCategoryId($categoryId);
  203. foreach (getCategories() as $category) {
  204. if ($category['id'] === $categoryId) {
  205. return $category;
  206. }
  207. }
  208. return null;
  209. }
  210. function getCategoryLabel($categoryId) {
  211. $category = getCategoryById($categoryId);
  212. if ($category !== null) {
  213. return $category['label'];
  214. }
  215. return trim((string) $categoryId);
  216. }
  217. function getCategoryLabels($categoryIds) {
  218. $labels = [];
  219. foreach (normalizeProductCategoryIds($categoryIds) as $categoryId) {
  220. $labels[] = getCategoryLabel($categoryId);
  221. }
  222. return $labels;
  223. }
  224. function generateCategoryIdFromLabel($label, $existingCategories = []) {
  225. $baseId = normalizeCategoryId($label);
  226. if ($baseId === '') {
  227. $baseId = 'category';
  228. }
  229. $used = [];
  230. foreach (normalizeCategories($existingCategories) as $category) {
  231. $used[$category['id']] = true;
  232. }
  233. $candidate = $baseId;
  234. $counter = 2;
  235. while (isset($used[$candidate])) {
  236. $candidate = $baseId . '-' . $counter;
  237. $counter++;
  238. }
  239. return $candidate;
  240. }
  241. function isCategoryInUse($categoryId) {
  242. foreach (getProducts() as $product) {
  243. if (productHasCategory($product, $categoryId)) {
  244. return true;
  245. }
  246. }
  247. return false;
  248. }
  249. function normalizeProductCategoryIds($categoryValue) {
  250. if (is_array($categoryValue)) {
  251. $rawIds = $categoryValue;
  252. } elseif ($categoryValue === null || $categoryValue === '') {
  253. $rawIds = [];
  254. } else {
  255. $rawIds = [$categoryValue];
  256. }
  257. $normalized = [];
  258. foreach ($rawIds as $categoryId) {
  259. $categoryId = normalizeCategoryId($categoryId);
  260. if ($categoryId !== '') {
  261. $normalized[$categoryId] = $categoryId;
  262. }
  263. }
  264. return array_values($normalized);
  265. }
  266. function getProductCategoryIds($product) {
  267. if (isset($product['categories'])) {
  268. return normalizeProductCategoryIds($product['categories']);
  269. }
  270. return normalizeProductCategoryIds($product['category'] ?? []);
  271. }
  272. function productHasCategory($product, $categoryId) {
  273. $categoryId = normalizeCategoryId($categoryId);
  274. if ($categoryId === '') {
  275. return false;
  276. }
  277. return in_array($categoryId, getProductCategoryIds($product), true);
  278. }
  279. function getProductSizes($product) {
  280. if (isset($product['sizes']) && is_array($product['sizes'])) {
  281. $sizes = $product['sizes'];
  282. } elseif (isset($product['sizes']) && is_string($product['sizes'])) {
  283. $sizes = explode(',', $product['sizes']);
  284. } else {
  285. $sizes = [];
  286. }
  287. $normalized = [];
  288. foreach ($sizes as $size) {
  289. $size = trim((string) $size);
  290. if ($size !== '') {
  291. $normalized[$size] = $size;
  292. }
  293. }
  294. return array_values($normalized);
  295. }
  296. function productUsesSizeStock($product) {
  297. return !empty(getProductSizes($product));
  298. }
  299. function normalizeAvailabilityLabels($sizes, $labels) {
  300. $result = [];
  301. if (!is_array($labels)) {
  302. $labels = [];
  303. }
  304. foreach ($sizes as $size) {
  305. $text = trim((string) ($labels[$size] ?? ''));
  306. $result[$size] = $text;
  307. }
  308. return $result;
  309. }
  310. function getAvailabilityLabel($product, $size) {
  311. $labels = isset($product['availability_labels']) && is_array($product['availability_labels'])
  312. ? $product['availability_labels']
  313. : [];
  314. return trim((string) ($labels[$size] ?? ''));
  315. }
  316. function normalizeProductRecord($product, $defaultCategoryId = '') {
  317. if (!is_array($product)) {
  318. return null;
  319. }
  320. $productId = isset($product['id']) ? (int) $product['id'] : 0;
  321. $name = trim((string) ($product['name'] ?? ''));
  322. if ($productId <= 0 || $name === '') {
  323. return null;
  324. }
  325. $sizes = getProductSizes($product);
  326. if (empty($sizes)) {
  327. $sizes = ['Standard'];
  328. }
  329. $categories = getProductCategoryIds($product);
  330. if (empty($categories) && $defaultCategoryId !== '') {
  331. $categories = [$defaultCategoryId];
  332. }
  333. $availabilityLabels = normalizeAvailabilityLabels(
  334. $sizes,
  335. isset($product['availability_labels']) && is_array($product['availability_labels'])
  336. ? $product['availability_labels']
  337. : []
  338. );
  339. return [
  340. 'id' => $productId,
  341. 'name' => $name,
  342. 'description' => trim((string) ($product['description'] ?? '')),
  343. 'image' => trim((string) ($product['image'] ?? '')),
  344. 'categories' => $categories,
  345. 'sizes' => implode(',', $sizes),
  346. 'availability_labels' => $availabilityLabels,
  347. ];
  348. }
  349. function getProducts() {
  350. $data = readJsonFile(PRODUCTS_FILE);
  351. $rawProducts = isset($data['products']) && is_array($data['products']) ? $data['products'] : [];
  352. $categories = getCategories();
  353. $defaultCategoryId = !empty($categories) ? $categories[0]['id'] : 'apparel';
  354. $products = [];
  355. foreach ($rawProducts as $product) {
  356. $normalized = normalizeProductRecord($product, $defaultCategoryId);
  357. if ($normalized !== null) {
  358. $products[] = $normalized;
  359. }
  360. }
  361. usort($products, function ($left, $right) {
  362. return strcasecmp($left['name'], $right['name']);
  363. });
  364. return $products;
  365. }
  366. function getProductById($id) {
  367. $id = (int) $id;
  368. foreach (getProducts() as $product) {
  369. if ((int) $product['id'] === $id) {
  370. return $product;
  371. }
  372. }
  373. return null;
  374. }
  375. function saveProducts($products) {
  376. $categories = getCategories();
  377. $defaultCategoryId = !empty($categories) ? $categories[0]['id'] : 'apparel';
  378. $normalized = [];
  379. foreach ($products as $product) {
  380. $record = normalizeProductRecord($product, $defaultCategoryId);
  381. if ($record !== null) {
  382. $normalized[] = $record;
  383. }
  384. }
  385. writeJsonFile(PRODUCTS_FILE, ['products' => array_values($normalized)]);
  386. }
  387. function getFaqFilePath(): string {
  388. $dataDir = defined('DATA_DIR') ? DATA_DIR : dirname(__DIR__) . '/data/';
  389. $defaultPath = rtrim($dataDir, '/\\') . '/faq.json';
  390. if (!defined('FAQ_FILE') || !is_string(FAQ_FILE) || FAQ_FILE === '') {
  391. return $defaultPath;
  392. }
  393. $configuredPath = FAQ_FILE;
  394. $normalizedDataDir = str_replace('\\', '/', rtrim($dataDir, '/\\')) . '/';
  395. $normalizedConfigured = str_replace('\\', '/', $configuredPath);
  396. if (strpos($normalizedConfigured, $normalizedDataDir) !== 0) {
  397. return $defaultPath;
  398. }
  399. return $configuredPath;
  400. }
  401. function getFaqContent(): string {
  402. $defaultContent = "# FAQ\n\nHier kann der FAQ-Inhalt im Admin-Bereich bearbeitet werden.";
  403. $data = readJsonFile(getFaqFilePath());
  404. if (!isset($data['content']) || !is_string($data['content'])) {
  405. return $defaultContent;
  406. }
  407. return $data['content'];
  408. }
  409. function saveFaqContent(string $markdown): void {
  410. writeJsonFile(getFaqFilePath(), ['content' => (string) $markdown]);
  411. }
  412. function renderFaqInlineMarkdown(string $text): string {
  413. $escaped = escape($text);
  414. $escaped = preg_replace('/\*\*(.+?)\*\*/s', '<strong>$1</strong>', $escaped);
  415. $escaped = preg_replace('/(?<!\*)\*(?!\s)(.+?)(?<!\s)\*(?!\*)/s', '<em>$1</em>', $escaped);
  416. return $escaped;
  417. }
  418. function renderFaqMarkdown(string $markdown): string {
  419. $normalized = str_replace(["\r\n", "\r"], "\n", $markdown);
  420. $lines = explode("\n", $normalized);
  421. $htmlParts = [];
  422. $paragraphLines = [];
  423. $listType = '';
  424. $flushParagraph = function () use (&$paragraphLines, &$htmlParts): void {
  425. if (empty($paragraphLines)) {
  426. return;
  427. }
  428. $rendered = [];
  429. foreach ($paragraphLines as $line) {
  430. $rendered[] = renderFaqInlineMarkdown($line);
  431. }
  432. $htmlParts[] = '<p>' . implode("<br>\n", $rendered) . '</p>';
  433. $paragraphLines = [];
  434. };
  435. $closeList = function () use (&$listType, &$htmlParts): void {
  436. if ($listType !== '') {
  437. $htmlParts[] = '</' . $listType . '>';
  438. $listType = '';
  439. }
  440. };
  441. foreach ($lines as $line) {
  442. $line = rtrim($line);
  443. $trimmed = trim($line);
  444. if ($trimmed === '') {
  445. $flushParagraph();
  446. $closeList();
  447. continue;
  448. }
  449. if (preg_match('/^(#{1,3})\s+(.+)$/', $trimmed, $matches) === 1) {
  450. $flushParagraph();
  451. $closeList();
  452. $level = strlen($matches[1]);
  453. $htmlParts[] = '<h' . $level . '>' . renderFaqInlineMarkdown($matches[2]) . '</h' . $level . '>';
  454. continue;
  455. }
  456. if (preg_match('/^\s*[-*]\s+(.+)$/', $line, $matches) === 1) {
  457. $flushParagraph();
  458. if ($listType !== 'ul') {
  459. $closeList();
  460. $listType = 'ul';
  461. $htmlParts[] = '<ul>';
  462. }
  463. $htmlParts[] = '<li>' . renderFaqInlineMarkdown($matches[1]) . '</li>';
  464. continue;
  465. }
  466. if (preg_match('/^\s*\d+\.\s+(.+)$/', $line, $matches) === 1) {
  467. $flushParagraph();
  468. if ($listType !== 'ol') {
  469. $closeList();
  470. $listType = 'ol';
  471. $htmlParts[] = '<ol>';
  472. }
  473. $htmlParts[] = '<li>' . renderFaqInlineMarkdown($matches[1]) . '</li>';
  474. continue;
  475. }
  476. $closeList();
  477. $paragraphLines[] = $trimmed;
  478. }
  479. $flushParagraph();
  480. $closeList();
  481. return empty($htmlParts) ? '<p>Keine FAQ-Inhalte vorhanden.</p>' : implode("\n", $htmlParts);
  482. }
  483. function getDefaultOrganizations() {
  484. return [
  485. [
  486. 'id' => 'feuerwehr-freising',
  487. 'label' => 'Feuerwehr Freising',
  488. 'sort_order' => 10,
  489. 'active' => true,
  490. ],
  491. ];
  492. }
  493. function normalizeOrganizationId($id) {
  494. return normalizeCategoryId($id);
  495. }
  496. function normalizeOrganizationLabel($label) {
  497. return trim((string) $label);
  498. }
  499. function isValidOrganizationLabel($label) {
  500. $label = normalizeOrganizationLabel($label);
  501. if ($label === '') {
  502. return false;
  503. }
  504. $length = function_exists('mb_strlen') ? mb_strlen($label) : strlen($label);
  505. return $length <= 120;
  506. }
  507. function normalizeOrganizations($organizations) {
  508. $normalized = [];
  509. if (!is_array($organizations)) {
  510. $organizations = [];
  511. }
  512. foreach ($organizations as $organization) {
  513. if (!is_array($organization)) {
  514. continue;
  515. }
  516. $id = normalizeOrganizationId($organization['id'] ?? '');
  517. $label = normalizeOrganizationLabel($organization['label'] ?? '');
  518. if ($id === '' || !isValidOrganizationLabel($label)) {
  519. continue;
  520. }
  521. $sortOrder = isset($organization['sort_order']) ? (int) $organization['sort_order'] : 0;
  522. $active = !isset($organization['active']) || (bool) $organization['active'];
  523. $normalized[$id] = [
  524. 'id' => $id,
  525. 'label' => $label,
  526. 'sort_order' => $sortOrder,
  527. 'active' => $active,
  528. ];
  529. }
  530. if (empty($normalized)) {
  531. foreach (getDefaultOrganizations() as $organization) {
  532. $normalized[$organization['id']] = $organization;
  533. }
  534. }
  535. uasort($normalized, function ($left, $right) {
  536. if ($left['sort_order'] === $right['sort_order']) {
  537. return strcasecmp($left['label'], $right['label']);
  538. }
  539. return $left['sort_order'] <=> $right['sort_order'];
  540. });
  541. return array_values($normalized);
  542. }
  543. function getOrganizations($onlyActive = false) {
  544. $data = readJsonFile(ORGANIZATIONS_FILE);
  545. $organizations = normalizeOrganizations($data['organizations'] ?? []);
  546. if ($onlyActive) {
  547. $organizations = array_values(array_filter($organizations, function ($organization) {
  548. return !empty($organization['active']);
  549. }));
  550. }
  551. return $organizations;
  552. }
  553. function saveOrganizations($organizations) {
  554. writeJsonFile(ORGANIZATIONS_FILE, ['organizations' => normalizeOrganizations($organizations)]);
  555. }
  556. function getOrganizationById($organizationId) {
  557. $organizationId = normalizeOrganizationId($organizationId);
  558. foreach (getOrganizations(false) as $organization) {
  559. if ($organization['id'] === $organizationId) {
  560. return $organization;
  561. }
  562. }
  563. return null;
  564. }
  565. function generateOrganizationIdFromLabel($label, $existingOrganizations = []) {
  566. $baseId = normalizeOrganizationId($label);
  567. if ($baseId === '') {
  568. $baseId = 'organization';
  569. }
  570. $used = [];
  571. foreach (normalizeOrganizations($existingOrganizations) as $organization) {
  572. $used[$organization['id']] = true;
  573. }
  574. $candidate = $baseId;
  575. $counter = 2;
  576. while (isset($used[$candidate])) {
  577. $candidate = $baseId . '-' . $counter;
  578. $counter++;
  579. }
  580. return $candidate;
  581. }
  582. function getDefaultSystemSettings() {
  583. return [
  584. 'order_recipient_email' => defined('ORDER_RECIPIENT_EMAIL') ? ORDER_RECIPIENT_EMAIL : getDefaultAdminEmail(),
  585. 'order_confirmation_required' => defined('ORDER_CONFIRMATION_REQUIRED') ? (bool) ORDER_CONFIRMATION_REQUIRED : false,
  586. 'order_confirmation_expiry_days' => defined('ORDER_CONFIRMATION_EXPIRY_DAYS') ? (int) ORDER_CONFIRMATION_EXPIRY_DAYS : 7,
  587. 'attach_order_pdf_to_admin_email' => defined('ATTACH_ORDER_PDF_TO_ADMIN_EMAIL') ? (bool) ATTACH_ORDER_PDF_TO_ADMIN_EMAIL : true,
  588. ];
  589. }
  590. function normalizeSystemSettings($settings) {
  591. $defaults = getDefaultSystemSettings();
  592. if (!is_array($settings)) {
  593. $settings = [];
  594. }
  595. $recipientEmail = normalizeAdminEmail($settings['order_recipient_email'] ?? $defaults['order_recipient_email']);
  596. if (!isValidAdminEmail($recipientEmail)) {
  597. $recipientEmail = $defaults['order_recipient_email'];
  598. }
  599. $expiryDays = isset($settings['order_confirmation_expiry_days']) ? (int) $settings['order_confirmation_expiry_days'] : $defaults['order_confirmation_expiry_days'];
  600. if ($expiryDays < 1) {
  601. $expiryDays = 7;
  602. }
  603. return [
  604. 'order_recipient_email' => $recipientEmail,
  605. 'order_confirmation_required' => !empty($settings['order_confirmation_required']),
  606. 'order_confirmation_expiry_days' => $expiryDays,
  607. 'attach_order_pdf_to_admin_email' => !empty($settings['attach_order_pdf_to_admin_email']),
  608. ];
  609. }
  610. function getSystemSettings() {
  611. $data = readJsonFile(SETTINGS_FILE);
  612. return normalizeSystemSettings($data['settings'] ?? []);
  613. }
  614. function saveSystemSettings($settings) {
  615. writeJsonFile(SETTINGS_FILE, ['settings' => normalizeSystemSettings($settings)]);
  616. }
  617. function getOrderRecipientEmail() {
  618. $settings = getSystemSettings();
  619. return $settings['order_recipient_email'];
  620. }
  621. function isOrderConfirmationRequired() {
  622. $settings = getSystemSettings();
  623. return !empty($settings['order_confirmation_required']);
  624. }
  625. function getOrderConfirmationExpiryDays() {
  626. $settings = getSystemSettings();
  627. return max(1, (int) $settings['order_confirmation_expiry_days']);
  628. }
  629. function shouldAttachOrderPdfToAdminEmail() {
  630. $settings = getSystemSettings();
  631. return !empty($settings['attach_order_pdf_to_admin_email']);
  632. }
  633. function normalizeOrderItem($item) {
  634. if (!is_array($item)) {
  635. return null;
  636. }
  637. $productId = isset($item['product_id']) ? (int) $item['product_id'] : 0;
  638. if ($productId <= 0) {
  639. return null;
  640. }
  641. $product = getProductById($productId);
  642. if ($product === null) {
  643. return null;
  644. }
  645. $size = trim((string) ($item['size'] ?? ''));
  646. $sizes = getProductSizes($product);
  647. if (!empty($sizes)) {
  648. if ($size === '' || !in_array($size, $sizes, true)) {
  649. return null;
  650. }
  651. } else {
  652. $size = '';
  653. }
  654. return [
  655. 'product_id' => $productId,
  656. 'product_name' => $product['name'],
  657. 'size' => $size,
  658. 'availability_label' => $size !== '' ? getAvailabilityLabel($product, $size) : '',
  659. 'is_processed' => !empty($item['is_processed']),
  660. ];
  661. }
  662. function normalizeOrderItems($items) {
  663. $normalized = [];
  664. $seen = [];
  665. if (!is_array($items)) {
  666. return [];
  667. }
  668. foreach ($items as $item) {
  669. $record = normalizeOrderItem($item);
  670. if ($record === null) {
  671. continue;
  672. }
  673. $key = $record['product_id'] . '|' . $record['size'];
  674. if (isset($seen[$key])) {
  675. continue;
  676. }
  677. $seen[$key] = true;
  678. $normalized[] = $record;
  679. }
  680. return array_values($normalized);
  681. }
  682. function getOrders() {
  683. $data = readJsonFile(ORDERS_FILE);
  684. $orders = isset($data['orders']) && is_array($data['orders']) ? $data['orders'] : [];
  685. $normalized = [];
  686. foreach ($orders as $order) {
  687. $record = normalizeOrderRecord($order);
  688. if ($record !== null) {
  689. $normalized[] = $record;
  690. }
  691. }
  692. return $normalized;
  693. }
  694. function saveOrders($orders) {
  695. $normalized = [];
  696. foreach ($orders as $order) {
  697. $record = normalizeOrderRecord($order);
  698. if ($record !== null) {
  699. $normalized[] = $record;
  700. }
  701. }
  702. writeJsonFile(ORDERS_FILE, ['orders' => array_values($normalized)]);
  703. }
  704. function generateOrderId() {
  705. $orders = getOrders();
  706. $year = date('Y');
  707. $prefix = defined('ORDER_PREFIX') ? ORDER_PREFIX : 'ORD';
  708. $max = 0;
  709. $pattern = '/^' . preg_quote($prefix, '/') . '-\d{4}-(\d+)$/';
  710. foreach ($orders as $order) {
  711. if (preg_match($pattern, (string) $order['id'], $matches) === 1) {
  712. $number = (int) $matches[1];
  713. if ($number > $max) {
  714. $max = $number;
  715. }
  716. }
  717. }
  718. return sprintf('%s-%s-%03d', $prefix, $year, $max + 1);
  719. }
  720. function normalizeOrderRecord($order) {
  721. if (!is_array($order)) {
  722. return null;
  723. }
  724. $id = trim((string) ($order['id'] ?? ''));
  725. $customerName = trim((string) ($order['customer_name'] ?? ''));
  726. $customerEmail = normalizeAdminEmail($order['customer_email'] ?? '');
  727. $organizationId = normalizeOrganizationId($order['organization_id'] ?? '');
  728. $organizationLabel = trim((string) ($order['organization_label'] ?? ''));
  729. $items = normalizeOrderItems($order['items'] ?? []);
  730. if ($id === '' || $customerName === '' || !isValidAdminEmail($customerEmail) || $organizationId === '' || $organizationLabel === '' || empty($items)) {
  731. return null;
  732. }
  733. $createdAt = trim((string) ($order['created_at'] ?? ''));
  734. if ($createdAt === '') {
  735. $createdAt = date('Y-m-d H:i:s');
  736. }
  737. $confirmationStatus = trim((string) ($order['confirmation_status'] ?? 'confirmed'));
  738. $allowedConfirmationStatuses = ['not_required', 'pending', 'confirmed', 'expired'];
  739. if (!in_array($confirmationStatus, $allowedConfirmationStatuses, true)) {
  740. $confirmationStatus = 'confirmed';
  741. }
  742. $status = trim((string) ($order['status'] ?? 'open'));
  743. $allowedStatuses = ['open', 'partial', 'processed', 'cancelled'];
  744. if (!in_array($status, $allowedStatuses, true)) {
  745. $status = 'open';
  746. }
  747. $normalized = [
  748. 'id' => $id,
  749. 'customer_name' => $customerName,
  750. 'customer_email' => $customerEmail,
  751. 'organization_id' => $organizationId,
  752. 'organization_label' => $organizationLabel,
  753. 'comment' => trim((string) ($order['comment'] ?? '')),
  754. 'items' => $items,
  755. 'status' => $status,
  756. 'confirmation_status' => $confirmationStatus,
  757. 'confirmation_token' => trim((string) ($order['confirmation_token'] ?? '')),
  758. 'confirmation_expires_at' => trim((string) ($order['confirmation_expires_at'] ?? '')),
  759. 'confirmed_at' => trim((string) ($order['confirmed_at'] ?? '')),
  760. 'created_at' => $createdAt,
  761. 'updated_at' => trim((string) ($order['updated_at'] ?? $createdAt)),
  762. 'cancelled_at' => trim((string) ($order['cancelled_at'] ?? '')),
  763. 'cancelled_by' => trim((string) ($order['cancelled_by'] ?? '')),
  764. 'cancellation_reason' => trim((string) ($order['cancellation_reason'] ?? '')),
  765. 'admin_notified_at' => trim((string) ($order['admin_notified_at'] ?? '')),
  766. ];
  767. return refreshOrderState($normalized);
  768. }
  769. function refreshOrderState($order) {
  770. if (!is_array($order)) {
  771. return null;
  772. }
  773. if (($order['status'] ?? '') === 'cancelled') {
  774. return $order;
  775. }
  776. if (($order['confirmation_status'] ?? '') === 'pending' && !empty($order['confirmation_expires_at'])) {
  777. $expiresAt = strtotime((string) $order['confirmation_expires_at']);
  778. if ($expiresAt !== false && time() > $expiresAt) {
  779. $order['confirmation_status'] = 'expired';
  780. }
  781. }
  782. $processedCount = 0;
  783. foreach ($order['items'] as $item) {
  784. if (!empty($item['is_processed'])) {
  785. $processedCount++;
  786. }
  787. }
  788. if ($processedCount <= 0) {
  789. $order['status'] = 'open';
  790. } elseif ($processedCount >= count($order['items'])) {
  791. $order['status'] = 'processed';
  792. } else {
  793. $order['status'] = 'partial';
  794. }
  795. return $order;
  796. }
  797. function expirePendingOrders() {
  798. $orders = getOrders();
  799. $changed = false;
  800. foreach ($orders as &$order) {
  801. $updated = refreshOrderState($order);
  802. if ($updated !== $order) {
  803. $order = $updated;
  804. $changed = true;
  805. }
  806. }
  807. unset($order);
  808. if ($changed) {
  809. saveOrders($orders);
  810. }
  811. }
  812. function getOrderById($orderId) {
  813. $orderId = trim((string) $orderId);
  814. if ($orderId === '') {
  815. return null;
  816. }
  817. foreach (getOrders() as $order) {
  818. if ($order['id'] === $orderId) {
  819. return $order;
  820. }
  821. }
  822. return null;
  823. }
  824. function findOrderByConfirmationToken($token) {
  825. $token = trim((string) $token);
  826. if ($token === '') {
  827. return null;
  828. }
  829. foreach (getOrders() as $order) {
  830. if (($order['confirmation_token'] ?? '') === $token) {
  831. return $order;
  832. }
  833. }
  834. return null;
  835. }
  836. function buildOrderConfirmationUrl($token) {
  837. $path = '/order-confirm.php?token=' . urlencode($token);
  838. return buildAbsoluteUrl($path);
  839. }
  840. function buildAbsoluteUrl($path) {
  841. $path = '/' . ltrim((string) $path, '/');
  842. $siteUrl = defined('SITE_URL') ? trim((string) SITE_URL) : '';
  843. if (strpos($siteUrl, '://') !== false) {
  844. return rtrim($siteUrl, '/') . $path;
  845. }
  846. $basePath = trim($siteUrl);
  847. if ($basePath !== '' && $basePath !== '/') {
  848. $path = '/' . trim($basePath, '/') . $path;
  849. }
  850. $scheme = isHttpsRequest() ? 'https' : 'http';
  851. $host = $_SERVER['HTTP_HOST'] ?? '';
  852. if ($host === '') {
  853. return $path;
  854. }
  855. return $scheme . '://' . $host . $path;
  856. }
  857. function isHttpsRequest(): bool {
  858. if (!empty($_SERVER['HTTPS']) && strtolower((string) $_SERVER['HTTPS']) !== 'off') {
  859. return true;
  860. }
  861. if (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && strtolower((string) $_SERVER['HTTP_X_FORWARDED_PROTO']) === 'https') {
  862. return true;
  863. }
  864. if (!empty($_SERVER['SERVER_PORT']) && (int) $_SERVER['SERVER_PORT'] === 443) {
  865. return true;
  866. }
  867. return false;
  868. }
  869. function createOrder($customerName, $customerEmail, $organizationId, $comment, $items) {
  870. $customerName = sanitize($customerName);
  871. $customerEmail = normalizeAdminEmail($customerEmail);
  872. $organizationId = normalizeOrganizationId($organizationId);
  873. $comment = trim((string) $comment);
  874. $items = normalizeOrderItems($items);
  875. if ($customerName === '') {
  876. return ['success' => false, 'message' => 'Bitte geben Sie einen Namen ein.'];
  877. }
  878. if (!isValidAdminEmail($customerEmail)) {
  879. return ['success' => false, 'message' => 'Bitte geben Sie eine gültige E-Mail-Adresse ein.'];
  880. }
  881. if (empty($items)) {
  882. return ['success' => false, 'message' => 'Der Warenkorb ist leer oder enthält ungültige Positionen.'];
  883. }
  884. $organization = getOrganizationById($organizationId);
  885. if ($organization === null || empty($organization['active'])) {
  886. return ['success' => false, 'message' => 'Bitte wählen Sie eine gültige Organisation aus.'];
  887. }
  888. $now = date('Y-m-d H:i:s');
  889. $requiresConfirmation = isOrderConfirmationRequired();
  890. $confirmationToken = $requiresConfirmation ? bin2hex(random_bytes(24)) : '';
  891. $confirmationExpiresAt = '';
  892. if ($requiresConfirmation) {
  893. $expires = new DateTimeImmutable();
  894. $expires = $expires->modify('+' . getOrderConfirmationExpiryDays() . ' days');
  895. $confirmationExpiresAt = $expires->format('Y-m-d H:i:s');
  896. }
  897. $order = [
  898. 'id' => generateOrderId(),
  899. 'customer_name' => $customerName,
  900. 'customer_email' => $customerEmail,
  901. 'organization_id' => $organization['id'],
  902. 'organization_label' => $organization['label'],
  903. 'comment' => $comment,
  904. 'items' => $items,
  905. 'status' => 'open',
  906. 'confirmation_status' => $requiresConfirmation ? 'pending' : 'not_required',
  907. 'confirmation_token' => $confirmationToken,
  908. 'confirmation_expires_at' => $confirmationExpiresAt,
  909. 'confirmed_at' => $requiresConfirmation ? '' : $now,
  910. 'created_at' => $now,
  911. 'updated_at' => $now,
  912. 'cancelled_at' => '',
  913. 'cancelled_by' => '',
  914. 'cancellation_reason' => '',
  915. 'admin_notified_at' => '',
  916. ];
  917. $orders = getOrders();
  918. $orders[] = $order;
  919. saveOrders($orders);
  920. if ($requiresConfirmation) {
  921. sendOrderConfirmationRequestEmail($order);
  922. } else {
  923. $result = sendConfirmedOrderAdminNotification($order);
  924. if ($result) {
  925. markOrderAdminNotified($order['id']);
  926. $order = getOrderById($order['id']);
  927. }
  928. sendOrderCreatedCustomerEmail($order);
  929. }
  930. return ['success' => true, 'order' => $order];
  931. }
  932. function markOrderAdminNotified($orderId) {
  933. $orders = getOrders();
  934. foreach ($orders as &$order) {
  935. if ($order['id'] !== $orderId) {
  936. continue;
  937. }
  938. $order['admin_notified_at'] = date('Y-m-d H:i:s');
  939. $order['updated_at'] = date('Y-m-d H:i:s');
  940. break;
  941. }
  942. unset($order);
  943. saveOrders($orders);
  944. }
  945. function confirmOrderByToken($token) {
  946. $orders = getOrders();
  947. $now = date('Y-m-d H:i:s');
  948. foreach ($orders as &$order) {
  949. if (($order['confirmation_token'] ?? '') !== $token) {
  950. continue;
  951. }
  952. $order = refreshOrderState($order);
  953. if ($order['status'] === 'cancelled') {
  954. return ['success' => false, 'message' => 'Diese Bestellung wurde storniert und kann nicht mehr bestätigt werden.'];
  955. }
  956. if ($order['confirmation_status'] === 'confirmed') {
  957. return ['success' => false, 'message' => 'Diese Bestellung wurde bereits bestätigt.'];
  958. }
  959. if ($order['confirmation_status'] === 'expired') {
  960. return ['success' => false, 'message' => 'Der Bestätigungslink ist abgelaufen.'];
  961. }
  962. if ($order['confirmation_status'] !== 'pending') {
  963. return ['success' => false, 'message' => 'Für diese Bestellung ist keine Bestätigung erforderlich.'];
  964. }
  965. $expiresAt = strtotime((string) $order['confirmation_expires_at']);
  966. if ($expiresAt !== false && time() > $expiresAt) {
  967. $order['confirmation_status'] = 'expired';
  968. $order['updated_at'] = $now;
  969. saveOrders($orders);
  970. return ['success' => false, 'message' => 'Der Bestätigungslink ist abgelaufen.'];
  971. }
  972. $order['confirmation_status'] = 'confirmed';
  973. $order['confirmed_at'] = $now;
  974. $order['updated_at'] = $now;
  975. saveOrders($orders);
  976. $sent = sendConfirmedOrderAdminNotification($order);
  977. if ($sent) {
  978. markOrderAdminNotified($order['id']);
  979. }
  980. sendOrderConfirmedCustomerEmail(getOrderById($order['id']));
  981. return ['success' => true, 'order' => getOrderById($order['id'])];
  982. }
  983. unset($order);
  984. return ['success' => false, 'message' => 'Bestellung nicht gefunden.'];
  985. }
  986. function toggleOrderItemProcessed($orderId, $itemIndex) {
  987. $orders = getOrders();
  988. $now = date('Y-m-d H:i:s');
  989. foreach ($orders as &$order) {
  990. if ($order['id'] !== $orderId) {
  991. continue;
  992. }
  993. if ($order['status'] === 'cancelled') {
  994. return ['success' => false, 'message' => 'Stornierte Bestellungen können nicht mehr bearbeitet werden.'];
  995. }
  996. if (($order['confirmation_status'] ?? '') === 'pending') {
  997. return ['success' => false, 'message' => 'Unbestätigte Bestellungen können noch nicht bearbeitet werden.'];
  998. }
  999. if (($order['confirmation_status'] ?? '') === 'expired') {
  1000. return ['success' => false, 'message' => 'Abgelaufene unbestätigte Bestellungen können nicht bearbeitet werden.'];
  1001. }
  1002. if (!isset($order['items'][$itemIndex])) {
  1003. return ['success' => false, 'message' => 'Position nicht gefunden.'];
  1004. }
  1005. $order['items'][$itemIndex]['is_processed'] = empty($order['items'][$itemIndex]['is_processed']);
  1006. $order['updated_at'] = $now;
  1007. $order = refreshOrderState($order);
  1008. saveOrders($orders);
  1009. return ['success' => true, 'order' => $order];
  1010. }
  1011. unset($order);
  1012. return ['success' => false, 'message' => 'Bestellung nicht gefunden.'];
  1013. }
  1014. function cancelOrder($orderId, $adminUsername, $reason = '') {
  1015. $orders = getOrders();
  1016. $now = date('Y-m-d H:i:s');
  1017. $adminUsername = normalizeAdminUsername($adminUsername);
  1018. $reason = trim((string) $reason);
  1019. foreach ($orders as &$order) {
  1020. if ($order['id'] !== $orderId) {
  1021. continue;
  1022. }
  1023. if ($order['status'] === 'cancelled') {
  1024. return ['success' => false, 'message' => 'Die Bestellung ist bereits storniert.'];
  1025. }
  1026. $order['status'] = 'cancelled';
  1027. $order['cancelled_at'] = $now;
  1028. $order['cancelled_by'] = $adminUsername;
  1029. $order['cancellation_reason'] = $reason;
  1030. $order['updated_at'] = $now;
  1031. saveOrders($orders);
  1032. return ['success' => true, 'order' => $order];
  1033. }
  1034. unset($order);
  1035. return ['success' => false, 'message' => 'Bestellung nicht gefunden.'];
  1036. }
  1037. function getOrderStatusLabel($order) {
  1038. if (($order['status'] ?? '') === 'cancelled') {
  1039. return 'Storniert';
  1040. }
  1041. if (($order['confirmation_status'] ?? '') === 'pending') {
  1042. return 'Unbestätigt';
  1043. }
  1044. if (($order['confirmation_status'] ?? '') === 'expired') {
  1045. return 'Bestätigung abgelaufen';
  1046. }
  1047. if (($order['status'] ?? '') === 'processed') {
  1048. return 'Bearbeitet';
  1049. }
  1050. if (($order['status'] ?? '') === 'partial') {
  1051. return 'Teilweise bearbeitet';
  1052. }
  1053. return 'Offen';
  1054. }
  1055. function getOrderStatusClass($order) {
  1056. if (($order['status'] ?? '') === 'cancelled') {
  1057. return 'status-cancelled';
  1058. }
  1059. if (($order['confirmation_status'] ?? '') === 'pending') {
  1060. return 'status-unconfirmed';
  1061. }
  1062. if (($order['confirmation_status'] ?? '') === 'expired') {
  1063. return 'status-expired';
  1064. }
  1065. if (($order['status'] ?? '') === 'processed') {
  1066. return 'status-processed';
  1067. }
  1068. if (($order['status'] ?? '') === 'partial') {
  1069. return 'status-partial';
  1070. }
  1071. return 'status-open';
  1072. }
  1073. function formatDate($dateString) {
  1074. $dateString = trim((string) $dateString);
  1075. if ($dateString === '') {
  1076. return '-';
  1077. }
  1078. try {
  1079. $date = new DateTimeImmutable($dateString);
  1080. return $date->format('d.m.Y H:i');
  1081. } catch (Exception $exception) {
  1082. return $dateString;
  1083. }
  1084. }
  1085. function getCart() {
  1086. $cart = $_SESSION['cart'] ?? [];
  1087. if (!is_array($cart)) {
  1088. $cart = [];
  1089. }
  1090. $normalized = [];
  1091. $seen = [];
  1092. foreach ($cart as $item) {
  1093. $productId = isset($item['product_id']) ? (int) $item['product_id'] : 0;
  1094. $size = trim((string) ($item['size'] ?? ''));
  1095. $product = getProductById($productId);
  1096. if ($product === null) {
  1097. continue;
  1098. }
  1099. $sizes = getProductSizes($product);
  1100. if (!empty($sizes)) {
  1101. if ($size === '' || !in_array($size, $sizes, true)) {
  1102. continue;
  1103. }
  1104. } else {
  1105. $size = '';
  1106. }
  1107. $key = $productId . '|' . $size;
  1108. if (isset($seen[$key])) {
  1109. continue;
  1110. }
  1111. $seen[$key] = true;
  1112. $normalized[] = [
  1113. 'product_id' => $productId,
  1114. 'size' => $size,
  1115. ];
  1116. }
  1117. $_SESSION['cart'] = array_values($normalized);
  1118. return $_SESSION['cart'];
  1119. }
  1120. function addCartItem($productId, $size = '') {
  1121. $productId = (int) $productId;
  1122. $size = trim((string) $size);
  1123. $product = getProductById($productId);
  1124. if ($product === null) {
  1125. return false;
  1126. }
  1127. $sizes = getProductSizes($product);
  1128. if (!empty($sizes)) {
  1129. if ($size === '' || !in_array($size, $sizes, true)) {
  1130. return false;
  1131. }
  1132. } else {
  1133. $size = '';
  1134. }
  1135. $cart = getCart();
  1136. foreach ($cart as $item) {
  1137. if ((int) $item['product_id'] === $productId && (string) $item['size'] === $size) {
  1138. return true;
  1139. }
  1140. }
  1141. $cart[] = [
  1142. 'product_id' => $productId,
  1143. 'size' => $size,
  1144. ];
  1145. $_SESSION['cart'] = array_values($cart);
  1146. return true;
  1147. }
  1148. function removeCartItemByIndex($index) {
  1149. $cart = getCart();
  1150. if (isset($cart[$index])) {
  1151. unset($cart[$index]);
  1152. $_SESSION['cart'] = array_values($cart);
  1153. }
  1154. }
  1155. function clearCart() {
  1156. $_SESSION['cart'] = [];
  1157. }
  1158. function getCartItemsDetailed() {
  1159. $items = [];
  1160. foreach (getCart() as $index => $cartItem) {
  1161. $product = getProductById($cartItem['product_id']);
  1162. if ($product === null) {
  1163. continue;
  1164. }
  1165. $size = trim((string) ($cartItem['size'] ?? ''));
  1166. $items[] = [
  1167. 'cart_index' => $index,
  1168. 'product' => $product,
  1169. 'size' => $size,
  1170. 'availability_label' => $size !== '' ? getAvailabilityLabel($product, $size) : '',
  1171. ];
  1172. }
  1173. return $items;
  1174. }
  1175. function buildOrderItemsFromCart() {
  1176. $items = [];
  1177. foreach (getCart() as $cartItem) {
  1178. $product = getProductById($cartItem['product_id']);
  1179. if ($product === null) {
  1180. continue;
  1181. }
  1182. $size = trim((string) ($cartItem['size'] ?? ''));
  1183. $items[] = [
  1184. 'product_id' => $product['id'],
  1185. 'size' => $size,
  1186. 'is_processed' => false,
  1187. ];
  1188. }
  1189. return normalizeOrderItems($items);
  1190. }
  1191. function buildOrderItemsHtml($order) {
  1192. $parts = [];
  1193. foreach ($order['items'] as $item) {
  1194. $label = '<strong>' . escape($item['product_name']) . '</strong>';
  1195. if ($item['size'] !== '') {
  1196. $label .= ' - Größe: ' . escape($item['size']);
  1197. }
  1198. if (!empty($item['availability_label'])) {
  1199. $label .= '<br><small>' . nl2br(escape($item['availability_label'])) . '</small>';
  1200. }
  1201. $parts[] = '<li style="margin: 0 0 0.6rem 0; padding: 0.75rem 0.9rem; background: #28292a; border: 1px solid #4a5263; border-radius: 6px;">' . $label . '</li>';
  1202. }
  1203. return '<ul style="list-style: none; margin: 0; padding: 0;">' . implode('', $parts) . '</ul>';
  1204. }
  1205. function buildOrderSummaryHtml($order, $title, $introHtml, $extraHtml = '') {
  1206. $itemsHtml = buildOrderItemsHtml($order);
  1207. return '
  1208. <html>
  1209. <head>
  1210. <meta charset="UTF-8">
  1211. </head>
  1212. <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #f5f7fb; background: #28292a; padding: 1.5rem;">
  1213. <div style="max-width: 720px; margin: 0 auto; background: #2f3541; padding: 1.5rem 2rem; border-radius: 10px; border: 1px solid #3b4252;">
  1214. <h2 style="color: #cac300; margin-top: 0;">' . escape($title) . '</h2>
  1215. ' . $introHtml . '
  1216. <div style="background: #28292a; border: 2px solid #cac300; padding: 1.5rem; margin: 1.5rem 0; border-radius: 8px;">
  1217. <h3 style="margin-top: 0;">Bestellnummer</h3>
  1218. <p style="margin: 0; color: #cac300; font-family: monospace;">' . escape($order['id']) . '</p>
  1219. </div>
  1220. <p><strong>Name:</strong> ' . escape($order['customer_name']) . '</p>
  1221. <p><strong>E-Mail:</strong> ' . escape($order['customer_email']) . '</p>
  1222. <p><strong>Organisation:</strong> ' . escape($order['organization_label']) . '</p>
  1223. <p><strong>Erstellt am:</strong> ' . escape(formatDate($order['created_at'])) . '</p>
  1224. <h3>Bestellte Artikel</h3>
  1225. <div style="background: #303745; border: 1px solid #4a5263; border-left: 4px solid #cac300; border-radius: 8px; padding: 1rem;">' . $itemsHtml . '</div>
  1226. <p><strong>Kommentar:</strong><br>' . ($order['comment'] !== '' ? nl2br(escape($order['comment'])) : 'Kein Kommentar') . '</p>
  1227. ' . $extraHtml . '
  1228. </div>
  1229. </body>
  1230. </html>';
  1231. }
  1232. function sendOrderConfirmationRequestEmail($order) {
  1233. $subject = 'Bitte Bestellung bestätigen: ' . $order['id'];
  1234. $link = buildOrderConfirmationUrl($order['confirmation_token']);
  1235. $expiryText = formatDate($order['confirmation_expires_at']);
  1236. $intro = '<p>Guten Tag ' . escape($order['customer_name']) . ',</p><p>bitte bestätigen Sie Ihre PSA-Bestellung über den folgenden Link.</p>';
  1237. $extra = '
  1238. <p><a href="' . escape($link) . '" style="display: inline-block; padding: 0.75rem 1.25rem; background: #cf2e2e; color: #ffffff; text-decoration: none; border-radius: 4px;">Bestellung bestätigen</a></p>
  1239. <p>Der Link ist gültig bis: <strong>' . escape($expiryText) . '</strong></p>
  1240. <p>Falls der Button nicht funktioniert, verwenden Sie bitte diesen Link:<br>' . escape($link) . '</p>';
  1241. $message = buildOrderSummaryHtml($order, 'Bestellung bestätigen', $intro, $extra);
  1242. return sendEmail($order['customer_email'], $subject, $message);
  1243. }
  1244. function sendOrderCreatedCustomerEmail($order) {
  1245. $subject = 'Ihre PSA-Bestellung: ' . $order['id'];
  1246. $intro = '<p>Guten Tag ' . escape($order['customer_name']) . ',</p><p>Ihre Bestellung wurde erfasst und an die zuständige Stelle weitergeleitet.</p>';
  1247. $message = buildOrderSummaryHtml($order, 'Bestellung eingegangen', $intro);
  1248. return sendEmail($order['customer_email'], $subject, $message);
  1249. }
  1250. function sendOrderConfirmedCustomerEmail($order) {
  1251. $subject = 'Ihre PSA-Bestellung wurde bestätigt: ' . $order['id'];
  1252. $intro = '<p>Guten Tag ' . escape($order['customer_name']) . ',</p><p>Ihre Bestellung wurde bestätigt und intern weitergeleitet.</p>';
  1253. $message = buildOrderSummaryHtml($order, 'Bestellung bestätigt', $intro);
  1254. return sendEmail($order['customer_email'], $subject, $message);
  1255. }
  1256. function sendConfirmedOrderAdminNotification($order) {
  1257. $recipient = getOrderRecipientEmail();
  1258. if (!isValidAdminEmail($recipient)) {
  1259. return false;
  1260. }
  1261. $subject = 'Neue PSA-Bestellung: ' . $order['id'];
  1262. $intro = '<p>Eine neue PSA-Bestellung wurde freigegeben und muss bearbeitet werden.</p>';
  1263. $message = buildOrderSummaryHtml($order, 'Neue PSA-Bestellung', $intro);
  1264. $attachments = [];
  1265. if (shouldAttachOrderPdfToAdminEmail()) {
  1266. $attachments[] = [
  1267. 'filename' => 'bestellung-' . strtolower($order['id']) . '.pdf',
  1268. 'content_type' => 'application/pdf',
  1269. 'content' => generateOrderPdf($order),
  1270. ];
  1271. }
  1272. return sendEmail($recipient, $subject, $message, true, $attachments);
  1273. }
  1274. function sendEmail($to, $subject, $message, $isHtml = true, $attachments = []) {
  1275. $headers = [];
  1276. $headers[] = 'From: ' . FROM_NAME . ' <' . FROM_EMAIL . '>';
  1277. $headers[] = 'Reply-To: ' . FROM_EMAIL;
  1278. $headers[] = 'X-Mailer: PHP/' . phpversion();
  1279. if (empty($attachments)) {
  1280. if ($isHtml) {
  1281. $headers[] = 'MIME-Version: 1.0';
  1282. $headers[] = 'Content-Type: text/html; charset=UTF-8';
  1283. } else {
  1284. $headers[] = 'Content-Type: text/plain; charset=UTF-8';
  1285. }
  1286. return mail($to, $subject, $message, implode("\r\n", $headers));
  1287. }
  1288. $boundary = '=_Boundary_' . bin2hex(random_bytes(8));
  1289. $headers[] = 'MIME-Version: 1.0';
  1290. $headers[] = 'Content-Type: multipart/mixed; boundary="' . $boundary . '"';
  1291. $body = [];
  1292. $body[] = '--' . $boundary;
  1293. $body[] = 'Content-Type: ' . ($isHtml ? 'text/html' : 'text/plain') . '; charset=UTF-8';
  1294. $body[] = 'Content-Transfer-Encoding: 8bit';
  1295. $body[] = '';
  1296. $body[] = $message;
  1297. foreach ($attachments as $attachment) {
  1298. if (!is_array($attachment)) {
  1299. continue;
  1300. }
  1301. $filename = trim((string) ($attachment['filename'] ?? 'attachment.bin'));
  1302. $contentType = trim((string) ($attachment['content_type'] ?? 'application/octet-stream'));
  1303. $content = isset($attachment['content']) ? (string) $attachment['content'] : '';
  1304. $body[] = '--' . $boundary;
  1305. $body[] = 'Content-Type: ' . $contentType . '; name="' . $filename . '"';
  1306. $body[] = 'Content-Transfer-Encoding: base64';
  1307. $body[] = 'Content-Disposition: attachment; filename="' . $filename . '"';
  1308. $body[] = '';
  1309. $body[] = chunk_split(base64_encode($content));
  1310. }
  1311. $body[] = '--' . $boundary . '--';
  1312. $body[] = '';
  1313. return mail($to, $subject, implode("\r\n", $body), implode("\r\n", $headers));
  1314. }
  1315. function buildOrderPdfLines($order) {
  1316. $lines = [
  1317. SITE_NAME,
  1318. '',
  1319. 'PSA-Bestellung',
  1320. 'Bestellnummer: ' . $order['id'],
  1321. 'Erstellt am: ' . formatDate($order['created_at']),
  1322. 'Name: ' . $order['customer_name'],
  1323. 'E-Mail: ' . $order['customer_email'],
  1324. 'Organisation: ' . $order['organization_label'],
  1325. '',
  1326. 'Artikel:',
  1327. ];
  1328. foreach ($order['items'] as $item) {
  1329. $line = '- ' . $item['product_name'];
  1330. if ($item['size'] !== '') {
  1331. $line .= ' | Größe: ' . $item['size'];
  1332. }
  1333. if ($item['availability_label'] !== '') {
  1334. $line .= ' | Hinweis: ' . preg_replace('/\s+/', ' ', $item['availability_label']);
  1335. }
  1336. $lines[] = $line;
  1337. }
  1338. $lines[] = '';
  1339. $lines[] = 'Kommentar:';
  1340. if ($order['comment'] !== '') {
  1341. foreach (preg_split('/\r\n|\r|\n/', $order['comment']) as $commentLine) {
  1342. $lines[] = $commentLine;
  1343. }
  1344. } else {
  1345. $lines[] = 'Kein Kommentar';
  1346. }
  1347. return $lines;
  1348. }
  1349. function pdfEscapeText($text) {
  1350. $text = str_replace('\\', '\\\\', $text);
  1351. $text = str_replace('(', '\(', $text);
  1352. $text = str_replace(')', '\)', $text);
  1353. $text = str_replace("\r", '', $text);
  1354. if (function_exists('iconv')) {
  1355. $converted = @iconv('UTF-8', 'Windows-1252//TRANSLIT//IGNORE', $text);
  1356. if (is_string($converted)) {
  1357. $text = $converted;
  1358. }
  1359. }
  1360. return $text;
  1361. }
  1362. function generateOrderPdf($order) {
  1363. $lines = buildOrderPdfLines($order);
  1364. $content = "BT\n/F1 12 Tf\n14 TL\n50 790 Td\n";
  1365. $first = true;
  1366. foreach ($lines as $line) {
  1367. if (!$first) {
  1368. $content .= "T*\n";
  1369. }
  1370. $first = false;
  1371. $content .= '(' . pdfEscapeText($line) . ") Tj\n";
  1372. }
  1373. $content .= "ET";
  1374. $length = strlen($content);
  1375. $objects = [];
  1376. $objects[] = "1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n";
  1377. $objects[] = "2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n";
  1378. $objects[] = "3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>\nendobj\n";
  1379. $objects[] = "4 0 obj\n<< /Length " . $length . " >>\nstream\n" . $content . "\nendstream\nendobj\n";
  1380. $objects[] = "5 0 obj\n<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>\nendobj\n";
  1381. $pdf = "%PDF-1.4\n";
  1382. $offsets = [0];
  1383. foreach ($objects as $object) {
  1384. $offsets[] = strlen($pdf);
  1385. $pdf .= $object;
  1386. }
  1387. $xrefOffset = strlen($pdf);
  1388. $pdf .= "xref\n0 " . (count($objects) + 1) . "\n";
  1389. $pdf .= "0000000000 65535 f \n";
  1390. for ($i = 1; $i <= count($objects); $i++) {
  1391. $pdf .= sprintf("%010d 00000 n \n", $offsets[$i]);
  1392. }
  1393. $pdf .= "trailer\n<< /Size " . (count($objects) + 1) . " /Root 1 0 R >>\n";
  1394. $pdf .= "startxref\n" . $xrefOffset . "\n%%EOF";
  1395. return $pdf;
  1396. }