| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324 |
- <?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 = "";
- }
- $backorderStatus = trim((string) ($item["backorder_status"] ?? ""));
- $allowedBackorderStatuses = ["", "to_be_backordered", "ordered"];
- if (!in_array($backorderStatus, $allowedBackorderStatuses, true)) {
- $backorderStatus = "";
- }
- return [
- "product_id" => $productId,
- "product_name" => $product["name"],
- "size" => $size,
- "availability_label" =>
- $size !== "" ? getAvailabilityLabel($product, $size) : "",
- "is_processed" => !empty($item["is_processed"]),
- "backorder_status" => $backorderStatus,
- "backordered_at" => trim((string) ($item["backordered_at"] ?? "")),
- "ordered_at" => trim((string) ($item["ordered_at"] ?? "")),
- ];
- }
- 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 uncancelOrder($orderId)
- {
- $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" => "Die Bestellung ist nicht storniert.",
- ];
- }
- $order["cancelled_at"] = "";
- $order["cancelled_by"] = "";
- $order["cancellation_reason"] = "";
- $order["status"] = "open";
- $order["updated_at"] = $now;
- $order = refreshOrderState($order);
- saveOrders($orders);
- return ["success" => true, "order" => $order];
- }
- unset($order);
- return ["success" => false, "message" => "Bestellung nicht gefunden."];
- }
- function orderItemCanBeManaged($order)
- {
- 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.",
- ];
- }
- return ["success" => true];
- }
- function setOrderItemBackorderStatus($orderId, $itemIndex, $status)
- {
- $allowedStatuses = ["", "to_be_backordered"];
- if (!in_array($status, $allowedStatuses, true)) {
- return ["success" => false, "message" => "Ungültiger Nachbestellstatus."];
- }
- $orders = getOrders();
- $now = date("Y-m-d H:i:s");
- foreach ($orders as &$order) {
- if ($order["id"] !== $orderId) {
- continue;
- }
- $guard = orderItemCanBeManaged($order);
- if (!$guard["success"]) {
- return $guard;
- }
- if (!isset($order["items"][$itemIndex])) {
- return [
- "success" => false,
- "message" => "Position nicht gefunden.",
- ];
- }
- if ($status === "to_be_backordered") {
- if (!empty($order["items"][$itemIndex]["is_processed"])) {
- return [
- "success" => false,
- "message" =>
- "Bearbeitete Positionen können nicht als Nachbestellung markiert werden.",
- ];
- }
- $order["items"][$itemIndex]["backorder_status"] = "to_be_backordered";
- $order["items"][$itemIndex]["backordered_at"] = $now;
- $order["items"][$itemIndex]["ordered_at"] = "";
- } else {
- $order["items"][$itemIndex]["backorder_status"] = "";
- $order["items"][$itemIndex]["backordered_at"] = "";
- $order["items"][$itemIndex]["ordered_at"] = "";
- }
- $order["updated_at"] = $now;
- saveOrders($orders);
- return ["success" => true, "order" => $order];
- }
- unset($order);
- return ["success" => false, "message" => "Bestellung nicht gefunden."];
- }
- function toggleOrderItemBackorder($orderId, $itemIndex)
- {
- $orders = getOrders();
- foreach ($orders as $order) {
- if ($order["id"] !== $orderId) {
- continue;
- }
- if (!isset($order["items"][$itemIndex])) {
- return [
- "success" => false,
- "message" => "Position nicht gefunden.",
- ];
- }
- $current = (string) ($order["items"][$itemIndex]["backorder_status"] ?? "");
- $newStatus = $current === "to_be_backordered" ? "" : "to_be_backordered";
- return setOrderItemBackorderStatus($orderId, $itemIndex, $newStatus);
- }
- return ["success" => false, "message" => "Bestellung nicht gefunden."];
- }
- function getManualBackorders()
- {
- $data = readJsonFile(MANUAL_BACKORDERS_FILE);
- $entries =
- isset($data["entries"]) && is_array($data["entries"])
- ? $data["entries"]
- : [];
- $normalized = [];
- foreach ($entries as $entry) {
- if (!is_array($entry)) {
- continue;
- }
- $id = trim((string) ($entry["id"] ?? ""));
- $productId = (int) ($entry["product_id"] ?? 0);
- $productName = trim((string) ($entry["product_name"] ?? ""));
- $size = trim((string) ($entry["size"] ?? ""));
- $status = trim((string) ($entry["backorder_status"] ?? ""));
- if ($id === "" || $productId <= 0 || $productName === "" || $status === "") {
- continue;
- }
- if (!in_array($status, ["to_be_backordered", "ordered"], true)) {
- continue;
- }
- $normalized[] = [
- "id" => $id,
- "product_id" => $productId,
- "product_name" => $productName,
- "size" => $size,
- "backorder_status" => $status,
- "backordered_at" => trim((string) ($entry["backordered_at"] ?? "")),
- "ordered_at" => trim((string) ($entry["ordered_at"] ?? "")),
- "created_at" => trim((string) ($entry["created_at"] ?? "")),
- ];
- }
- return $normalized;
- }
- function saveManualBackorders($entries)
- {
- return writeJsonFile(MANUAL_BACKORDERS_FILE, [
- "entries" => array_values($entries),
- ]);
- }
- function generateManualBackorderId()
- {
- return "mb-" . date("YmdHis") . "-" . bin2hex(random_bytes(4));
- }
- function addManualBackorderItems($productId, $size, $quantity)
- {
- $productId = (int) $productId;
- $size = trim((string) $size);
- $quantity = (int) $quantity;
- if ($productId <= 0 || $quantity <= 0) {
- return [
- "success" => false,
- "message" => "Ungültige Menge oder Artikel.",
- ];
- }
- if ($quantity > 100) {
- return [
- "success" => false,
- "message" => "Maximal 100 Positionen auf einmal.",
- ];
- }
- $product = getProductById($productId);
- if ($product === null) {
- return ["success" => false, "message" => "Artikel nicht gefunden."];
- }
- $allowedSizes = getProductSizes($product);
- if (empty($allowedSizes)) {
- $allowedSizes = ["Standard"];
- }
- if (!in_array($size, $allowedSizes, true)) {
- return ["success" => false, "message" => "Ungültige Größe für diesen Artikel."];
- }
- $entries = getManualBackorders();
- $now = date("Y-m-d H:i:s");
- for ($i = 0; $i < $quantity; $i++) {
- $entries[] = [
- "id" => generateManualBackorderId(),
- "product_id" => $productId,
- "product_name" => $product["name"],
- "size" => $size,
- "backorder_status" => "to_be_backordered",
- "backordered_at" => $now,
- "ordered_at" => "",
- "created_at" => $now,
- ];
- }
- if (!saveManualBackorders($entries)) {
- return [
- "success" => false,
- "message" => "Nachbestellungen konnten nicht gespeichert werden.",
- ];
- }
- return ["success" => true, "added" => $quantity];
- }
- function collectBackorderItemRefs()
- {
- $refs = [];
- foreach (getManualBackorders() as $entry) {
- $refs[] = [
- "order_id" => "",
- "item_index" => 0,
- "manual_id" => $entry["id"],
- "is_manual" => true,
- "product_id" => $entry["product_id"],
- "product_name" => $entry["product_name"],
- "size" => $entry["size"],
- "backorder_status" => $entry["backorder_status"],
- "created_at" => $entry["created_at"] !== "" ? $entry["created_at"] : $entry["backordered_at"],
- "sort_at" =>
- $entry["backorder_status"] === "ordered"
- ? ($entry["ordered_at"] !== ""
- ? $entry["ordered_at"]
- : $entry["created_at"])
- : ($entry["backordered_at"] !== ""
- ? $entry["backordered_at"]
- : $entry["created_at"]),
- ];
- }
- foreach (getOrders() as $order) {
- if (($order["status"] ?? "") === "cancelled") {
- continue;
- }
- if (in_array($order["confirmation_status"] ?? "", ["pending", "expired"], true)) {
- continue;
- }
- foreach ($order["items"] as $itemIndex => $item) {
- $status = (string) ($item["backorder_status"] ?? "");
- if ($status === "") {
- continue;
- }
- $refs[] = [
- "order_id" => $order["id"],
- "item_index" => (int) $itemIndex,
- "product_id" => (int) $item["product_id"],
- "product_name" => $item["product_name"],
- "size" => $item["size"],
- "backorder_status" => $status,
- "created_at" => $order["created_at"],
- "sort_at" =>
- $status === "ordered"
- ? ($item["ordered_at"] !== ""
- ? $item["ordered_at"]
- : $order["created_at"])
- : ($item["backordered_at"] !== ""
- ? $item["backordered_at"]
- : $order["created_at"]),
- ];
- }
- }
- return $refs;
- }
- function getBackorderGroups()
- {
- $refs = collectBackorderItemRefs();
- $groups = [];
- foreach ($refs as $ref) {
- $key = $ref["product_id"] . "|" . $ref["size"];
- if (!isset($groups[$key])) {
- $groups[$key] = [
- "product_id" => $ref["product_id"],
- "product_name" => $ref["product_name"],
- "size" => $ref["size"],
- "to_be_backordered" => 0,
- "ordered" => 0,
- "items_to_be_backordered" => [],
- "items_ordered" => [],
- ];
- }
- if ($ref["backorder_status"] === "to_be_backordered") {
- $groups[$key]["to_be_backordered"]++;
- $groups[$key]["items_to_be_backordered"][] = $ref;
- } elseif ($ref["backorder_status"] === "ordered") {
- $groups[$key]["ordered"]++;
- $groups[$key]["items_ordered"][] = $ref;
- }
- }
- foreach ($groups as &$group) {
- usort($group["items_to_be_backordered"], function ($left, $right) {
- $cmp = strcmp($left["created_at"], $right["created_at"]);
- if ($cmp !== 0) {
- return $cmp;
- }
- return strcmp($left["order_id"], $right["order_id"]);
- });
- usort($group["items_ordered"], function ($left, $right) {
- $cmp = strcmp($left["sort_at"], $right["sort_at"]);
- if ($cmp !== 0) {
- return $cmp;
- }
- return strcmp($left["order_id"], $right["order_id"]);
- });
- }
- unset($group);
- $result = array_values($groups);
- usort($result, function ($left, $right) {
- $cmp = strcmp($left["product_name"], $right["product_name"]);
- if ($cmp !== 0) {
- return $cmp;
- }
- return strcmp($left["size"], $right["size"]);
- });
- return $result;
- }
- function applyBackorderBulkUpdate($productId, $size, $fromStatus, $toStatus, $quantity)
- {
- $productId = (int) $productId;
- $size = trim((string) $size);
- $quantity = (int) $quantity;
- if ($productId <= 0 || $quantity <= 0) {
- return [
- "success" => false,
- "message" => "Ungültige Menge oder Artikel.",
- ];
- }
- $refs = collectBackorderItemRefs();
- $candidates = [];
- foreach ($refs as $ref) {
- if (
- $ref["product_id"] !== $productId ||
- $ref["size"] !== $size ||
- $ref["backorder_status"] !== $fromStatus
- ) {
- continue;
- }
- $candidates[] = $ref;
- }
- usort($candidates, function ($left, $right) {
- $cmp = strcmp($left["created_at"], $right["created_at"]);
- if ($cmp !== 0) {
- return $cmp;
- }
- return strcmp($left["order_id"], $right["order_id"]);
- });
- if ($quantity > count($candidates)) {
- return [
- "success" => false,
- "message" =>
- "Nur " .
- count($candidates) .
- " Position(en) verfügbar, " .
- $quantity .
- " angefordert.",
- ];
- }
- $targets = array_slice($candidates, 0, $quantity);
- $orders = getOrders();
- $manualEntries = getManualBackorders();
- $manualChanged = false;
- $now = date("Y-m-d H:i:s");
- $updated = 0;
- foreach ($targets as $target) {
- if (!empty($target["is_manual"])) {
- $manualId = (string) ($target["manual_id"] ?? "");
- foreach ($manualEntries as &$entry) {
- if ($entry["id"] !== $manualId) {
- continue;
- }
- if ($toStatus === "ordered") {
- $entry["backorder_status"] = "ordered";
- $entry["ordered_at"] = $now;
- } else {
- $entry["backorder_status"] = "";
- $entry["ordered_at"] = "";
- }
- $manualChanged = true;
- $updated++;
- break;
- }
- unset($entry);
- continue;
- }
- foreach ($orders as &$order) {
- if ($order["id"] !== $target["order_id"]) {
- continue;
- }
- $itemIndex = $target["item_index"];
- if (!isset($order["items"][$itemIndex])) {
- continue 2;
- }
- if ($toStatus === "ordered") {
- $order["items"][$itemIndex]["backorder_status"] = "ordered";
- $order["items"][$itemIndex]["ordered_at"] = $now;
- } else {
- $order["items"][$itemIndex]["backorder_status"] = "";
- $order["items"][$itemIndex]["ordered_at"] = "";
- }
- $order["updated_at"] = $now;
- $updated++;
- break;
- }
- unset($order);
- }
- if ($updated === 0) {
- return [
- "success" => false,
- "message" => "Keine Positionen aktualisiert.",
- ];
- }
- if ($manualChanged) {
- $manualEntries = array_values(
- array_filter($manualEntries, function ($entry) {
- return ($entry["backorder_status"] ?? "") !== "";
- }),
- );
- if (!saveManualBackorders($manualEntries)) {
- return [
- "success" => false,
- "message" => "Manuelle Nachbestellungen konnten nicht gespeichert werden.",
- ];
- }
- }
- saveOrders($orders);
- return ["success" => true, "updated" => $updated];
- }
- function markBackorderItemsOrdered($productId, $size, $quantity)
- {
- return applyBackorderBulkUpdate(
- $productId,
- $size,
- "to_be_backordered",
- "ordered",
- $quantity,
- );
- }
- function markBackorderItemsDelivered($productId, $size, $quantity)
- {
- return applyBackorderBulkUpdate($productId, $size, "ordered", "", $quantity);
- }
- function orderHasBackorder($order)
- {
- if (!is_array($order["items"] ?? null)) {
- return false;
- }
- foreach ($order["items"] as $item) {
- if (($item["backorder_status"] ?? "") !== "") {
- return true;
- }
- }
- return false;
- }
- function getBackorderStatusLabel($status)
- {
- switch ((string) $status) {
- case "to_be_backordered":
- return "Nachzubestellen";
- case "ordered":
- return "Wartet auf Lieferung";
- default:
- return "-";
- }
- }
- function getBackorderStatusClass($status)
- {
- switch ((string) $status) {
- case "to_be_backordered":
- return "status-backorder";
- case "ordered":
- return "status-backorder-waiting";
- default:
- return "";
- }
- }
- 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;
- $topY = 800;
- $bottomY = 60;
- $lineHeight = 14;
- $pages = [];
- $pageContent = "";
- $y = $topY;
- $pageNumber = 0;
- $encodeText = function ($text) {
- return pdfEncodeWinAnsi((string) $text);
- };
- $siteName = $encodeText(SITE_FULL_NAME);
- $orderId = $encodeText($order["id"]);
- $createdAt = $encodeText(formatDate($order["created_at"]));
- $customerName = $encodeText($order["customer_name"]);
- $customerEmail = $encodeText($order["customer_email"]);
- $organization = $encodeText($order["organization_label"]);
- $commentRaw = (string) $order["comment"];
- $writeText = function ($x, $y, $encodedText, $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($encodedText) .
- ") Tj\nET\n";
- };
- $startPage = function () use (
- &$pages,
- &$pageContent,
- &$y,
- &$pageNumber,
- $topY,
- $leftMargin,
- $lineHeight,
- $siteName,
- $orderId,
- $createdAt,
- $writeText,
- $encodeText
- ) {
- if ($pageContent !== "") {
- $pages[] = $pageContent;
- }
- $pageNumber++;
- $pageContent = "";
- $y = $topY;
- foreach (pdfWrapAnsiText($siteName, 70) as $index => $line) {
- $writeText($leftMargin, $y, $line, $index === 0 ? 15 : 11);
- $y -= $index === 0 ? 19 : $lineHeight;
- }
- $headerLine = "Bestellung: " . $orderId;
- if ($pageNumber > 1) {
- $headerLine .= " | Seite " . $encodeText($pageNumber);
- }
- $writeText($leftMargin, $y, $headerLine, 12);
- $y -= 17;
- $writeText($leftMargin, $y, "Erstellt am: " . $createdAt, 11);
- $y -= 20;
- };
- $ensureSpace = function ($requiredHeight) use (&$y, $bottomY, $startPage) {
- if ($y - $requiredHeight < $bottomY) {
- $startPage();
- }
- };
- $writeWrapped = function (
- $encodedText,
- $maxChars,
- $fontSize = 11,
- $x = null
- ) use (&$y, $lineHeight, $leftMargin, $writeText, $ensureSpace) {
- $targetX = $x === null ? $leftMargin : $x;
- $lines = pdfWrapAnsiText($encodedText, $maxChars);
- foreach ($lines as $line) {
- $ensureSpace($lineHeight);
- $writeText($targetX, $y, $line, $fontSize);
- $y -= $lineHeight;
- }
- };
- $writeSectionTitle = function ($titleText) use (
- &$y,
- $leftMargin,
- $writeText,
- $ensureSpace,
- $encodeText
- ) {
- $ensureSpace(24);
- $writeText($leftMargin, $y, $encodeText($titleText), 13);
- $y -= 18;
- };
- $startPage();
- $writeSectionTitle("Gehört zu");
- $writeWrapped("Name: " . $customerName, 80);
- $writeWrapped("Organisation: " . $organization, 80);
- $writeWrapped("E-Mail: " . $customerEmail, 80);
- $y -= 6;
- $writeSectionTitle("Artikelliste");
- $itemNumber = 1;
- if (empty($order["items"])) {
- $writeWrapped($encodeText("Keine Artikel"), 80);
- } else {
- foreach ($order["items"] as $item) {
- $itemName = $encodeText($item["product_name"]);
- $sizeLabel = $encodeText($item["size"]);
- $hintLabel = $encodeText(
- preg_replace("/\s+/", " ", (string) $item["availability_label"]),
- );
- $writeWrapped($encodeText($itemNumber . ". ") . $itemName, 78);
- if ($sizeLabel !== "") {
- $writeWrapped($encodeText(" Größe: ") . $sizeLabel, 76);
- }
- if ($hintLabel !== "") {
- $writeWrapped($encodeText(" Hinweis: ") . $hintLabel, 76);
- }
- $y -= 4;
- $itemNumber++;
- }
- }
- $y -= 4;
- $writeSectionTitle("Kommentar");
- if (trim($commentRaw) === "") {
- $writeWrapped($encodeText("Kein Kommentar"), 80);
- } else {
- foreach (preg_split('/\r\n|\r|\n/', $commentRaw) as $commentLine) {
- $writeWrapped($encodeText($commentLine), 82);
- }
- }
- $y -= 6;
- $writeSectionTitle("Lagerbearbeitung");
- $warehouseLines = [
- "Ausgegeben am: ________________________",
- "Ausgegeben durch: _____________________",
- "Unterschrift: _________________________",
- "",
- "[ ] Vollständig ausgegeben",
- "[ ] Teilweise ausgegeben",
- ];
- foreach ($warehouseLines as $line) {
- if ($line === "") {
- $ensureSpace($lineHeight);
- $y -= $lineHeight;
- continue;
- }
- $writeWrapped($encodeText($line), 80);
- }
- 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");
|