functions.php 54 KB

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