functions.php 53 KB

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