RegisterPropertyString('Title', 'NextFloor'); $this->RegisterAttributeString('Building', ''); $this->RegisterAttributeString('Images', '{}'); $this->RegisterAttributeString('Packs', '[]'); $this->RegisterAttributeString('History', '[]'); $this->RegisterAttributeString('AccessToken', ''); $this->RegisterAttributeString('StateHash', ''); $this->RegisterAttributeString('HookError', ''); $this->RegisterAttributeInteger('BuildingRevision', 0); $this->RegisterAttributeInteger('StateRevision', 0); $this->RegisterMessage(0, IPS_KERNELSTARTED); $this->RegisterTimer('WebHookRetry', 0, 'NFSC_RetryWebHook($_IPS[\'TARGET\']);'); $this->ensureAccessToken(); $this->SetVisualizationType(1); $this->ensureWebHook(); } public function ApplyChanges(): void { parent::ApplyChanges(); $this->SetVisualizationType(1); $this->ensureWebHook(); } public function MessageSink(int $TimeStamp, int $SenderID, int $Message, array $Data): void { parent::MessageSink($TimeStamp, $SenderID, $Message, $Data); if ($SenderID === 0 && $Message === IPS_KERNELSTARTED) { $this->ensureWebHook(); } } /** Timer callback; stops itself as soon as the volatile hook has been restored. */ public function RetryWebHook(): void { $this->ensureWebHook(); } /** Explicit recovery from the console without recreating the instance or changing its project. */ public function RepairWebHook(): string { if (!$this->ensureWebHook()) { return $this->hookErrorMessage(); } return 'WebHook registriert: /hook/' . $this->hookPath() . '. Jetzt den Designer öffnen.'; } /** URL returned to the console form. It opens in a console tab, as IPSView does. */ public function OpenDesigner(): string { $this->requireWebHook(); // `link:` is the documented Form-Button marker for a relative Symcon WebHook URL. return 'link:' . $this->designerUrl('designer'); } /** Invalidates links from copied browser history and returns a fresh designer URL. */ public function RotateAccessToken(): string { $this->requireWebHook(); $this->WriteAttributeString('AccessToken', $this->newToken()); return 'link:' . $this->designerUrl('designer'); } /** The custom tile is deliberately an iframe: the full 3D viewer can lazy-load its assets via the same protected hook. */ public function GetVisualizationTile(): string { if (!$this->ensureWebHook()) { return '
NextFloor wird geladen …
' . '' . ''; } private function sendAsset(string $asset): void { // Only build artifacts are public through the authenticated hook. No request can escape the module folder. if (!preg_match('#^(?:nextfloor-(?:designer|3d|editor|card-editor)\\.js|lang/[a-z]{2}\\.json)$#', $asset)) { $this->sendError(404, 'asset_not_found'); return; } $file = __DIR__ . '/assets/' . $asset; if (!is_file($file)) { $this->sendError(503, 'assets_not_built'); return; } header('Content-Type: ' . (str_ends_with($asset, '.json') ? 'application/json; charset=utf-8' : 'text/javascript; charset=utf-8')); header('Cache-Control: private, max-age=3600'); readfile($file); } // --------------------------------------------------------------------- JSON API private function handleApi(): void { if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { $this->sendError(405, 'method_not_allowed'); return; } $request = json_decode((string) file_get_contents('php://input'), true); if (!is_array($request) || !is_string($request['action'] ?? null)) { $this->sendError(400, 'invalid_request'); return; } try { $result = match ($request['action']) { 'bootstrap' => $this->bootstrap(), 'variables/snapshot' => $this->variablesSnapshot((int) ($request['revision'] ?? -1)), 'building/get' => ['building' => $this->building(), 'revision' => $this->ReadAttributeInteger('BuildingRevision'), 'version' => $this->moduleVersion()], 'building/save' => ['revision' => $this->saveBuilding($this->arrayValue($request, 'building'))], 'image/get' => $this->imageGet((string) ($request['image_id'] ?? '')), 'image/set' => $this->imageSet((string) ($request['image_id'] ?? ''), (string) ($request['data'] ?? '')), 'image/delete' => $this->imageDelete((string) ($request['image_id'] ?? '')), 'packs/list' => ['packs' => $this->allPacks()], 'packs/import' => $this->packImport((string) ($request['pack'] ?? '')), 'packs/remove' => $this->packRemove((string) ($request['pack_id'] ?? '')), 'history/list' => ['snapshots' => $this->historyList()], 'history/snapshot' => ['id' => $this->takeSnapshot(isset($request['name']) ? (string) $request['name'] : null)], 'history/get' => $this->historyGet((string) ($request['snapshot_id'] ?? '')), 'history/restore' => $this->historyRestore((string) ($request['snapshot_id'] ?? '')), 'history/delete' => $this->historyDelete((string) ($request['snapshot_id'] ?? '')), 'backup/export' => ['format' => 'nextfloor-backup', 'version' => 1, 'building' => $this->building(), 'packs' => $this->importedPacks()], 'backup/import' => $this->backupImport($this->arrayValue($request, 'building'), $request['packs'] ?? []), 'variables/action' => $this->variableAction((string) ($request['domain'] ?? ''), (string) ($request['service'] ?? ''), $this->arrayValue($request, 'data')), 'transport/read' => $this->readTransfer((string) ($request['transfer_id'] ?? ''), (int) ($request['index'] ?? -1)), 'transport/release' => $this->releaseTransfer((string) ($request['transfer_id'] ?? '')), default => throw new RuntimeException('unknown_action') }; $this->sendApiResult($result, ($request['transport'] ?? '') === 'nextfloor-chunks-v1'); } catch (InvalidArgumentException $error) { $this->sendError(400, $error->getMessage()); } catch (RuntimeException $error) { $this->sendError(404, $error->getMessage()); } } private function bootstrap(): array { $objects = $this->objectTree(); $stateRevision = $this->stateRevision($objects); return [ 'state_revision' => $stateRevision, 'building_revision' => $this->ReadAttributeInteger('BuildingRevision'), 'variables' => $objects['variables'], 'areas' => $objects['areas'], 'objects' => $objects['objects'] ]; } private function variablesSnapshot(int $knownRevision): array { $objects = $this->objectTree(); $stateRevision = $this->stateRevision($objects); $result = [ 'state_revision' => $stateRevision, 'building_revision' => $this->ReadAttributeInteger('BuildingRevision') ]; if ($stateRevision !== $knownRevision) { $result['variables'] = $objects['variables']; $result['areas'] = $objects['areas']; $result['objects'] = $objects['objects']; } return $result; } /** Export real object nodes, not paths reconstructed from variable names. */ private function objectTree(): array { $variables = []; $areas = []; $nodes = []; foreach (IPS_GetChildrenIDs(0) as $child) { $this->collectObjects($child, [], null, $variables, $areas, $nodes); } $byVariable = []; foreach ($variables as $variable) { $byVariable[$variable['attributes']['symcon_id']] = $variable['entity_id']; } // A link stays at its original position in the tree and selects its target variable. foreach ($nodes as &$node) { if ($node['object_type'] === 6) { $target = (int) IPS_GetLink($node['object_id'])['TargetID']; if (isset($byVariable[$target])) { $node['entity_id'] = $byVariable[$target]; } } } unset($node); usort($variables, static fn(array $a, array $b): int => strnatcasecmp($a['path'], $b['path'])); usort($areas, static fn(array $a, array $b): int => strnatcasecmp($a['name'], $b['name'])); return ['variables' => $variables, 'areas' => $areas, 'objects' => $nodes]; } private function collectObjects(int $objectID, array $parents, ?int $nearestCategory, array &$variables, array &$areas, array &$nodes): void { if (!IPS_ObjectExists($objectID)) { return; } $object = IPS_GetObject($objectID); $name = IPS_GetName($objectID); $path = [...$parents, $name]; $type = (int) $object['ObjectType']; $node = [ 'object_id' => $objectID, 'parent_id' => (int) $object['ParentID'], 'name' => $name, 'path' => implode(' / ', $path), 'object_type' => $type, 'position' => (int) $object['ObjectPosition'], 'hidden' => (bool) $object['ObjectIsHidden'], 'icon' => (string) $object['ObjectIcon'] ]; if ($type === 1) { // OBJECTTYPE_INSTANCE: the logical console view separates system modules. $node['module_type'] = (int) IPS_GetInstance($objectID)['ModuleInfo']['ModuleType']; } if ($type === 0) { // OBJECTTYPE_CATEGORY $nearestCategory = $objectID; $areas[] = ['area_id' => 'symcon-category-' . $objectID, 'name' => implode(' / ', $path)]; } if ($type === 2) { // OBJECTTYPE_VARIABLE $variable = $this->describeVariable($objectID, $name, implode(' / ', $path), $nearestCategory); $variables[] = $variable; $node['entity_id'] = $variable['entity_id']; } $nodes[] = $node; foreach (IPS_GetChildrenIDs($objectID) as $child) { $this->collectObjects($child, $path, $nearestCategory, $variables, $areas, $nodes); } } private function describeVariable(int $variableID, string $name, string $path, ?int $categoryID): array { $variable = IPS_GetVariable($variableID); $profile = (string) ($variable['VariableCustomProfile'] ?: $variable['VariableProfile']); $value = GetValue($variableID); $kind = $this->kindFor($variable, $profile, $name . ' ' . $path); $attributes = [ 'symcon_id' => $variableID, 'symcon_path' => $path, 'symcon_profile' => $profile, 'symcon_variable_type' => (int) $variable['VariableType'], 'symcon_has_action' => ((int) ($variable['VariableCustomAction'] ?: $variable['VariableAction'])) !== 0, 'symcon_formatted' => GetValueFormatted($variableID), 'device_class' => $this->deviceClassFor($profile, $name . ' ' . $path) ]; $profileData = $profile !== '' && IPS_VariableProfileExists($profile) ? IPS_GetVariableProfile($profile) : null; if (is_array($profileData) && (string) ($profileData['Suffix'] ?? '') !== '') { $attributes['unit_of_measurement'] = trim((string) $profileData['Suffix']); } if ($kind === 'light' && is_numeric($value)) { $attributes['brightness'] = (int) round(max(0, min(100, (float) $value)) * 2.55); $attributes['color_mode'] = 'brightness'; $attributes['supported_color_modes'] = ['brightness']; } if ($kind === 'cover' && is_numeric($value)) { $attributes['current_position'] = max(0, min(100, (int) round((float) $value))); $attributes['supported_features'] = 4; } if ($kind === 'climate' && is_numeric($value)) { // A Symcon thermostat commonly exposes one writable setpoint. Present it as both // target and current temperature so all existing NextFloor climate displays can use it. $attributes['current_temperature'] = (float) $value; $attributes['temperature'] = (float) $value; $attributes['hvac_modes'] = ['off', 'heat']; $attributes['hvac_action'] = (float) $value > 0 ? 'heating' : 'idle'; } return [ 'entity_id' => $kind . '.' . $variableID, 'name' => $name, 'path' => $path, 'state' => $this->stateFor($kind, $value), 'attributes' => $attributes, 'area_id' => $categoryID === null ? null : 'symcon-category-' . $categoryID, 'device_id' => 'symcon-variable-' . $variableID ]; } private function kindFor(array $variable, string $profile, string $haystack): string { $text = mb_strtolower($profile . ' ' . $haystack); $type = (int) $variable['VariableType']; $action = (int) ($variable['VariableCustomAction'] ?: $variable['VariableAction']); if (preg_match('/roll|jalous|raff|shutter|blind|markise|cover|tor|garage/', $text)) { return 'cover'; } if (preg_match('/schloss|lock/', $text)) { return 'lock'; } if ($action !== 0 && preg_match('/licht|lampe|light|dimm|intensity/', $text)) { return 'light'; } if ($action !== 0 && preg_match('/heizung|thermostat|heating|climate|hvac/', $text)) { return 'climate'; } if ($action !== 0 && preg_match('/szene|scene|script|taster|button/', $text)) { return 'script'; } if ($type === 0 && $action !== 0) { return 'switch'; } if ($type === 0) { return 'binary_sensor'; } return 'sensor'; } private function deviceClassFor(string $profile, string $haystack): string { $text = mb_strtolower($profile . ' ' . $haystack); return match (true) { str_contains($text, 'temperature') || str_contains($text, 'temperatur') => 'temperature', str_contains($text, 'humidity') || str_contains($text, 'feuchte') => 'humidity', str_contains($text, 'co2') => 'carbon_dioxide', str_contains($text, 'watt') || str_contains($text, 'power') || str_contains($text, 'leistung') => 'power', preg_match('/kontakt|fenster|tür|tuer|motion|bewegung|presence|anwesen/', $text) === 1 => 'opening', default => '' }; } private function stateFor(string $kind, mixed $value): string { if ($kind === 'cover' && is_numeric($value)) { return (float) $value <= 0 ? 'closed' : ((float) $value >= 100 ? 'open' : 'opening'); } if ($kind === 'light' && is_numeric($value)) { return (float) $value > 0 ? 'on' : 'off'; } if ($kind === 'lock' && is_bool($value)) { return $value ? 'locked' : 'unlocked'; } if ($kind === 'climate' && is_numeric($value)) { return (float) $value > 0 ? 'heat' : 'off'; } if (is_bool($value)) { return $value ? 'on' : 'off'; } if (is_float($value)) { return rtrim(rtrim(sprintf('%.6F', $value), '0'), '.'); } return (string) $value; } private function stateRevision(array $objects): int { $hash = hash('sha256', $this->encodeResponse($objects)); if (!hash_equals($this->ReadAttributeString('StateHash'), $hash)) { $this->WriteAttributeString('StateHash', $hash); $this->WriteAttributeInteger('StateRevision', $this->ReadAttributeInteger('StateRevision') + 1); } return $this->ReadAttributeInteger('StateRevision'); } // --------------------------------------------------------------------- plan, packs, images and history private function building(): array { $stored = $this->jsonAttribute('Building', null); return is_array($stored) ? $stored : $this->emptyBuilding(); } private function emptyBuilding(): array { return [ 'version' => 1, 'floors' => [], 'settings' => ['wall_exterior' => 0.24, 'wall_interior' => 0.12, 'grid' => 0.05, 'north' => 0, 'roof' => ['type' => 'none', 'pitch' => 35, 'overhang' => 0.4]], 'energy' => ['meter' => null, 'grid' => null, 'grid_invert' => false, 'solar' => null, 'battery' => null, 'battery_invert' => false, 'battery_soc' => null, 'consumption' => null, 'tariff' => null], 'presence' => [] ]; } private function saveBuilding(array $building): int { if (($building['version'] ?? null) !== 1 || !is_array($building['floors'] ?? null) || !is_array($building['settings'] ?? null)) { throw new InvalidArgumentException('invalid_building'); } $encoded = json_encode($building, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR); if (strlen($encoded) > self::MAX_BUILDING_BYTES) { throw new InvalidArgumentException('building_too_large'); } $this->WriteAttributeString('Building', $encoded); $revision = $this->ReadAttributeInteger('BuildingRevision') + 1; $this->WriteAttributeInteger('BuildingRevision', $revision); $this->UpdateVisualizationValue(json_encode(['building_revision' => $revision])); return $revision; } private function imageGet(string $imageID): array { $images = $this->jsonAttribute('Images', []); if (!is_array($images) || !isset($images[$imageID])) { throw new RuntimeException('not_found'); } return ['data' => $images[$imageID]]; } private function imageSet(string $imageID, string $data): array { if (!preg_match('/^[A-Za-z0-9_.-]{1,64}$/', $imageID) || !str_starts_with($data, 'data:image/') || strlen($data) > self::MAX_IMAGE_BYTES) { throw new InvalidArgumentException('invalid_image'); } $images = $this->jsonAttribute('Images', []); $images[$imageID] = $data; $this->writeJsonAttribute('Images', $images); return []; } private function imageDelete(string $imageID): array { $images = $this->jsonAttribute('Images', []); unset($images[$imageID]); $this->writeJsonAttribute('Images', $images); return []; } private function allPacks(): array { return [...$this->builtInPacks(), ...$this->importedPacks()]; } private function builtInPacks(): array { $packs = []; foreach (glob(__DIR__ . '/packs/*.json') ?: [] as $file) { $pack = json_decode((string) file_get_contents($file), true); if (is_array($pack) && is_string($pack['id'] ?? null) && is_array($pack['items'] ?? null)) { $packs[] = [...$pack, 'builtin' => true]; } } return $packs; } private function importedPacks(): array { $packs = $this->jsonAttribute('Packs', []); return is_array($packs) ? array_values($packs) : []; } private function packImport(string $source): array { $pack = json_decode($source, true); if (!is_array($pack) || !is_string($pack['id'] ?? null) || !is_string($pack['name'] ?? null) || !is_array($pack['items'] ?? null)) { throw new InvalidArgumentException('invalid_pack'); } if (in_array($pack['id'], array_column($this->builtInPacks(), 'id'), true)) { throw new InvalidArgumentException('builtin_pack'); } $entry = [...$pack, 'imported_at' => time()]; $packs = array_values(array_filter($this->importedPacks(), static fn(array $old): bool => $old['id'] !== $entry['id'])); $packs[] = $entry; $this->writeJsonAttribute('Packs', $packs); return ['id' => $entry['id'], 'name' => $entry['name'], 'publisher' => (string) ($entry['publisher'] ?? ''), 'items' => count($entry['items'])]; } private function packRemove(string $packID): array { $before = $this->importedPacks(); $after = array_values(array_filter($before, static fn(array $pack): bool => $pack['id'] !== $packID)); if (count($before) === count($after)) { throw new RuntimeException('not_found'); } $this->writeJsonAttribute('Packs', $after); return []; } private function takeSnapshot(?string $name = null): string { $history = $this->history(); $id = substr(bin2hex(random_bytes(12)), 0, 12); $entry = ['id' => $id, 'revision' => $this->ReadAttributeInteger('BuildingRevision'), 'saved_at' => time(), 'building' => $this->building()]; if ($name !== null && trim($name) !== '') { $entry['name'] = mb_substr(trim($name), 0, 60); } $history[] = $entry; $this->writeJsonAttribute('History', array_slice($history, -self::MAX_HISTORY)); return $id; } private function historyList(): array { $history = array_reverse($this->history()); return array_map(function (array $entry): array { $building = is_array($entry['building'] ?? null) ? $entry['building'] : []; return [ 'id' => $entry['id'], 'revision' => $entry['revision'], 'saved_at' => $entry['saved_at'], 'floors' => count($building['floors'] ?? []), 'rooms' => array_sum(array_map(static fn(array $floor): int => count($floor['rooms'] ?? []), $building['floors'] ?? [])), 'furniture' => array_sum(array_map(static fn(array $floor): int => count($floor['furniture'] ?? []), $building['floors'] ?? [])), ...isset($entry['name']) ? ['name' => $entry['name']] : [] ]; }, $history); } private function historyGet(string $id): array { foreach ($this->history() as $entry) { if (($entry['id'] ?? '') === $id) { return ['building' => $entry['building']]; } } throw new RuntimeException('not_found'); } private function historyRestore(string $id): array { $snapshot = $this->historyGet($id); $this->takeSnapshot(); return ['revision' => $this->saveBuilding($snapshot['building'])]; } private function historyDelete(string $id): array { $history = $this->history(); $after = array_values(array_filter($history, static fn(array $entry): bool => ($entry['id'] ?? '') !== $id)); if (count($history) === count($after)) { throw new RuntimeException('not_found'); } $this->writeJsonAttribute('History', $after); return []; } private function backupImport(array $building, mixed $packs): array { if (!is_array($packs)) { throw new InvalidArgumentException('invalid_packs'); } $this->takeSnapshot(); $accepted = array_values(array_filter($packs, static fn(mixed $pack): bool => is_array($pack) && is_string($pack['id'] ?? null) && is_array($pack['items'] ?? null))); $this->writeJsonAttribute('Packs', $accepted); return ['revision' => $this->saveBuilding($building), 'building' => $building, 'packs' => count($accepted), 'skipped' => []]; } private function history(): array { $history = $this->jsonAttribute('History', []); return is_array($history) ? array_values($history) : []; } // --------------------------------------------------------------------- variable actions private function variableAction(string $domain, string $service, array $data): array { $entity = $data['entity_id'] ?? null; $entities = is_array($entity) ? $entity : [$entity]; foreach ($entities as $entityID) { if (!is_string($entityID)) { continue; } $variableID = $this->variableIdForEntity($entityID); if ($variableID === null || !IPS_VariableExists($variableID)) { continue; } $this->writeAction($variableID, $domain, $service, $data); } return []; } private function variableIdForEntity(string $entityID): ?int { return preg_match('/^[a-z_]+\\.(\\d+)$/', $entityID, $matches) === 1 ? (int) $matches[1] : null; } private function writeAction(int $variableID, string $domain, string $service, array $data): void { $variable = IPS_GetVariable($variableID); $current = GetValue($variableID); $value = match ($service) { 'toggle', 'media_play_pause' => is_bool($current) ? !$current : (is_numeric($current) ? ((float) $current > 0 ? 0 : 100) : true), 'turn_on', 'open_cover', 'lock' => $this->onValue($variable, $data), 'turn_off', 'close_cover', 'unlock' => $this->offValue($variable), 'set_cover_position', 'set_cover_tilt_position' => $data['position'] ?? $data['tilt_position'] ?? $current, 'set_percentage' => $data['percentage'] ?? $current, 'set_temperature' => $data['temperature'] ?? $current, 'set_hvac_mode' => ($data['hvac_mode'] ?? '') === 'off' ? $this->offValue($variable) : $this->onValue($variable, $data), 'press' => true, default => $this->onValue($variable, $data) }; $this->setVariable($variableID, $variable, $value); } private function onValue(array $variable, array $data): mixed { $type = (int) $variable['VariableType']; if ($type === 0) { return true; } if (isset($data['brightness_pct'])) { return (float) $data['brightness_pct']; } return $type === 3 ? 'on' : 100; } private function offValue(array $variable): mixed { return match ((int) $variable['VariableType']) { 0 => false, 3 => 'off', default => 0 }; } private function setVariable(int $variableID, array $variable, mixed $value): void { $type = (int) $variable['VariableType']; $cast = match ($type) { 0 => (bool) $value, 1 => (int) round((float) $value), 2 => (float) $value, default => (string) $value }; $action = (int) ($variable['VariableCustomAction'] ?: $variable['VariableAction']); if ($action !== 0) { RequestAction($variableID, $cast); } else { SetValue($variableID, $cast); } } // --------------------------------------------------------------------- small helpers private function moduleVersion(): string { $library = json_decode((string) file_get_contents(__DIR__ . '/../library.json'), true, 512, JSON_THROW_ON_ERROR); return (string) $library['version']; } private function arrayValue(array $source, string $key): array { if (!is_array($source[$key] ?? null)) { throw new InvalidArgumentException('invalid_' . $key); } return $source[$key]; } private function jsonAttribute(string $name, mixed $fallback): mixed { $value = json_decode($this->ReadAttributeString($name), true); return $value === null && json_last_error() !== JSON_ERROR_NONE ? $fallback : $value; } private function writeJsonAttribute(string $name, mixed $value): void { $this->WriteAttributeString($name, json_encode($value, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR)); } private function sendJson(array $data): void { $encoded = $this->encodeResponse($data); header('Content-Type: application/json; charset=utf-8'); header('Cache-Control: no-store'); echo $encoded; } private function encodeResponse(array $data): string { return json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE | JSON_THROW_ON_ERROR); } /** Never emit a JSON response near the kernel's default 1 MiB PHP output limit. */ private function sendApiResult(array $data, bool $supportsChunks): void { $encoded = $this->encodeResponse($data); if (strlen($encoded) <= self::MAX_API_RESPONSE_BYTES) { header('Content-Type: application/json; charset=utf-8'); header('Cache-Control: no-store'); echo $encoded; return; } if (!$supportsChunks) { $this->sendError(409, 'client_update_required: Bitte den Designer neu laden.'); return; } $this->sendJson(['_nextfloor_transfer' => $this->createTransfer($encoded)]); } /** Large results use private, short-lived snapshots, not the module's size-limited SetBuffer. */ private function transferDirectory(): string { $directory = rtrim(sys_get_temp_dir(), '/\\') . DIRECTORY_SEPARATOR . 'nextfloor-transfers-' . $this->InstanceID; if (is_link($directory) || (!is_dir($directory) && !mkdir($directory, 0700, true) && !is_dir($directory))) { throw new RuntimeException('transfer_storage_unavailable'); } return $directory; } private function transferFile(string $id): string { if (preg_match('/^[a-f0-9]{32}$/D', $id) !== 1) { throw new InvalidArgumentException('invalid_transfer_id'); } return $this->transferDirectory() . DIRECTORY_SEPARATOR . $id . '.json'; } private function createTransfer(string $encoded): array { $bytes = strlen($encoded); if ($bytes > self::MAX_TRANSFER_BYTES) { throw new InvalidArgumentException('response_too_large'); } $active = 0; foreach (glob($this->transferDirectory() . DIRECTORY_SEPARATOR . '*.json') ?: [] as $file) { if (preg_match('/^[a-f0-9]{32}\.json$/D', basename($file)) !== 1 || is_link($file)) continue; if ((int) filemtime($file) < time() - self::TRANSFER_TTL) { unlink($file); } else { $active++; } } if ($active >= 8) throw new RuntimeException('transfer_busy: Bitte kurz warten und erneut laden.'); $id = bin2hex(random_bytes(16)); $file = $this->transferFile($id); $handle = fopen($file, 'xb'); if ($handle === false) throw new RuntimeException('transfer_storage_unavailable'); chmod($file, 0600); try { $written = 0; while ($written < $bytes) { $count = fwrite($handle, substr($encoded, $written)); if ($count === false || $count === 0) throw new RuntimeException('transfer_write_failed'); $written += $count; } } catch (Throwable $error) { fclose($handle); unlink($file); throw $error; } fclose($handle); return ['id' => $id, 'bytes' => $bytes, 'chunk_bytes' => self::TRANSFER_CHUNK_BYTES, 'chunks' => (int) ceil($bytes / self::TRANSFER_CHUNK_BYTES)]; } private function readTransfer(string $id, int $index): array { $file = $this->transferFile($id); if (!is_file($file) || is_link($file)) throw new RuntimeException('transfer_not_found'); if ((int) filemtime($file) < time() - self::TRANSFER_TTL) { unlink($file); throw new RuntimeException('transfer_expired: Bitte erneut laden.'); } $bytes = (int) filesize($file); if ($index < 0 || $index >= (int) ceil($bytes / self::TRANSFER_CHUNK_BYTES)) { throw new InvalidArgumentException('invalid_transfer_index'); } $handle = fopen($file, 'rb'); if ($handle === false) throw new RuntimeException('transfer_not_found'); try { if (fseek($handle, $index * self::TRANSFER_CHUNK_BYTES) !== 0) throw new RuntimeException('transfer_read_failed'); $data = fread($handle, self::TRANSFER_CHUNK_BYTES); if ($data === false) throw new RuntimeException('transfer_read_failed'); } finally { fclose($handle); } touch($file); // Active slow connections keep their immutable snapshot alive. return ['index' => $index, 'data' => base64_encode($data)]; } private function releaseTransfer(string $id): array { $file = $this->transferFile($id); if (is_file($file) && !is_link($file)) unlink($file); return []; } private function sendError(int $status, string $error): void { http_response_code($status); $this->sendJson(['error' => $error]); } }