functions.php 53 KB

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