| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831 |
- <?php
- require_once __DIR__ . "/../config.php";
- function readJsonFile($file)
- {
- if (!file_exists($file)) {
- return [];
- }
- $content = file_get_contents($file);
- if ($content === false || trim($content) === "") {
- return [];
- }
- $data = json_decode($content, true);
- return is_array($data) ? $data : [];
- }
- function writeJsonFile($file, $data)
- {
- $dir = dirname($file);
- if (!is_dir($dir) && !mkdir($dir, 02775, true) && !is_dir($dir)) {
- return false;
- }
- @chmod($dir, 02775);
- if (file_exists($file) && !is_writable($file)) {
- @chmod($file, 0664);
- }
- $json = json_encode(
- $data,
- JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES,
- );
- // Atomic write using temp file + rename
- $tmpFile = $file . ".tmp";
- $result = file_put_contents($tmpFile, $json, LOCK_EX);
- if ($result === false) {
- return false;
- }
- @chmod($tmpFile, 0664);
- // Rename is atomic on same filesystem
- if (!rename($tmpFile, $file)) {
- unlink($tmpFile);
- return false;
- }
- @chmod($file, 0664);
- return true;
- }
- function sanitize($input)
- {
- return trim(strip_tags((string) $input));
- }
- function escape($value)
- {
- return htmlspecialchars((string) $value, ENT_QUOTES, "UTF-8");
- }
- /**
- * CSRF Protection
- */
- function generateCsrfToken()
- {
- if (empty($_SESSION["csrf_token"])) {
- $_SESSION["csrf_token"] = bin2hex(random_bytes(32));
- }
- return $_SESSION["csrf_token"];
- }
- function validateCsrfToken($token)
- {
- if (empty($_SESSION["csrf_token"])) {
- return false;
- }
- return hash_equals($_SESSION["csrf_token"], $token);
- }
- function csrfField()
- {
- return '<input type="hidden" name="csrf_token" value="' .
- escape(generateCsrfToken()) .
- '">';
- }
- function getUploadFilename($filename)
- {
- $filename = trim((string) $filename);
- if ($filename === "") {
- return "";
- }
- return basename($filename);
- }
- function getUploadPath($filename)
- {
- $filename = getUploadFilename($filename);
- if ($filename === "") {
- return null;
- }
- return rtrim(UPLOADS_DIR, "/\\") . "/" . $filename;
- }
- function getUploadUrl($filename)
- {
- $filename = getUploadFilename($filename);
- if ($filename === "") {
- return null;
- }
- return rtrim(UPLOADS_URL, "/\\") . "/" . rawurlencode($filename);
- }
- function setFlashMessage($key, $type, $message)
- {
- $key = trim((string) $key);
- $type = trim((string) $type);
- $message = trim((string) $message);
- if ($key === "" || $type === "" || $message === "") {
- return;
- }
- $_SESSION["flash_messages"][$key] = [
- "type" => $type,
- "message" => $message,
- ];
- }
- function consumeFlashMessage($key)
- {
- $key = trim((string) $key);
- if ($key === "") {
- return null;
- }
- $messages = $_SESSION["flash_messages"] ?? [];
- if (
- !is_array($messages) ||
- !isset($messages[$key]) ||
- !is_array($messages[$key])
- ) {
- return null;
- }
- $message = $messages[$key];
- unset($_SESSION["flash_messages"][$key]);
- $type = trim((string) ($message["type"] ?? ""));
- $text = trim((string) ($message["message"] ?? ""));
- if ($type === "" || $text === "") {
- return null;
- }
- return [
- "type" => $type,
- "message" => $text,
- ];
- }
- function normalizeAdminUsername($username)
- {
- return trim((string) $username);
- }
- function normalizeAdminDescription($description)
- {
- return trim((string) $description);
- }
- function normalizeAdminEmail($email)
- {
- return strtolower(trim((string) $email));
- }
- function isValidAdminUsername($username)
- {
- $username = normalizeAdminUsername($username);
- return preg_match('/^[A-Za-z0-9][A-Za-z0-9._-]{2,49}$/', $username) === 1;
- }
- function isValidAdminDescription($description)
- {
- $description = normalizeAdminDescription($description);
- if ($description === "") {
- return false;
- }
- $length = function_exists("mb_strlen")
- ? mb_strlen($description)
- : strlen($description);
- return $length <= 120;
- }
- function isValidAdminEmail($email)
- {
- $email = normalizeAdminEmail($email);
- return $email !== "" && filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
- }
- function getDefaultAdminDescription($username)
- {
- return "Admin";
- }
- function getDefaultAdminEmail()
- {
- $email = defined("ADMIN_EMAIL") ? normalizeAdminEmail(ADMIN_EMAIL) : "";
- return isValidAdminEmail($email) ? $email : "";
- }
- function getAdminAccounts()
- {
- $data = readJsonFile(ADMINS_FILE);
- $records =
- isset($data["admins"]) && is_array($data["admins"])
- ? $data["admins"]
- : [];
- $accounts = [];
- foreach ($records as $username => $record) {
- $username = normalizeAdminUsername($username);
- if ($username === "") {
- continue;
- }
- if (is_string($record)) {
- $record = [
- "password_hash" => $record,
- "description" => getDefaultAdminDescription($username),
- "email" => getDefaultAdminEmail(),
- ];
- }
- if (!is_array($record)) {
- continue;
- }
- $hash = isset($record["password_hash"])
- ? (string) $record["password_hash"]
- : "";
- if ($hash === "") {
- continue;
- }
- $description = normalizeAdminDescription(
- $record["description"] ?? getDefaultAdminDescription($username),
- );
- if (!isValidAdminDescription($description)) {
- $description = getDefaultAdminDescription($username);
- }
- $email = normalizeAdminEmail(
- $record["email"] ?? getDefaultAdminEmail(),
- );
- if (!isValidAdminEmail($email)) {
- $email = getDefaultAdminEmail();
- }
- $accounts[$username] = [
- "password_hash" => $hash,
- "description" => $description,
- "email" => $email,
- ];
- }
- ksort($accounts);
- return $accounts;
- }
- function getAdminUsers()
- {
- $users = [];
- foreach (getAdminAccounts() as $username => $record) {
- $users[$username] = $record["password_hash"];
- }
- return $users;
- }
- function saveAdminAccounts($accounts)
- {
- $result = [];
- foreach ($accounts as $username => $record) {
- $username = normalizeAdminUsername($username);
- if ($username === "" || !is_array($record)) {
- continue;
- }
- $hash = isset($record["password_hash"])
- ? (string) $record["password_hash"]
- : "";
- if ($hash === "") {
- continue;
- }
- $description = normalizeAdminDescription(
- $record["description"] ?? getDefaultAdminDescription($username),
- );
- if (!isValidAdminDescription($description)) {
- $description = getDefaultAdminDescription($username);
- }
- $email = normalizeAdminEmail(
- $record["email"] ?? getDefaultAdminEmail(),
- );
- if (!isValidAdminEmail($email)) {
- $email = getDefaultAdminEmail();
- }
- $result[$username] = [
- "password_hash" => $hash,
- "description" => $description,
- "email" => $email,
- ];
- }
- ksort($result);
- return writeJsonFile(ADMINS_FILE, ["admins" => $result]);
- }
- function getDefaultCategories()
- {
- return [["id" => "apparel", "label" => "Bekleidung"]];
- }
- function normalizeCategoryId($id)
- {
- $id = trim((string) $id);
- if ($id === "") {
- return "";
- }
- if (function_exists("iconv")) {
- $converted = @iconv("UTF-8", "ASCII//TRANSLIT//IGNORE", $id);
- if (is_string($converted) && $converted !== "") {
- $id = $converted;
- }
- }
- $id = strtolower($id);
- $id = preg_replace("/[^a-z0-9]+/", "-", $id);
- return trim((string) $id, "-");
- }
- function normalizeCategoryLabel($label)
- {
- return trim((string) $label);
- }
- function isValidCategoryLabel($label)
- {
- $label = normalizeCategoryLabel($label);
- if ($label === "") {
- return false;
- }
- $length = function_exists("mb_strlen") ? mb_strlen($label) : strlen($label);
- return $length <= 80;
- }
- function normalizeCategories($categories)
- {
- $normalized = [];
- if (!is_array($categories)) {
- $categories = [];
- }
- foreach ($categories as $category) {
- if (!is_array($category)) {
- continue;
- }
- $id = normalizeCategoryId($category["id"] ?? "");
- $label = normalizeCategoryLabel($category["label"] ?? "");
- if ($id === "" || !isValidCategoryLabel($label)) {
- continue;
- }
- $normalized[$id] = [
- "id" => $id,
- "label" => $label,
- ];
- }
- if (empty($normalized)) {
- foreach (getDefaultCategories() as $category) {
- $normalized[$category["id"]] = $category;
- }
- }
- uasort($normalized, function ($left, $right) {
- return strcasecmp($left["label"], $right["label"]);
- });
- return array_values($normalized);
- }
- function getCategories()
- {
- $data = readJsonFile(CATEGORIES_FILE);
- return normalizeCategories($data["categories"] ?? []);
- }
- function saveCategories($categories)
- {
- return writeJsonFile(CATEGORIES_FILE, [
- "categories" => normalizeCategories($categories),
- ]);
- }
- function getCategoryById($categoryId)
- {
- $categoryId = normalizeCategoryId($categoryId);
- foreach (getCategories() as $category) {
- if ($category["id"] === $categoryId) {
- return $category;
- }
- }
- return null;
- }
- function getCategoryLabel($categoryId)
- {
- $category = getCategoryById($categoryId);
- if ($category !== null) {
- return $category["label"];
- }
- return trim((string) $categoryId);
- }
- function getCategoryLabels($categoryIds)
- {
- $labels = [];
- foreach (normalizeProductCategoryIds($categoryIds) as $categoryId) {
- $labels[] = getCategoryLabel($categoryId);
- }
- return $labels;
- }
- function getCategoryChipPalette($categoryId)
- {
- $categoryId = normalizeCategoryId($categoryId);
- if ($categoryId === "") {
- return [
- "background" => "#ebe8df",
- "border" => "#d0c8b5",
- "text" => "#4b4b4b",
- ];
- }
- $hash = crc32($categoryId);
- if ($hash < 0) {
- $hash = $hash * -1;
- }
- // Spread hues across a distinct red -> blue range.
- $hueSteps = [0, 16, 32, 48, 66, 84, 104, 128, 152, 176, 200, 224];
- $hue = $hueSteps[$hash % count($hueSteps)];
- $saturation = 44 + (($hash >> 8) % 10);
- $lightness = 84 + (($hash >> 16) % 7);
- $background = "hsl(" . $hue . ", " . $saturation . "%, " . $lightness . "%)";
- $border = "hsl(" . $hue . ", " . ($saturation + 8) . "%, " . ($lightness - 16) . "%)";
- $text = "hsl(" . $hue . ", " . ($saturation + 18) . "%, 24%)";
- return [
- "background" => $background,
- "border" => $border,
- "text" => $text,
- ];
- }
- function generateCategoryIdFromLabel($label, $existingCategories = [])
- {
- $baseId = normalizeCategoryId($label);
- if ($baseId === "") {
- $baseId = "category";
- }
- $used = [];
- foreach (normalizeCategories($existingCategories) as $category) {
- $used[$category["id"]] = true;
- }
- $candidate = $baseId;
- $counter = 2;
- while (isset($used[$candidate])) {
- $candidate = $baseId . "-" . $counter;
- $counter++;
- }
- return $candidate;
- }
- function isCategoryInUse($categoryId)
- {
- foreach (getProducts() as $product) {
- if (productHasCategory($product, $categoryId)) {
- return true;
- }
- }
- return false;
- }
- function normalizeProductCategoryIds($categoryValue)
- {
- if (is_array($categoryValue)) {
- $rawIds = $categoryValue;
- } elseif ($categoryValue === null || $categoryValue === "") {
- $rawIds = [];
- } else {
- $rawIds = [$categoryValue];
- }
- $normalized = [];
- foreach ($rawIds as $categoryId) {
- $categoryId = normalizeCategoryId($categoryId);
- if ($categoryId !== "") {
- $normalized[$categoryId] = $categoryId;
- }
- }
- return array_values($normalized);
- }
- function getProductCategoryIds($product)
- {
- if (isset($product["categories"])) {
- return normalizeProductCategoryIds($product["categories"]);
- }
- return normalizeProductCategoryIds($product["category"] ?? []);
- }
- function productHasCategory($product, $categoryId)
- {
- $categoryId = normalizeCategoryId($categoryId);
- if ($categoryId === "") {
- return false;
- }
- return in_array($categoryId, getProductCategoryIds($product), true);
- }
- function getProductSizes($product)
- {
- if (isset($product["sizes"]) && is_array($product["sizes"])) {
- $sizes = $product["sizes"];
- } elseif (isset($product["sizes"]) && is_string($product["sizes"])) {
- $sizes = explode(",", $product["sizes"]);
- } else {
- $sizes = [];
- }
- $normalized = [];
- foreach ($sizes as $size) {
- $size = trim((string) $size);
- if ($size !== "") {
- $normalized[$size] = $size;
- }
- }
- return array_values($normalized);
- }
- function productUsesSizeStock($product)
- {
- return !empty(getProductSizes($product));
- }
- function normalizeAvailabilityLabels($sizes, $labels)
- {
- $result = [];
- if (!is_array($labels)) {
- $labels = [];
- }
- foreach ($sizes as $size) {
- $text = trim((string) ($labels[$size] ?? ""));
- $result[$size] = $text;
- }
- return $result;
- }
- function getAvailabilityLabel($product, $size)
- {
- $labels =
- isset($product["availability_labels"]) &&
- is_array($product["availability_labels"])
- ? $product["availability_labels"]
- : [];
- return trim((string) ($labels[$size] ?? ""));
- }
- function normalizeProductRecord($product, $defaultCategoryId = "")
- {
- if (!is_array($product)) {
- return null;
- }
- $productId = isset($product["id"]) ? (int) $product["id"] : 0;
- $name = trim((string) ($product["name"] ?? ""));
- if ($productId <= 0 || $name === "") {
- return null;
- }
- $sizes = getProductSizes($product);
- if (empty($sizes)) {
- $sizes = ["Standard"];
- }
- $categories = getProductCategoryIds($product);
- if (empty($categories) && $defaultCategoryId !== "") {
- $categories = [$defaultCategoryId];
- }
- $availabilityLabels = normalizeAvailabilityLabels(
- $sizes,
- isset($product["availability_labels"]) &&
- is_array($product["availability_labels"])
- ? $product["availability_labels"]
- : [],
- );
- return [
- "id" => $productId,
- "name" => $name,
- "description" => trim((string) ($product["description"] ?? "")),
- "image" => trim((string) ($product["image"] ?? "")),
- "categories" => $categories,
- "sizes" => implode(",", $sizes),
- "availability_labels" => $availabilityLabels,
- ];
- }
- function getProducts()
- {
- $data = readJsonFile(PRODUCTS_FILE);
- $rawProducts =
- isset($data["products"]) && is_array($data["products"])
- ? $data["products"]
- : [];
- $categories = getCategories();
- $defaultCategoryId = !empty($categories) ? $categories[0]["id"] : "apparel";
- $products = [];
- foreach ($rawProducts as $product) {
- $normalized = normalizeProductRecord($product, $defaultCategoryId);
- if ($normalized !== null) {
- $products[] = $normalized;
- }
- }
- usort($products, function ($left, $right) {
- return strcasecmp($left["name"], $right["name"]);
- });
- return $products;
- }
- function getProductById($id)
- {
- $id = (int) $id;
- foreach (getProducts() as $product) {
- if ((int) $product["id"] === $id) {
- return $product;
- }
- }
- return null;
- }
- function saveProducts($products)
- {
- $categories = getCategories();
- $defaultCategoryId = !empty($categories) ? $categories[0]["id"] : "apparel";
- $normalized = [];
- foreach ($products as $product) {
- $record = normalizeProductRecord($product, $defaultCategoryId);
- if ($record !== null) {
- $normalized[] = $record;
- }
- }
- return writeJsonFile(PRODUCTS_FILE, [
- "products" => array_values($normalized),
- ]);
- }
- function getFaqFilePath(): string
- {
- $dataDir = defined("DATA_DIR") ? DATA_DIR : dirname(__DIR__) . "/data/";
- $defaultPath = rtrim($dataDir, "/\\") . "/faq.json";
- if (!defined("FAQ_FILE") || !is_string(FAQ_FILE) || FAQ_FILE === "") {
- return $defaultPath;
- }
- $configuredPath = FAQ_FILE;
- $normalizedDataDir = str_replace("\\", "/", rtrim($dataDir, "/\\")) . "/";
- $normalizedConfigured = str_replace("\\", "/", $configuredPath);
- if (strpos($normalizedConfigured, $normalizedDataDir) !== 0) {
- return $defaultPath;
- }
- return $configuredPath;
- }
- function getFaqContent(): string
- {
- $defaultContent =
- "# FAQ\n\nHier kann der FAQ-Inhalt im Admin-Bereich bearbeitet werden.";
- $data = readJsonFile(getFaqFilePath());
- if (!isset($data["content"]) || !is_string($data["content"])) {
- return $defaultContent;
- }
- return $data["content"];
- }
- function saveFaqContent(string $markdown): bool
- {
- return writeJsonFile(getFaqFilePath(), ["content" => (string) $markdown]);
- }
- function renderFaqInlineMarkdown(string $text): string
- {
- $escaped = escape($text);
- $escaped = preg_replace_callback(
- '/\[([^\]]+)\]\(([^)\s]+)\)/',
- function ($matches) {
- $label = $matches[1];
- $url = trim(html_entity_decode($matches[2], ENT_QUOTES, "UTF-8"));
- if ($url === "") {
- return $matches[0];
- }
- $scheme = strtolower((string) parse_url($url, PHP_URL_SCHEME));
- if (!in_array($scheme, ["http", "https", "mailto"], true)) {
- return $matches[0];
- }
- return '<a href="' . escape($url) . '">' . $label . "</a>";
- },
- $escaped,
- );
- $escaped = preg_replace(
- "/\*\*(.+?)\*\*/s",
- '<strong>$1</strong>',
- $escaped,
- );
- $escaped = preg_replace(
- "/(?<!\*)\*(?!\s)(.+?)(?<!\s)\*(?!\*)/s",
- '<em>$1</em>',
- $escaped,
- );
- return $escaped;
- }
- function renderFaqMarkdown(string $markdown): string
- {
- $normalized = str_replace(["\r\n", "\r"], "\n", $markdown);
- $lines = explode("\n", $normalized);
- $htmlParts = [];
- $paragraphLines = [];
- $listType = "";
- $flushParagraph = function () use (&$paragraphLines, &$htmlParts): void {
- if (empty($paragraphLines)) {
- return;
- }
- $rendered = [];
- foreach ($paragraphLines as $line) {
- $rendered[] = renderFaqInlineMarkdown($line);
- }
- $htmlParts[] = "<p>" . implode("<br>\n", $rendered) . "</p>";
- $paragraphLines = [];
- };
- $closeList = function () use (&$listType, &$htmlParts): void {
- if ($listType !== "") {
- $htmlParts[] = "</" . $listType . ">";
- $listType = "";
- }
- };
- foreach ($lines as $line) {
- $line = rtrim($line);
- $trimmed = trim($line);
- if ($trimmed === "") {
- $flushParagraph();
- $closeList();
- continue;
- }
- if (preg_match('/^(#{1,3})\s+(.+)$/', $trimmed, $matches) === 1) {
- $flushParagraph();
- $closeList();
- $level = strlen($matches[1]);
- $htmlParts[] =
- "<h" .
- $level .
- ">" .
- renderFaqInlineMarkdown($matches[2]) .
- "</h" .
- $level .
- ">";
- continue;
- }
- if (preg_match('/^\s*[-*]\s+(.+)$/', $line, $matches) === 1) {
- $flushParagraph();
- if ($listType !== "ul") {
- $closeList();
- $listType = "ul";
- $htmlParts[] = "<ul>";
- }
- $htmlParts[] =
- "<li>" . renderFaqInlineMarkdown($matches[1]) . "</li>";
- continue;
- }
- if (preg_match('/^\s*\d+\.\s+(.+)$/', $line, $matches) === 1) {
- $flushParagraph();
- if ($listType !== "ol") {
- $closeList();
- $listType = "ol";
- $htmlParts[] = "<ol>";
- }
- $htmlParts[] =
- "<li>" . renderFaqInlineMarkdown($matches[1]) . "</li>";
- continue;
- }
- $closeList();
- $paragraphLines[] = $trimmed;
- }
- $flushParagraph();
- $closeList();
- return empty($htmlParts)
- ? "<p>Keine FAQ-Inhalte vorhanden.</p>"
- : implode("\n", $htmlParts);
- }
- function getDefaultOrganizations()
- {
- return [
- [
- "id" => "feuerwehr-freising",
- "label" => "Amt 32 - Feuerwehr Freising",
- "sort_order" => 10,
- "active" => true,
- ],
- ];
- }
- function normalizeOrganizationId($id)
- {
- return normalizeCategoryId($id);
- }
- function normalizeOrganizationLabel($label)
- {
- return trim((string) $label);
- }
- function isValidOrganizationLabel($label)
- {
- $label = normalizeOrganizationLabel($label);
- if ($label === "") {
- return false;
- }
- $length = function_exists("mb_strlen") ? mb_strlen($label) : strlen($label);
- return $length <= 120;
- }
- function normalizeOrganizations($organizations)
- {
- $normalized = [];
- if (!is_array($organizations)) {
- $organizations = [];
- }
- foreach ($organizations as $organization) {
- if (!is_array($organization)) {
- continue;
- }
- $id = normalizeOrganizationId($organization["id"] ?? "");
- $label = normalizeOrganizationLabel($organization["label"] ?? "");
- if ($id === "" || !isValidOrganizationLabel($label)) {
- continue;
- }
- $sortOrder = isset($organization["sort_order"])
- ? (int) $organization["sort_order"]
- : 0;
- $active =
- !isset($organization["active"]) || (bool) $organization["active"];
- $normalized[$id] = [
- "id" => $id,
- "label" => $label,
- "sort_order" => $sortOrder,
- "active" => $active,
- ];
- }
- if (empty($normalized)) {
- foreach (getDefaultOrganizations() as $organization) {
- $normalized[$organization["id"]] = $organization;
- }
- }
- uasort($normalized, function ($left, $right) {
- if ($left["sort_order"] === $right["sort_order"]) {
- return strcasecmp($left["label"], $right["label"]);
- }
- return $left["sort_order"] <=> $right["sort_order"];
- });
- return array_values($normalized);
- }
- function getOrganizations($onlyActive = false)
- {
- $data = readJsonFile(ORGANIZATIONS_FILE);
- $organizations = normalizeOrganizations($data["organizations"] ?? []);
- if ($onlyActive) {
- $organizations = array_values(
- array_filter($organizations, function ($organization) {
- return !empty($organization["active"]);
- }),
- );
- }
- return $organizations;
- }
- function saveOrganizations($organizations)
- {
- return writeJsonFile(ORGANIZATIONS_FILE, [
- "organizations" => normalizeOrganizations($organizations),
- ]);
- }
- function getOrganizationById($organizationId)
- {
- $organizationId = normalizeOrganizationId($organizationId);
- foreach (getOrganizations(false) as $organization) {
- if ($organization["id"] === $organizationId) {
- return $organization;
- }
- }
- return null;
- }
- function generateOrganizationIdFromLabel($label, $existingOrganizations = [])
- {
- $baseId = normalizeOrganizationId($label);
- if ($baseId === "") {
- $baseId = "organization";
- }
- $used = [];
- foreach (normalizeOrganizations($existingOrganizations) as $organization) {
- $used[$organization["id"]] = true;
- }
- $candidate = $baseId;
- $counter = 2;
- while (isset($used[$candidate])) {
- $candidate = $baseId . "-" . $counter;
- $counter++;
- }
- return $candidate;
- }
- function getDefaultSystemSettings()
- {
- $startpageIntroText = "";
- if (defined("DISCLAIMER_LINES") && is_array(DISCLAIMER_LINES)) {
- $lines = array_filter(
- array_map(function ($line) {
- return trim((string) $line);
- }, DISCLAIMER_LINES),
- function ($line) {
- return $line !== "";
- },
- );
- $startpageIntroText = implode("\n", $lines);
- }
- return [
- "order_recipient_email" => defined("ORDER_RECIPIENT_EMAIL")
- ? ORDER_RECIPIENT_EMAIL
- : getDefaultAdminEmail(),
- "order_confirmation_required" => defined("ORDER_CONFIRMATION_REQUIRED")
- ? (bool) ORDER_CONFIRMATION_REQUIRED
- : false,
- "order_confirmation_expiry_days" => defined(
- "ORDER_CONFIRMATION_EXPIRY_DAYS",
- )
- ? (int) ORDER_CONFIRMATION_EXPIRY_DAYS
- : 7,
- "attach_order_pdf_to_admin_email" => defined(
- "ATTACH_ORDER_PDF_TO_ADMIN_EMAIL",
- )
- ? (bool) ATTACH_ORDER_PDF_TO_ADMIN_EMAIL
- : true,
- "startpage_intro_text" => $startpageIntroText,
- ];
- }
- function normalizeSystemSettings($settings)
- {
- $defaults = getDefaultSystemSettings();
- if (!is_array($settings)) {
- $settings = [];
- }
- $recipientEmail = normalizeAdminEmail(
- $settings["order_recipient_email"] ??
- $defaults["order_recipient_email"],
- );
- if (!isValidAdminEmail($recipientEmail)) {
- $recipientEmail = $defaults["order_recipient_email"];
- }
- $expiryDays = isset($settings["order_confirmation_expiry_days"])
- ? (int) $settings["order_confirmation_expiry_days"]
- : $defaults["order_confirmation_expiry_days"];
- if ($expiryDays < 1) {
- $expiryDays = 7;
- }
- $startpageIntroText = trim(
- (string) ($settings["startpage_intro_text"] ?? $defaults["startpage_intro_text"]),
- );
- return [
- "order_recipient_email" => $recipientEmail,
- "order_confirmation_required" => !empty(
- $settings["order_confirmation_required"]
- ),
- "order_confirmation_expiry_days" => $expiryDays,
- "attach_order_pdf_to_admin_email" => !empty(
- $settings["attach_order_pdf_to_admin_email"]
- ),
- "startpage_intro_text" => $startpageIntroText,
- ];
- }
- function getSystemSettings()
- {
- $data = readJsonFile(SETTINGS_FILE);
- return normalizeSystemSettings($data["settings"] ?? []);
- }
- function saveSystemSettings($settings)
- {
- return writeJsonFile(SETTINGS_FILE, [
- "settings" => normalizeSystemSettings($settings),
- ]);
- }
- function getOrderRecipientEmail()
- {
- $settings = getSystemSettings();
- return $settings["order_recipient_email"];
- }
- function isOrderConfirmationRequired()
- {
- $settings = getSystemSettings();
- return !empty($settings["order_confirmation_required"]);
- }
- function getOrderConfirmationExpiryDays()
- {
- $settings = getSystemSettings();
- return max(1, (int) $settings["order_confirmation_expiry_days"]);
- }
- function shouldAttachOrderPdfToAdminEmail()
- {
- $settings = getSystemSettings();
- return !empty($settings["attach_order_pdf_to_admin_email"]);
- }
- function getStartpageIntroLines()
- {
- $settings = getSystemSettings();
- $text = trim((string) ($settings["startpage_intro_text"] ?? ""));
- if ($text === "") {
- return [];
- }
- $lines = preg_split('/\R+/', $text) ?: [];
- $lines = array_values(
- array_filter(
- array_map(function ($line) {
- return trim((string) $line);
- }, $lines),
- function ($line) {
- return $line !== "";
- },
- ),
- );
- return $lines;
- }
- function normalizeOrderItem($item)
- {
- if (!is_array($item)) {
- return null;
- }
- $productId = isset($item["product_id"]) ? (int) $item["product_id"] : 0;
- if ($productId <= 0) {
- return null;
- }
- $product = getProductById($productId);
- if ($product === null) {
- return null;
- }
- $size = trim((string) ($item["size"] ?? ""));
- $sizes = getProductSizes($product);
- if (!empty($sizes)) {
- if ($size === "" || !in_array($size, $sizes, true)) {
- return null;
- }
- } else {
- $size = "";
- }
- return [
- "product_id" => $productId,
- "product_name" => $product["name"],
- "size" => $size,
- "availability_label" =>
- $size !== "" ? getAvailabilityLabel($product, $size) : "",
- "is_processed" => !empty($item["is_processed"]),
- ];
- }
- function normalizeOrderItems($items)
- {
- $normalized = [];
- $seen = [];
- if (!is_array($items)) {
- return [];
- }
- foreach ($items as $item) {
- $record = normalizeOrderItem($item);
- if ($record === null) {
- continue;
- }
- $key = $record["product_id"] . "|" . $record["size"];
- if (isset($seen[$key])) {
- continue;
- }
- $seen[$key] = true;
- $normalized[] = $record;
- }
- return array_values($normalized);
- }
- function getOrders()
- {
- $data = readJsonFile(ORDERS_FILE);
- $orders =
- isset($data["orders"]) && is_array($data["orders"])
- ? $data["orders"]
- : [];
- $normalized = [];
- foreach ($orders as $order) {
- $record = normalizeOrderRecord($order);
- if ($record !== null) {
- $normalized[] = $record;
- }
- }
- return $normalized;
- }
- function saveOrders($orders)
- {
- $normalized = [];
- foreach ($orders as $order) {
- $record = normalizeOrderRecord($order);
- if ($record !== null) {
- $normalized[] = $record;
- }
- }
- $result = writeJsonFile(ORDERS_FILE, [
- "orders" => array_values($normalized),
- ]);
- if (!$result) {
- logError("Failed to save orders", [
- "file" => ORDERS_FILE,
- "order_count" => count($normalized),
- ]);
- }
- return (bool) $result;
- }
- function generateOrderId()
- {
- $orders = getOrders();
- $year = date("Y");
- $prefix = defined("ORDER_PREFIX") ? ORDER_PREFIX : "ORD";
- $max = 0;
- $pattern = "/^" . preg_quote($prefix, "/") . '-\d{4}-(\d+)$/';
- foreach ($orders as $order) {
- if (preg_match($pattern, (string) $order["id"], $matches) === 1) {
- $number = (int) $matches[1];
- if ($number > $max) {
- $max = $number;
- }
- }
- }
- return sprintf("%s-%s-%03d", $prefix, $year, $max + 1);
- }
- function normalizeOrderRecord($order)
- {
- if (!is_array($order)) {
- return null;
- }
- $id = trim((string) ($order["id"] ?? ""));
- $customerName = trim((string) ($order["customer_name"] ?? ""));
- $customerEmail = normalizeAdminEmail($order["customer_email"] ?? "");
- $organizationId = normalizeOrganizationId($order["organization_id"] ?? "");
- $organizationLabel = trim((string) ($order["organization_label"] ?? ""));
- $items = normalizeOrderItems($order["items"] ?? []);
- if (
- $id === "" ||
- $customerName === "" ||
- !isValidAdminEmail($customerEmail) ||
- $organizationId === "" ||
- $organizationLabel === "" ||
- empty($items)
- ) {
- return null;
- }
- $createdAt = trim((string) ($order["created_at"] ?? ""));
- if ($createdAt === "") {
- $createdAt = date("Y-m-d H:i:s");
- }
- $confirmationStatus = trim(
- (string) ($order["confirmation_status"] ?? "confirmed"),
- );
- $allowedConfirmationStatuses = [
- "not_required",
- "pending",
- "confirmed",
- "expired",
- ];
- if (!in_array($confirmationStatus, $allowedConfirmationStatuses, true)) {
- $confirmationStatus = "confirmed";
- }
- $status = trim((string) ($order["status"] ?? "open"));
- $allowedStatuses = ["open", "partial", "processed", "cancelled"];
- if (!in_array($status, $allowedStatuses, true)) {
- $status = "open";
- }
- $normalized = [
- "id" => $id,
- "customer_name" => $customerName,
- "customer_email" => $customerEmail,
- "organization_id" => $organizationId,
- "organization_label" => $organizationLabel,
- "comment" => trim((string) ($order["comment"] ?? "")),
- "items" => $items,
- "status" => $status,
- "confirmation_status" => $confirmationStatus,
- "confirmation_token" => trim(
- (string) ($order["confirmation_token"] ?? ""),
- ),
- "confirmation_expires_at" => trim(
- (string) ($order["confirmation_expires_at"] ?? ""),
- ),
- "confirmed_at" => trim((string) ($order["confirmed_at"] ?? "")),
- "created_at" => $createdAt,
- "updated_at" => trim((string) ($order["updated_at"] ?? $createdAt)),
- "cancelled_at" => trim((string) ($order["cancelled_at"] ?? "")),
- "cancelled_by" => trim((string) ($order["cancelled_by"] ?? "")),
- "cancellation_reason" => trim(
- (string) ($order["cancellation_reason"] ?? ""),
- ),
- "admin_notified_at" => trim(
- (string) ($order["admin_notified_at"] ?? ""),
- ),
- ];
- return refreshOrderState($normalized);
- }
- function refreshOrderState($order)
- {
- if (!is_array($order)) {
- return null;
- }
- if (($order["status"] ?? "") === "cancelled") {
- return $order;
- }
- if (
- ($order["confirmation_status"] ?? "") === "pending" &&
- !empty($order["confirmation_expires_at"])
- ) {
- $expiresAt = strtotime((string) $order["confirmation_expires_at"]);
- if ($expiresAt !== false && time() > $expiresAt) {
- $order["confirmation_status"] = "expired";
- }
- }
- $processedCount = 0;
- foreach ($order["items"] as $item) {
- if (!empty($item["is_processed"])) {
- $processedCount++;
- }
- }
- if ($processedCount <= 0) {
- $order["status"] = "open";
- } elseif ($processedCount >= count($order["items"])) {
- $order["status"] = "processed";
- } else {
- $order["status"] = "partial";
- }
- return $order;
- }
- function expirePendingOrders()
- {
- $orders = getOrders();
- $changed = false;
- foreach ($orders as &$order) {
- $updated = refreshOrderState($order);
- if ($updated !== $order) {
- $order = $updated;
- $changed = true;
- }
- }
- unset($order);
- if ($changed) {
- saveOrders($orders);
- }
- }
- function getOrderById($orderId)
- {
- $orderId = trim((string) $orderId);
- if ($orderId === "") {
- return null;
- }
- foreach (getOrders() as $order) {
- if ($order["id"] === $orderId) {
- return $order;
- }
- }
- return null;
- }
- function findOrderByConfirmationToken($token)
- {
- $token = trim((string) $token);
- if ($token === "") {
- return null;
- }
- foreach (getOrders() as $order) {
- if (($order["confirmation_token"] ?? "") === $token) {
- return $order;
- }
- }
- return null;
- }
- function buildOrderConfirmationUrl($token)
- {
- $path = "/order-confirm.php?token=" . urlencode($token);
- return buildAbsoluteUrl($path);
- }
- function buildAbsoluteUrl($path)
- {
- $path = "/" . ltrim((string) $path, "/");
- $siteUrl = defined("SITE_URL") ? trim((string) SITE_URL) : "";
- if (strpos($siteUrl, "://") !== false) {
- return rtrim($siteUrl, "/") . $path;
- }
- $basePath = trim($siteUrl);
- if ($basePath !== "" && $basePath !== "/") {
- $path = "/" . trim($basePath, "/") . $path;
- }
- $scheme = isHttpsRequest() ? "https" : "http";
- $host = $_SERVER["HTTP_HOST"] ?? "";
- if ($host === "") {
- return $path;
- }
- return $scheme . "://" . $host . $path;
- }
- function isHttpsRequest(): bool
- {
- if (
- !empty($_SERVER["HTTPS"]) &&
- strtolower((string) $_SERVER["HTTPS"]) !== "off"
- ) {
- return true;
- }
- if (
- !empty($_SERVER["HTTP_X_FORWARDED_PROTO"]) &&
- strtolower((string) $_SERVER["HTTP_X_FORWARDED_PROTO"]) === "https"
- ) {
- return true;
- }
- if (
- !empty($_SERVER["SERVER_PORT"]) &&
- (int) $_SERVER["SERVER_PORT"] === 443
- ) {
- return true;
- }
- return false;
- }
- function createOrder(
- $customerName,
- $customerEmail,
- $organizationId,
- $comment,
- $items,
- ) {
- $customerName = sanitize($customerName);
- $customerEmail = normalizeAdminEmail($customerEmail);
- $organizationId = normalizeOrganizationId($organizationId);
- $comment = trim((string) $comment);
- $items = normalizeOrderItems($items);
- if ($customerName === "") {
- return [
- "success" => false,
- "message" => "Bitte geben Sie einen Namen ein.",
- ];
- }
- if (!isValidAdminEmail($customerEmail)) {
- return [
- "success" => false,
- "message" => "Bitte geben Sie eine gültige E-Mail-Adresse ein.",
- ];
- }
- if (empty($items)) {
- return [
- "success" => false,
- "message" =>
- "Der Warenkorb ist leer oder enthält ungültige Positionen.",
- ];
- }
- $organization = getOrganizationById($organizationId);
- if ($organization === null || empty($organization["active"])) {
- return [
- "success" => false,
- "message" => "Bitte wählen Sie eine gültige Organisation aus.",
- ];
- }
- $now = date("Y-m-d H:i:s");
- $requiresConfirmation = isOrderConfirmationRequired();
- $confirmationToken = $requiresConfirmation ? bin2hex(random_bytes(24)) : "";
- $confirmationExpiresAt = "";
- if ($requiresConfirmation) {
- $expires = new DateTimeImmutable();
- $expires = $expires->modify(
- "+" . getOrderConfirmationExpiryDays() . " days",
- );
- $confirmationExpiresAt = $expires->format("Y-m-d H:i:s");
- }
- $order = [
- "id" => generateOrderId(),
- "customer_name" => $customerName,
- "customer_email" => $customerEmail,
- "organization_id" => $organization["id"],
- "organization_label" => $organization["label"],
- "comment" => $comment,
- "items" => $items,
- "status" => "open",
- "confirmation_status" => $requiresConfirmation
- ? "pending"
- : "not_required",
- "confirmation_token" => $confirmationToken,
- "confirmation_expires_at" => $confirmationExpiresAt,
- "confirmed_at" => $requiresConfirmation ? "" : $now,
- "created_at" => $now,
- "updated_at" => $now,
- "cancelled_at" => "",
- "cancelled_by" => "",
- "cancellation_reason" => "",
- "admin_notified_at" => "",
- ];
- $orders = getOrders();
- $orders[] = $order;
- saveOrders($orders);
- logAccess("Order created in createOrder", [
- "order_id" => $order["id"],
- "customer" => $customerEmail,
- "organization" => $organization["label"],
- ]);
- if ($requiresConfirmation) {
- sendOrderConfirmationRequestEmail($order);
- } else {
- $result = sendConfirmedOrderAdminNotification($order);
- if ($result) {
- markOrderAdminNotified($order["id"]);
- $order = getOrderById($order["id"]);
- }
- sendOrderCreatedCustomerEmail($order);
- }
- return ["success" => true, "order" => $order];
- }
- function markOrderAdminNotified($orderId)
- {
- $orders = getOrders();
- foreach ($orders as &$order) {
- if ($order["id"] !== $orderId) {
- continue;
- }
- $order["admin_notified_at"] = date("Y-m-d H:i:s");
- $order["updated_at"] = date("Y-m-d H:i:s");
- break;
- }
- unset($order);
- saveOrders($orders);
- }
- function confirmOrderByToken($token)
- {
- $orders = getOrders();
- $now = date("Y-m-d H:i:s");
- foreach ($orders as &$order) {
- if (($order["confirmation_token"] ?? "") !== $token) {
- continue;
- }
- $order = refreshOrderState($order);
- if ($order["status"] === "cancelled") {
- return [
- "success" => false,
- "message" =>
- "Diese Bestellung wurde storniert und kann nicht mehr bestätigt werden.",
- ];
- }
- if ($order["confirmation_status"] === "confirmed") {
- return [
- "success" => false,
- "message" => "Diese Bestellung wurde bereits bestätigt.",
- ];
- }
- if ($order["confirmation_status"] === "expired") {
- return [
- "success" => false,
- "message" => "Der Bestätigungslink ist abgelaufen.",
- ];
- }
- if ($order["confirmation_status"] !== "pending") {
- return [
- "success" => false,
- "message" =>
- "Für diese Bestellung ist keine Bestätigung erforderlich.",
- ];
- }
- $expiresAt = strtotime((string) $order["confirmation_expires_at"]);
- if ($expiresAt !== false && time() > $expiresAt) {
- $order["confirmation_status"] = "expired";
- $order["updated_at"] = $now;
- saveOrders($orders);
- return [
- "success" => false,
- "message" => "Der Bestätigungslink ist abgelaufen.",
- ];
- }
- $order["confirmation_status"] = "confirmed";
- $order["confirmed_at"] = $now;
- $order["updated_at"] = $now;
- saveOrders($orders);
- $sent = sendConfirmedOrderAdminNotification($order);
- if ($sent) {
- markOrderAdminNotified($order["id"]);
- }
- sendOrderConfirmedCustomerEmail(getOrderById($order["id"]));
- return ["success" => true, "order" => getOrderById($order["id"])];
- }
- unset($order);
- return ["success" => false, "message" => "Bestellung nicht gefunden."];
- }
- function toggleOrderItemProcessed($orderId, $itemIndex)
- {
- $orders = getOrders();
- $now = date("Y-m-d H:i:s");
- foreach ($orders as &$order) {
- if ($order["id"] !== $orderId) {
- continue;
- }
- if ($order["status"] === "cancelled") {
- return [
- "success" => false,
- "message" =>
- "Stornierte Bestellungen können nicht mehr bearbeitet werden.",
- ];
- }
- if (($order["confirmation_status"] ?? "") === "pending") {
- return [
- "success" => false,
- "message" =>
- "Unbestätigte Bestellungen können noch nicht bearbeitet werden.",
- ];
- }
- if (($order["confirmation_status"] ?? "") === "expired") {
- return [
- "success" => false,
- "message" =>
- "Abgelaufene unbestätigte Bestellungen können nicht bearbeitet werden.",
- ];
- }
- if (!isset($order["items"][$itemIndex])) {
- return [
- "success" => false,
- "message" => "Position nicht gefunden.",
- ];
- }
- $order["items"][$itemIndex]["is_processed"] = empty(
- $order["items"][$itemIndex]["is_processed"]
- );
- $order["updated_at"] = $now;
- $order = refreshOrderState($order);
- saveOrders($orders);
- return ["success" => true, "order" => $order];
- }
- unset($order);
- return ["success" => false, "message" => "Bestellung nicht gefunden."];
- }
- function cancelOrder($orderId, $adminUsername, $reason = "")
- {
- $orders = getOrders();
- $now = date("Y-m-d H:i:s");
- $adminUsername = normalizeAdminUsername($adminUsername);
- $reason = trim((string) $reason);
- foreach ($orders as &$order) {
- if ($order["id"] !== $orderId) {
- continue;
- }
- if ($order["status"] === "cancelled") {
- return [
- "success" => false,
- "message" => "Die Bestellung ist bereits storniert.",
- ];
- }
- $order["status"] = "cancelled";
- $order["cancelled_at"] = $now;
- $order["cancelled_by"] = $adminUsername;
- $order["cancellation_reason"] = $reason;
- $order["updated_at"] = $now;
- saveOrders($orders);
- return ["success" => true, "order" => $order];
- }
- unset($order);
- return ["success" => false, "message" => "Bestellung nicht gefunden."];
- }
- function getOrderStatusLabel($order)
- {
- if (($order["status"] ?? "") === "cancelled") {
- return "Storniert";
- }
- if (($order["confirmation_status"] ?? "") === "pending") {
- return "Unbestätigt";
- }
- if (($order["confirmation_status"] ?? "") === "expired") {
- return "Bestätigung abgelaufen";
- }
- if (($order["status"] ?? "") === "processed") {
- return "Bearbeitet";
- }
- if (($order["status"] ?? "") === "partial") {
- return "Teilweise bearbeitet";
- }
- return "Offen";
- }
- function getOrderStatusClass($order)
- {
- if (($order["status"] ?? "") === "cancelled") {
- return "status-cancelled";
- }
- if (($order["confirmation_status"] ?? "") === "pending") {
- return "status-unconfirmed";
- }
- if (($order["confirmation_status"] ?? "") === "expired") {
- return "status-expired";
- }
- if (($order["status"] ?? "") === "processed") {
- return "status-processed";
- }
- if (($order["status"] ?? "") === "partial") {
- return "status-partial";
- }
- return "status-open";
- }
- function formatDate($dateString)
- {
- $dateString = trim((string) $dateString);
- if ($dateString === "") {
- return "-";
- }
- try {
- $date = new DateTimeImmutable($dateString);
- return $date->format("d.m.Y H:i");
- } catch (Exception $exception) {
- return $dateString;
- }
- }
- function getCart()
- {
- $cart = $_SESSION["cart"] ?? [];
- if (!is_array($cart)) {
- $cart = [];
- }
- $normalized = [];
- foreach ($cart as $item) {
- $productId = isset($item["product_id"]) ? (int) $item["product_id"] : 0;
- $size = trim((string) ($item["size"] ?? ""));
- $product = getProductById($productId);
- if ($product === null) {
- continue;
- }
- $sizes = getProductSizes($product);
- if (!empty($sizes)) {
- if ($size === "" || !in_array($size, $sizes, true)) {
- continue;
- }
- } else {
- $size = "";
- }
- if (isset($normalized[$productId])) {
- unset($normalized[$productId]);
- }
- $normalized[$productId] = [
- "product_id" => $productId,
- "size" => $size,
- ];
- }
- $_SESSION["cart"] = array_values($normalized);
- return $_SESSION["cart"];
- }
- function addCartItem($productId, $size = "")
- {
- $productId = (int) $productId;
- $size = trim((string) $size);
- $product = getProductById($productId);
- if ($product === null) {
- return [
- "success" => false,
- "status" => "error",
- ];
- }
- $sizes = getProductSizes($product);
- if (!empty($sizes)) {
- if ($size === "" || !in_array($size, $sizes, true)) {
- return [
- "success" => false,
- "status" => "error",
- ];
- }
- } else {
- $size = "";
- }
- $cart = getCart();
- foreach ($cart as $index => $item) {
- if ((int) $item["product_id"] !== $productId) {
- continue;
- }
- $existingSize = trim((string) ($item["size"] ?? ""));
- if ($existingSize === $size) {
- return [
- "success" => true,
- "status" => "unchanged",
- "size" => $size,
- ];
- }
- $cart[$index]["size"] = $size;
- $_SESSION["cart"] = array_values($cart);
- return [
- "success" => true,
- "status" => "replaced",
- "size" => $size,
- "previous_size" => $existingSize,
- ];
- }
- $cart[] = [
- "product_id" => $productId,
- "size" => $size,
- ];
- $_SESSION["cart"] = array_values($cart);
- return [
- "success" => true,
- "status" => "added",
- "size" => $size,
- ];
- }
- function removeCartItemByIndex($index)
- {
- $cart = getCart();
- if (isset($cart[$index])) {
- unset($cart[$index]);
- $_SESSION["cart"] = array_values($cart);
- }
- }
- function clearCart()
- {
- $_SESSION["cart"] = [];
- }
- function getCartItemsDetailed()
- {
- $items = [];
- foreach (getCart() as $index => $cartItem) {
- $product = getProductById($cartItem["product_id"]);
- if ($product === null) {
- continue;
- }
- $size = trim((string) ($cartItem["size"] ?? ""));
- $items[] = [
- "cart_index" => $index,
- "product" => $product,
- "size" => $size,
- "availability_label" =>
- $size !== "" ? getAvailabilityLabel($product, $size) : "",
- ];
- }
- return $items;
- }
- function buildOrderItemsFromCart()
- {
- $items = [];
- foreach (getCart() as $cartItem) {
- $product = getProductById($cartItem["product_id"]);
- if ($product === null) {
- continue;
- }
- $size = trim((string) ($cartItem["size"] ?? ""));
- $items[] = [
- "product_id" => $product["id"],
- "size" => $size,
- "is_processed" => false,
- ];
- }
- return normalizeOrderItems($items);
- }
- function buildOrderItemsHtml($order)
- {
- $parts = [];
- foreach ($order["items"] as $item) {
- $label = "<strong>" . escape($item["product_name"]) . "</strong>";
- if ($item["size"] !== "") {
- $label .= " - Größe: " . escape($item["size"]);
- }
- if (!empty($item["availability_label"])) {
- $label .=
- "<br><small>" .
- nl2br(escape($item["availability_label"])) .
- "</small>";
- }
- $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>";
- }
- return '<ul style="list-style: none; margin: 0; padding: 0;">' .
- implode("", $parts) .
- "</ul>";
- }
- function buildOrderSummaryHtml($order, $title, $introHtml, $extraHtml = "")
- {
- $itemsHtml = buildOrderItemsHtml($order);
- return '
- <html>
- <head>
- <meta charset="UTF-8">
- </head>
- <body style="font-family: \'Freising Sans\', Arial, sans-serif; line-height: 1.6; color: #111111; background: #f4efe1; padding: 1.5rem;">
- <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);">
- <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>
- <h1 style="margin: 0; font-size: 1.75rem; line-height: 1.2; color: #111111;">' .
- escape(SITE_NAME) .
- '</h1>
- <p style="margin: 0.25rem 0 1.5rem; font-size: 1rem; color: #5e5a4d;">' .
- escape(SITE_SERVICE_HEADER) .
- '</p>
- <div style="width: 80px; height: 6px; border-radius: 999px; background: #ffd71c; margin-bottom: 1.5rem;"></div>
- <h2 style="color: #111111; margin-top: 0;">' .
- escape($title) .
- '</h2>
- ' .
- $introHtml .
- '
- <div style="background: #f8f4e7; border: 2px solid #ffd71c; padding: 1.5rem; margin: 1.5rem 0; border-radius: 20px;">
- <h3 style="margin-top: 0;">Bestellnummer</h3>
- <p style="margin: 0; color: #111111; font-family: monospace; font-size: 1.05rem;">' .
- escape($order["id"]) .
- '</p>
- </div>
- <p><strong>Name:</strong> ' .
- escape($order["customer_name"]) .
- '</p>
- <p><strong>E-Mail:</strong> ' .
- escape($order["customer_email"]) .
- '</p>
- <p><strong>Organisation:</strong> ' .
- escape($order["organization_label"]) .
- '</p>
- <p><strong>Erstellt am:</strong> ' .
- escape(formatDate($order["created_at"])) .
- '</p>
- <h3>Bestellte Artikel</h3>
- <div style="background: #fffdf6; border: 1px solid #d7ceb5; border-left: 6px solid #ffd71c; border-radius: 20px; padding: 1rem;">' .
- $itemsHtml .
- '</div>
- <p><strong>Kommentar:</strong><br>' .
- ($order["comment"] !== ""
- ? nl2br(escape($order["comment"]))
- : "Kein Kommentar") .
- '</p>
- ' .
- $extraHtml .
- '
- <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>
- </div>
- </body>
- </html>';
- }
- function sendOrderConfirmationRequestEmail($order)
- {
- $subject = SITE_SERVICE_NAME . ": Bestellung bestätigen - " . $order["id"];
- $link = buildOrderConfirmationUrl($order["confirmation_token"]);
- $expiryText = formatDate($order["confirmation_expires_at"]);
- $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>";
- $extra =
- '
- <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>
- <p>Der Link ist gültig bis: <strong>' .
- escape($expiryText) .
- '</strong></p>
- <p>Falls der Button nicht funktioniert, verwenden Sie bitte diesen Link:<br>' .
- escape($link) .
- "</p>";
- $message = buildOrderSummaryHtml(
- $order,
- "Bestellung bestätigen",
- $intro,
- $extra,
- );
- return sendEmail($order["customer_email"], $subject, $message);
- }
- function sendOrderCreatedCustomerEmail($order)
- {
- $subject = SITE_SERVICE_NAME . ": Ihre Bestellung - " . $order["id"];
- $intro =
- "<p>Guten Tag " .
- escape($order["customer_name"]) .
- ",</p><p>Ihre Bestellung wurde erfasst und an " .
- escape(SITE_DEPARTMENT_NAME) .
- " weitergeleitet.</p>";
- $message = buildOrderSummaryHtml($order, "Bestellung eingegangen", $intro);
- return sendEmail($order["customer_email"], $subject, $message);
- }
- function sendOrderConfirmedCustomerEmail($order)
- {
- $subject = SITE_SERVICE_NAME . ": Bestellung bestätigt - " . $order["id"];
- $intro =
- "<p>Guten Tag " .
- escape($order["customer_name"]) .
- ",</p><p>Ihre Bestellung wurde bestätigt und an " .
- escape(SITE_DEPARTMENT_NAME) .
- " weitergeleitet.</p>";
- $message = buildOrderSummaryHtml($order, "Bestellung bestätigt", $intro);
- return sendEmail($order["customer_email"], $subject, $message);
- }
- function sendConfirmedOrderAdminNotification($order)
- {
- $recipient = getOrderRecipientEmail();
- if (!isValidAdminEmail($recipient)) {
- return false;
- }
- $subject = SITE_SERVICE_NAME . ": Neue Bestellung - " . $order["id"];
- $intro =
- "<p>Eine neue PSA-Bestellung wurde freigegeben und muss bearbeitet werden.</p>";
- $message = buildOrderSummaryHtml($order, "Neue PSA-Bestellung", $intro);
- $attachments = [];
- if (shouldAttachOrderPdfToAdminEmail()) {
- $attachments[] = [
- "filename" => "bestellung-" . strtolower($order["id"]) . ".pdf",
- "content_type" => "application/pdf",
- "content" => generateOrderPdf($order),
- ];
- }
- return sendEmail($recipient, $subject, $message, true, $attachments);
- }
- function sendEmail($to, $subject, $message, $isHtml = true, $attachments = [])
- {
- $headers = [];
- $headers[] = "From: " . FROM_NAME . " <" . FROM_EMAIL . ">";
- $headers[] = "Reply-To: " . FROM_EMAIL;
- $headers[] = "X-Mailer: PHP/" . phpversion();
- if (empty($attachments)) {
- if ($isHtml) {
- $headers[] = "MIME-Version: 1.0";
- $headers[] = "Content-Type: text/html; charset=UTF-8";
- } else {
- $headers[] = "Content-Type: text/plain; charset=UTF-8";
- }
- return mail($to, $subject, $message, implode("\r\n", $headers));
- }
- $boundary = "=_Boundary_" . bin2hex(random_bytes(8));
- $headers[] = "MIME-Version: 1.0";
- $headers[] = 'Content-Type: multipart/mixed; boundary="' . $boundary . '"';
- $body = [];
- $body[] = "--" . $boundary;
- $body[] =
- "Content-Type: " .
- ($isHtml ? "text/html" : "text/plain") .
- "; charset=UTF-8";
- $body[] = "Content-Transfer-Encoding: 8bit";
- $body[] = "";
- $body[] = $message;
- foreach ($attachments as $attachment) {
- if (!is_array($attachment)) {
- continue;
- }
- $filename = trim(
- (string) ($attachment["filename"] ?? "attachment.bin"),
- );
- $contentType = trim(
- (string) ($attachment["content_type"] ??
- "application/octet-stream"),
- );
- $content = isset($attachment["content"])
- ? (string) $attachment["content"]
- : "";
- $body[] = "--" . $boundary;
- $body[] =
- "Content-Type: " . $contentType . '; name="' . $filename . '"';
- $body[] = "Content-Transfer-Encoding: base64";
- $body[] =
- 'Content-Disposition: attachment; filename="' . $filename . '"';
- $body[] = "";
- $body[] = chunk_split(base64_encode($content));
- }
- $body[] = "--" . $boundary . "--";
- $body[] = "";
- return mail(
- $to,
- $subject,
- implode("\r\n", $body),
- implode("\r\n", $headers),
- );
- }
- function pdfEncodeWinAnsi($text)
- {
- $text = str_replace("\r", "", (string) $text);
- if (!function_exists("iconv")) {
- return preg_replace('/[^\x09\x0A\x20-\x7E]/', "?", $text);
- }
- $chars = preg_split("//u", $text, -1, PREG_SPLIT_NO_EMPTY);
- if (!is_array($chars)) {
- $fallback = @iconv("UTF-8", "Windows-1252//TRANSLIT//IGNORE", $text);
- return is_string($fallback) ? $fallback : $text;
- }
- $result = "";
- foreach ($chars as $char) {
- $converted = @iconv("UTF-8", "Windows-1252", $char);
- if ($converted !== false) {
- $result .= $converted;
- continue;
- }
- $fallback = @iconv("UTF-8", "Windows-1252//TRANSLIT", $char);
- if ($fallback !== false && $fallback !== "") {
- $result .= $fallback;
- continue;
- }
- $result .= "?";
- }
- return $result;
- }
- function pdfEscapeText($text)
- {
- $text = str_replace("\\", "\\\\", $text);
- $text = str_replace("(", "\(", $text);
- $text = str_replace(")", "\)", $text);
- return preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', "", $text);
- }
- function pdfWrapAnsiText($text, $maxChars)
- {
- $lines = [];
- $paragraphs = explode("\n", str_replace("\r", "", (string) $text));
- foreach ($paragraphs as $paragraph) {
- $normalized = trim(preg_replace("/\s+/", " ", $paragraph));
- if ($normalized === "") {
- $lines[] = "";
- continue;
- }
- $words = explode(" ", $normalized);
- $current = "";
- foreach ($words as $word) {
- if ($word === "") {
- continue;
- }
- if (strlen($word) > $maxChars) {
- if ($current !== "") {
- $lines[] = $current;
- $current = "";
- }
- $parts = str_split($word, $maxChars);
- $lastIndex = count($parts) - 1;
- for ($i = 0; $i < $lastIndex; $i++) {
- $lines[] = $parts[$i];
- }
- $current = $parts[$lastIndex];
- continue;
- }
- $candidate = $current === "" ? $word : $current . " " . $word;
- if (strlen($candidate) <= $maxChars) {
- $current = $candidate;
- } else {
- if ($current !== "") {
- $lines[] = $current;
- }
- $current = $word;
- }
- }
- if ($current !== "") {
- $lines[] = $current;
- }
- }
- if (empty($lines)) {
- $lines[] = "";
- }
- return $lines;
- }
- function generateOrderPdf($order)
- {
- $pageWidth = 595;
- $pageHeight = 842;
- $leftMargin = 45;
- $rightMargin = 45;
- $topY = 800;
- $bottomY = 55;
- $lineHeight = 14;
- $orderId = pdfEncodeWinAnsi($order["id"]);
- $createdAt = pdfEncodeWinAnsi(formatDate($order["created_at"]));
- $customerName = pdfEncodeWinAnsi($order["customer_name"]);
- $customerEmail = pdfEncodeWinAnsi($order["customer_email"]);
- $organization = pdfEncodeWinAnsi($order["organization_label"]);
- $comment = pdfEncodeWinAnsi($order["comment"]);
- $labelBelongsTo = pdfEncodeWinAnsi("Gehört zu");
- $labelSize = pdfEncodeWinAnsi("Größe");
- $labelFullyIssued = pdfEncodeWinAnsi("Vollständig ausgegeben");
- $pages = [];
- $pageContent = "";
- $y = $topY;
- $isFirstPage = true;
- $writeText = function ($x, $y, $text, $fontSize = 12) use (&$pageContent) {
- $pageContent .=
- "BT\n/F1 " .
- $fontSize .
- " Tf\n1 0 0 1 " .
- number_format($x, 2, ".", "") .
- " " .
- number_format($y, 2, ".", "") .
- " Tm\n(" .
- pdfEscapeText($text) .
- ") Tj\nET\n";
- };
- $drawLine = function ($x1, $y1, $x2, $y2) use (&$pageContent) {
- $pageContent .=
- number_format($x1, 2, ".", "") .
- " " .
- number_format($y1, 2, ".", "") .
- " m " .
- number_format($x2, 2, ".", "") .
- " " .
- number_format($y2, 2, ".", "") .
- " l S\n";
- };
- $drawRect = function ($x, $y, $width, $height) use (&$pageContent) {
- $pageContent .=
- number_format($x, 2, ".", "") .
- " " .
- number_format($y, 2, ".", "") .
- " " .
- number_format($width, 2, ".", "") .
- " " .
- number_format($height, 2, ".", "") .
- " re S\n";
- };
- $startPage = function () use (
- &$pages,
- &$pageContent,
- &$y,
- &$isFirstPage,
- $topY,
- $leftMargin,
- $pageWidth,
- $rightMargin,
- $orderId,
- $createdAt,
- $customerName,
- $customerEmail,
- $organization,
- $labelBelongsTo,
- $writeText,
- $drawLine
- ) {
- if ($pageContent !== "") {
- $pages[] = $pageContent;
- }
- $pageContent = "";
- $y = $topY;
- $leftTitle = pdfEncodeWinAnsi(SITE_FULL_NAME);
- $leftDepartment = pdfEncodeWinAnsi(SITE_DEPARTMENT_NAME);
- $leftService = pdfEncodeWinAnsi(SITE_SERVICE_HEADER);
- $writeText($leftMargin, $y, $leftTitle, 16);
- $y -= 18;
- $writeText($leftMargin, $y, $leftDepartment, 11);
- $y -= 14;
- $writeText($leftMargin, $y, $leftService, 11);
- $writeText(350, $topY, "BESTELLUNG", 11);
- $writeText(350, $topY - 22, "ID " . $orderId, 20);
- $writeText(350, $topY - 44, "Erstellt am: " . $createdAt, 11);
- $y = $topY - 62;
- $drawLine($leftMargin, $y, $pageWidth - $rightMargin, $y);
- $y -= 18;
- if ($isFirstPage) {
- $writeText($leftMargin, $y, $labelBelongsTo, 11);
- $y -= 18;
- $belongsFields = [
- "Name: " . $customerName,
- "Organisation: " . $organization,
- "E-Mail: " . $customerEmail,
- ];
- foreach ($belongsFields as $fieldLine) {
- foreach (pdfWrapAnsiText($fieldLine, 70) as $wrappedLine) {
- $writeText($leftMargin, $y, $wrappedLine, 12);
- $y -= 16;
- }
- }
- $y -= 2;
- $drawLine($leftMargin, $y, $pageWidth - $rightMargin, $y);
- $y -= 18;
- $isFirstPage = false;
- } else {
- $writeText($leftMargin, $y, "Fortsetzung Bestellung " . $orderId, 11);
- $y -= 20;
- }
- };
- $ensureSpace = function ($requiredHeight) use (&$y, $bottomY, $startPage) {
- if ($y - $requiredHeight < $bottomY) {
- $startPage();
- }
- };
- $drawItemTableHeader = function () use (
- &$y,
- $lineHeight,
- $leftMargin,
- $writeText,
- $labelSize,
- $drawLine,
- $pageWidth,
- $rightMargin
- ) {
- $writeText($leftMargin, $y, "Nr.", 11);
- $writeText(75, $y, "Artikel", 11);
- $writeText(340, $y, $labelSize, 11);
- $writeText(430, $y, "Hinweis", 11);
- $y -= $lineHeight;
- $drawLine($leftMargin, $y + 4, $pageWidth - $rightMargin, $y + 4);
- };
- $startPage();
- $ensureSpace(36);
- $writeText($leftMargin, $y, "Artikelliste", 13);
- $y -= 20;
- $drawItemTableHeader();
- $itemNumber = 1;
- foreach ($order["items"] as $item) {
- $itemName = pdfEncodeWinAnsi($item["product_name"]);
- $sizeLabel = pdfEncodeWinAnsi($item["size"]);
- $hintLabel = pdfEncodeWinAnsi(
- preg_replace("/\s+/", " ", (string) $item["availability_label"]),
- );
- $itemLines = pdfWrapAnsiText($itemName, 40);
- $sizeLines = pdfWrapAnsiText($sizeLabel, 12);
- $hintLines = pdfWrapAnsiText($hintLabel, 22);
- $lineCount = max(count($itemLines), count($sizeLines), count($hintLines));
- $rowHeight = $lineCount * $lineHeight + 4;
- if ($y - $rowHeight < $bottomY) {
- $startPage();
- $ensureSpace(30);
- $writeText($leftMargin, $y, "Artikelliste (Fortsetzung)", 13);
- $y -= 20;
- $drawItemTableHeader();
- }
- $rowTop = $y;
- $writeText($leftMargin, $rowTop, (string) $itemNumber, 11);
- for ($i = 0; $i < $lineCount; $i++) {
- if (isset($itemLines[$i])) {
- $writeText(75, $rowTop - $i * $lineHeight, $itemLines[$i], 11);
- }
- if (isset($sizeLines[$i])) {
- $writeText(340, $rowTop - $i * $lineHeight, $sizeLines[$i], 11);
- }
- if (isset($hintLines[$i])) {
- $writeText(430, $rowTop - $i * $lineHeight, $hintLines[$i], 11);
- }
- }
- $y -= $rowHeight;
- $drawLine($leftMargin, $y + 4, $pageWidth - $rightMargin, $y + 4);
- $y -= 4;
- $itemNumber++;
- }
- $commentSource = trim($comment) !== "" ? $comment : "Kein Kommentar";
- $commentLines = [];
- foreach (preg_split('/\r\n|\r|\n/', $commentSource) as $commentPart) {
- $wrapped = pdfWrapAnsiText($commentPart, 92);
- foreach ($wrapped as $line) {
- $commentLines[] = $line;
- }
- }
- $ensureSpace(40);
- $y -= 8;
- $writeText($leftMargin, $y, "Kommentar", 13);
- $y -= 18;
- foreach ($commentLines as $line) {
- if ($y - $lineHeight < $bottomY) {
- $startPage();
- $ensureSpace(34);
- $writeText($leftMargin, $y, "Kommentar (Fortsetzung)", 13);
- $y -= 18;
- }
- $writeText($leftMargin, $y, $line, 11);
- $y -= $lineHeight;
- }
- $footerHeight = 96;
- $ensureSpace($footerHeight + 10);
- $y -= 12;
- $drawLine($leftMargin, $y + 8, $pageWidth - $rightMargin, $y + 8);
- $writeText($leftMargin, $y, "Lagerbearbeitung", 13);
- $y -= 18;
- $writeText($leftMargin, $y, "Ausgegeben am: ____________________", 11);
- $y -= 20;
- $writeText($leftMargin, $y, "Ausgegeben durch: ____________________", 11);
- $y -= 20;
- $writeText($leftMargin, $y, "Unterschrift: ________________________", 11);
- $y -= 22;
- $drawRect($leftMargin, $y - 8, 10, 10);
- $writeText($leftMargin + 16, $y, $labelFullyIssued, 11);
- $y -= 18;
- $drawRect($leftMargin, $y - 8, 10, 10);
- $writeText($leftMargin + 16, $y, "Teilweise ausgegeben", 11);
- if ($pageContent !== "") {
- $pages[] = $pageContent;
- }
- if (empty($pages)) {
- $pages[] = "";
- }
- $fontObjectNumber = 3;
- $objects = [];
- $objects[1] = "1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n";
- $objects[
- $fontObjectNumber
- ] = "3 0 obj\n<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>\nendobj\n";
- $kids = [];
- $nextObjectNumber = 4;
- foreach ($pages as $pageStream) {
- $pageObjectNumber = $nextObjectNumber++;
- $contentObjectNumber = $nextObjectNumber++;
- $kids[] = $pageObjectNumber . " 0 R";
- $objects[$pageObjectNumber] =
- $pageObjectNumber .
- " 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 " .
- $pageWidth .
- " " .
- $pageHeight .
- "] /Contents " .
- $contentObjectNumber .
- " 0 R /Resources << /Font << /F1 " .
- $fontObjectNumber .
- " 0 R >> >> >>\nendobj\n";
- $objects[$contentObjectNumber] =
- $contentObjectNumber .
- " 0 obj\n<< /Length " .
- strlen($pageStream) .
- " >>\nstream\n" .
- $pageStream .
- "\nendstream\nendobj\n";
- }
- $objects[2] =
- "2 0 obj\n<< /Type /Pages /Kids [" .
- implode(" ", $kids) .
- "] /Count " .
- count($kids) .
- " >>\nendobj\n";
- ksort($objects);
- $pdf = "%PDF-1.4\n";
- $offsets = [0];
- foreach ($objects as $number => $objectContent) {
- $offsets[$number] = strlen($pdf);
- $pdf .= $objectContent;
- }
- $lastObjectNumber = (int) max(array_keys($objects));
- $xrefOffset = strlen($pdf);
- $pdf .= "xref\n0 " . ($lastObjectNumber + 1) . "\n";
- $pdf .= "0000000000 65535 f \n";
- for ($i = 1; $i <= $lastObjectNumber; $i++) {
- if (isset($offsets[$i])) {
- $pdf .= sprintf("%010d 00000 n \n", $offsets[$i]);
- } else {
- $pdf .= "0000000000 00000 f \n";
- }
- }
- $pdf .= "trailer\n<< /Size " . ($lastObjectNumber + 1) . " /Root 1 0 R >>\n";
- $pdf .= "startxref\n" . $xrefOffset . "\n%%EOF";
- return $pdf;
- }
- /**
- * Input Validation Class
- */
- class Validator
- {
- private $errors = [];
- private $data = [];
- public function __construct($data)
- {
- $this->data = $data;
- }
- public function required($field, $label = null)
- {
- $value = $this->get($field);
- if (empty(trim($value ?? ""))) {
- $this->errors[] = ($label ?? $field) . " ist erforderlich.";
- }
- return $this;
- }
- public function email($field, $label = null)
- {
- $value = $this->get($field);
- if (!empty($value) && !filter_var($value, FILTER_VALIDATE_EMAIL)) {
- $this->errors[] =
- ($label ?? $field) . " muss eine gültige E-Mail-Adresse sein.";
- }
- return $this;
- }
- public function minLength($field, $min, $label = null)
- {
- $value = $this->get($field);
- if (!empty($value) && strlen($value) < $min) {
- $this->errors[] =
- ($label ?? $field) .
- " muss mindestens " .
- $min .
- " Zeichen lang sein.";
- }
- return $this;
- }
- public function maxLength($field, $max, $label = null)
- {
- $value = $this->get($field);
- if (!empty($value) && strlen($value) > $max) {
- $this->errors[] =
- ($label ?? $field) .
- " darf maximal " .
- $max .
- " Zeichen lang sein.";
- }
- return $this;
- }
- public function inArray($field, $allowed, $label = null)
- {
- $value = $this->get($field);
- if (!empty($value) && !in_array($value, $allowed, true)) {
- $this->errors[] = ($label ?? $field) . " ist ungültig.";
- }
- return $this;
- }
- public function get($field)
- {
- return $this->data[$field] ?? null;
- }
- public function getErrors()
- {
- return $this->errors;
- }
- public function isValid()
- {
- return empty($this->errors);
- }
- }
- /**
- * Error Logging Functions
- */
- if (!defined("LOG_DIR")) {
- define("LOG_DIR", DATA_DIR . "logs/");
- }
- if (!defined("ERROR_LOG_FILE")) {
- define("ERROR_LOG_FILE", LOG_DIR . "error.log");
- }
- if (!defined("ACCESS_LOG_FILE")) {
- define("ACCESS_LOG_FILE", LOG_DIR . "access.log");
- }
- function initLogging()
- {
- if (!is_dir(LOG_DIR)) {
- mkdir(LOG_DIR, 02775, true);
- @chmod(LOG_DIR, 02775);
- }
- }
- function logError($message, $context = [], $level = "ERROR")
- {
- initLogging();
- $entry = [
- "timestamp" => date("Y-m-d H:i:s.u"),
- "level" => $level,
- "message" => $message,
- "context" => $context,
- "ip" => $_SERVER["REMOTE_ADDR"] ?? "unknown",
- "user_agent" => $_SERVER["HTTP_USER_AGENT"] ?? "unknown",
- "request_uri" => $_SERVER["REQUEST_URI"] ?? "unknown",
- "session_id" => session_id()
- ? substr(session_id(), 0, 8) . "..."
- : "none",
- ];
- $logLine = json_encode($entry, JSON_UNESCAPED_UNICODE) . PHP_EOL;
- file_put_contents(ERROR_LOG_FILE, $logLine, FILE_APPEND | LOCK_EX);
- if (defined("DEVELOPMENT_MODE") && DEVELOPMENT_MODE) {
- error_log(
- "PSA Order: " . $message . " | Context: " . json_encode($context),
- );
- }
- }
- function logAccess($message, $context = [])
- {
- initLogging();
- $entry = [
- "timestamp" => date("Y-m-d H:i:s.u"),
- "message" => $message,
- "context" => $context,
- "ip" => $_SERVER["REMOTE_ADDR"] ?? "unknown",
- "request_method" => $_SERVER["REQUEST_METHOD"] ?? "unknown",
- "request_uri" => $_SERVER["REQUEST_URI"] ?? "unknown",
- ];
- $logLine = json_encode($entry, JSON_UNESCAPED_UNICODE) . PHP_EOL;
- file_put_contents(ACCESS_LOG_FILE, $logLine, FILE_APPEND | LOCK_EX);
- }
- function handleException($exception)
- {
- logError(
- "Uncaught exception: " . $exception->getMessage(),
- [
- "file" => $exception->getFile(),
- "line" => $exception->getLine(),
- "trace" => $exception->getTraceAsString(),
- ],
- "CRITICAL",
- );
- if (defined("DEVELOPMENT_MODE") && DEVELOPMENT_MODE) {
- echo "<h1>Error</h1><pre>" .
- escape($exception->getMessage()) .
- "</pre>";
- } else {
- echo "<h1>Es ist ein Fehler aufgetreten</h1><p>Bitte versuchen Sie es später erneut.</p>";
- }
- exit();
- }
- set_exception_handler("handleException");
- function handleError($errno, $errstr, $errfile, $errline)
- {
- if (!(error_reporting() & $errno)) {
- return false;
- }
- logError(
- "PHP Error: " . $errstr,
- [
- "type" => $errno,
- "file" => $errfile,
- "line" => $errline,
- ],
- "WARNING",
- );
- return true;
- }
- set_error_handler("handleError");
|