Files

297 lines
18 KiB
PHP

<?php
declare(strict_types=1);
class NextFloorDenied extends RuntimeException {}
/** Deny by default; project geometry and live data are separate capabilities. */
trait NextFloorPermissions
{
private const REF_FIELDS = ['entity', 'entity_id', 'device', 'tracker', 'power', 'energy', 'temperature', 'humidity', 'co2', 'illuminance',
'supply_vsr', 'extract_vsr', 'supply_temperature', 'extract_temperature', 'reheat', 'status', 'schedules',
'floor_heating', 'clean_entity', 'panel', 'hidden', 'no_state', 'cover', 'cover2', 'cover_tilt', 'cover2_tilt',
'contact', 'contact2', 'tilt', 'tilt2', 'position', 'tilt_angle', 'lock', 'door_left', 'door_right', 'soc', 'charge', 'export',
'gang_entities', 'flow', 'return', 'command', 'feedback', 'circulation_temperature', 'hot_water', 'cold_water',
'start', 'end', 'duration', 'start_time', 'end_time', 'charging_time', 'charged_energy', 'lock_status', 'range', 'charging', 'plugged', 'departure',
'grid', 'solar', 'battery', 'battery_soc', 'consumption', 'tariff', 'meter', 'favorites', 'condition', 'pressure', 'wind_speed', 'wind_gust_speed', 'wind_bearing',
'cloud_coverage', 'precipitation', 'precipitation_total', 'uv_index', 'visibility', 'snow', 'fog', 'lightning'];
private const REF_GROUPS = ['climate', 'hvac', 'utility_meters', 'electricity', 'water', 'gas', 'heating', 'cooling',
'values', 'charging', 'hydronic', 'circuits', 'sensors', 'stations', 'pump', 'valve', 'circulation', 'show_when', 'car', 'gates', 'settings', 'presence', 'weather_variables'];
private function refKey(string $key): bool { return in_array($key, self::REF_FIELDS, true) || preg_match('/_(?:entit(?:y\d*|ies)|sensor\d*)$/D', $key) === 1; }
private function entityRefs(array $node): array
{
$ids = [];
foreach ($node as $key => $value) {
if (!is_int($key) && !$this->refKey($key) && !in_array($key, self::REF_GROUPS, true)) continue;
if (is_string($value) && $this->variableIdForEntity($value) !== null) $ids[] = $this->variableIdForEntity($value);
if (is_array($value)) $ids = [...$ids, ...$this->entityRefs($value)];
}
return array_values(array_unique($ids));
}
private function planKey(string $kind, array $floor, string $id): string { return $kind . ':' . rawurlencode((string) $floor['id']) . ':' . rawurlencode($id); }
private function accessCatalog(): array
{
$rooms = []; $devices = [];
$building = $this->building();
$topology = $building['topology'] ?? [];
$find = static function (string $group, ?string $id) use ($topology): array {
foreach ($topology[$group] ?? [] as $row) if ($row['id'] === $id) return $row;
return [];
};
foreach ($building['floors'] ?? [] as $floor) {
$group = $find('buildings', $floor['building_id'] ?? null);
$branch = $find('branches', $group['branch_id'] ?? null);
$location = $find('locations', $floor['outdoor_location_id'] ?? $branch['location_id'] ?? null);
$parts = [$location['name'] ?? '', $branch['name'] ?? '', $group['name'] ?? '', $floor['name'] ?? 'Etage'];
$prefix = implode(' / ', array_filter($parts, static fn(string $v): bool => $v !== '')) . ' / ';
foreach ($floor['rooms'] ?? [] as $room) $rooms[] = ['caption' => $prefix . ($room['name'] ?? $room['id']), 'value' => $this->planKey('room', $floor, (string) $room['id'])];
foreach (['furniture', 'openings', 'placements'] as $group) foreach ($floor[$group] ?? [] as $item) {
$id = (string) ($item['id'] ?? $item['entity_id'] ?? '');
if ($id === '') continue;
$room = $this->itemRoom($floor, $item);
$label = trim((string) ($item['name'] ?? ''));
if ($label === '' && ($native = $this->variableIdForEntity($id)) !== null && IPS_ObjectExists($native)) {
$parts = []; $at = $native; $seen = [];
while ($at > 0 && IPS_ObjectExists($at) && count($parts) < 3 && !isset($seen[$at])) {
$seen[$at] = true; array_unshift($parts, IPS_GetName($at)); $at = (int) IPS_GetObject($at)['ParentID'];
}
$label = implode(' / ', $parts);
}
if ($label === '') $label = str_replace('_', ' ', (string) ($item['type'] ?? 'Gerät'));
$devices[] = ['caption' => $prefix . ($room ? ($room['name'] ?? '') . ' / ' : '') . $label, 'value' => $this->planKey($group, $floor, $id)];
}
}
return ['rooms' => $rooms, 'devices' => $devices];
}
private function insideRoom(float $x, float $z, array $points): bool
{
$inside = false; $count = count($points);
for ($i = 0, $j = $count - 1; $i < $count; $j = $i++) {
[$xi, $zi] = $points[$i]; [$xj, $zj] = $points[$j];
if (($zi > $z) !== ($zj > $z) && $x < ($xj - $xi) * ($z - $zi) / ($zj - $zi) + $xi) $inside = !$inside;
}
return $inside;
}
private function itemRoom(array $floor, array $item): ?array
{
foreach ($floor['rooms'] ?? [] as $room) {
if (isset($item['room_id']) ? $item['room_id'] === $room['id'] : (isset($item['x'], $item['z']) && $this->insideRoom((float) $item['x'], (float) $item['z'], $room['points'] ?? []))) return $room;
}
return null;
}
private function grantMap(array $grants): array
{
$map = [];
foreach ($grants as $g) if (in_array($g['access'] ?? '', ['view', 'control'], true)) $map[(string) $g['target']] = $g['access'];
return $map;
}
private function isAdministrator(): bool { return ($this->requestUser['role'] ?? '') === 'admin'; }
private function scope(?array $tree = null): array
{
if ($this->requestScope !== null) return $this->requestScope;
if ($this->requestUser === null) throw new NextFloorDenied('authentication_required');
$user = $this->requestUser;
$all = $this->isAdministrator();
$scope = ['view_all' => $all || ($user['view_all'] ?? false) || ($user['control_all'] ?? false), 'control_all' => $all || ($user['control_all'] ?? false),
'read' => [], 'write' => [], 'native_read' => [], 'entities' => [], 'rooms' => $this->grantMap($user['rooms'] ?? []), 'devices' => $this->grantMap($user['devices'] ?? [])];
if ($all) return $this->requestScope = $scope;
$tree ??= $this->objectTree();
$parents = []; $native = [];
foreach ($tree['objects'] as $o) $parents[(int) $o['object_id']] = (int) $o['parent_id'];
foreach ($tree['variables'] as $v) {
$native[(int) $v['attributes']['symcon_id']] = true;
$scope['entities'][(int) $v['attributes']['symcon_id']] = $v['entity_id'];
}
$descendantCache = [];
$descendants = static function (int $root) use ($native, $parents, &$descendantCache): array {
if (isset($descendantCache[$root])) return $descendantCache[$root];
$ids = [];
foreach ($native as $id => $_) {
$at = $id; $seen = [];
while ($at > 0 && !isset($seen[$at])) {
if ($at === $root) { $ids[] = $id; break; }
$seen[$at] = true; $at = $parents[$at] ?? 0;
}
}
return $descendantCache[$root] = $ids;
};
$allow = static function (array $ids, string $level, bool $explicit = false) use (&$scope, $native): void {
foreach ($ids as $id) if (isset($native[$id])) {
$scope['read'][$id] = true;
if ($level === 'control') $scope['write'][$id] = true;
if ($explicit) $scope['native_read'][$id] = true;
}
};
foreach ($user['objects'] ?? [] as $g) {
$target = (int) $g['target']; $seen = [];
while (IPS_ObjectExists($target) && (int) IPS_GetObject($target)['ObjectType'] === 6 && !isset($seen[$target])) {
$seen[$target] = true; $target = (int) IPS_GetLink($target)['TargetID'];
}
$allow($descendants($target), $g['access'], true);
}
foreach ($this->building()['floors'] ?? [] as $floor) {
foreach ($floor['rooms'] ?? [] as $room) {
$key = $this->planKey('room', $floor, (string) $room['id']);
$own = $scope['rooms'][$key] ?? null;
$level = $scope['control_all'] || $own === 'control' ? 'control' : ($scope['view_all'] ? 'view' : $own);
if ($level === null) continue;
$scope['rooms'][$key] = $level;
$allow($this->entityRefs($room), $level);
foreach ([$room['area_id'] ?? '', ...($room['sub_areas'] ?? [])] as $area) if (preg_match('/^symcon-category-(\d+)$/D', (string) $area, $m) === 1) $allow($descendants((int) $m[1]), $level);
}
foreach (['furniture', 'openings', 'placements'] as $group) foreach ($floor[$group] ?? [] as $item) {
$id = (string) ($item['id'] ?? $item['entity_id'] ?? '');
$own = $scope['devices'][$this->planKey($group, $floor, $id)] ?? null;
$room = $this->itemRoom($floor, $item);
$inherited = $room ? ($scope['rooms'][$this->planKey('room', $floor, (string) $room['id'])] ?? null) : null;
$level = $scope['control_all'] || $own === 'control' || $inherited === 'control' ? 'control' : ($own ?? $inherited ?? ($scope['view_all'] ? 'view' : null));
if ($level !== null) { $scope['devices'][$this->planKey($group, $floor, $id)] = $level; $allow($this->entityRefs($item), $level); }
}
if ($scope['view_all']) {
$allow($this->entityRefs($floor), $scope['control_all'] ? 'control' : 'view');
foreach ($floor['outdoor'] ?? [] as $area) $allow($this->entityRefs($area), $scope['control_all'] ? 'control' : 'view');
}
}
if ($scope['view_all']) $allow($this->entityRefs($this->building()), $scope['control_all'] ? 'control' : 'view');
return $this->requestScope = $scope;
}
private function allowedEntity(string $entity, bool $write): bool
{
$id = $this->variableIdForEntity($entity);
if ($id === null) return false;
$s = $this->scope();
return $this->isAdministrator() || ($write ? isset($s['write'][$id]) : isset($s['read'][$id]));
}
/** Authorize every target before the first write: mixed bulk commands cannot partially execute. */
private function authorizeApi(string $action, array $request): void
{
if ($this->requestUser === null) throw new NextFloorDenied('authentication_required');
$read = ['bootstrap', 'variables/snapshot', 'archive/trend', 'building/get', 'image/get', 'packs/list', 'transport/read', 'transport/release'];
if (!$this->isAdministrator() && !in_array($action, [...$read, 'variables/action'], true)) throw new NextFloorDenied('admin_required');
if ($action === 'archive/trend' && (!is_string($request['entity_id'] ?? null) || !$this->allowedEntity($request['entity_id'], false))) throw new NextFloorDenied('read_forbidden');
if ($action === 'variables/action') {
$targets = $request['data']['entity_id'] ?? [];
$targets = is_array($targets) ? $targets : [$targets];
if (!$targets || count($targets) > 256) throw new NextFloorDenied('invalid_targets');
foreach ($targets as $target) {
if (!is_string($target) || !$this->allowedEntity($target, true)) throw new NextFloorDenied('control_forbidden');
$id = $this->variableIdForEntity($target);
if (!$this->isAdministrator() && IPS_VariableExists($id)) {
$v = IPS_GetVariable($id); $actionID = (int) ($v['VariableCustomAction'] ?: $v['VariableAction']);
if ($actionID <= 0) throw new NextFloorDenied('variable_readonly');
}
}
}
if ($action === 'image/get' && !$this->isAdministrator()) {
$id = is_string($request['image_id'] ?? null) ? $request['image_id'] : '';
$images = [];
$visible = $this->visibleBuilding();
array_walk_recursive($visible, static function (mixed $value, mixed $key) use (&$images): void {
if (!is_string($value)) return;
if ($key === 'image_id') $images[] = $value;
elseif (is_string($key) && preg_match('/^(?:picture|image|url|.*_image)$/D', $key) && str_starts_with($value, 'image:')) $images[] = substr($value, 6);
});
if ($id === '' || !in_array($id, $images, true)) throw new NextFloorDenied('image_forbidden');
}
}
private function visibleTree(array $tree): array
{
if ($this->isAdministrator()) return $tree;
$scope = $this->scope($tree);
$variables = [];
foreach ($tree['variables'] as $v) {
$id = (int) $v['attributes']['symcon_id'];
if (!isset($scope['read'][$id])) continue;
$can = isset($scope['write'][$id]) && (($v['attributes']['symcon_schedule'] ?? false) || ($v['attributes']['symcon_has_action'] ?? false));
$v['attributes']['symcon_can_control'] = $can;
if (!$can) $v['attributes']['symcon_has_action'] = false;
$variables[] = $v;
}
$areaIDs = array_fill_keys(array_filter(array_column($variables, 'area_id'), 'is_string'), true);
$areas = array_filter($tree['areas'], static fn(array $a): bool => isset($areaIDs[$a['area_id']]));
// Utility discovery also needs topology (e.g. Büro / Strom / Leistung). Keep only permitted
// variable nodes and their ancestors; never expose unrelated branches or variable values.
$nodes = [];
foreach ($tree['objects'] as $node) $nodes[(int) $node['object_id']] = $node;
$keep = [];
foreach ($variables as $v) {
$at = (int) $v['attributes']['symcon_id'];
while ($at > 0 && isset($nodes[$at]) && !isset($keep[$at])) {
$keep[$at] = true; $at = (int) $nodes[$at]['parent_id'];
}
}
$objects = array_values(array_filter($tree['objects'], static fn(array $node): bool => isset($keep[(int) $node['object_id']])));
return ['variables' => $variables, 'areas' => array_values($areas), 'objects' => $objects];
}
private function maskRefs(array $node, array $allow): array
{
foreach ($node as $key => $v) {
// Strip unknown/legacy binding fields too. Geometry identifiers and captions are not live bindings.
if (in_array($key, ['id', 'name', 'type', 'label', 'icon', 'room_id', 'area_id', 'parent_meter', 'buffer_id'], true)) continue;
if (is_string($v) && ($id = $this->variableIdForEntity($v)) !== null && !isset($allow[$id])) $node[$key] = 'none';
elseif (is_array($v)) $node[$key] = $this->maskRefs($v, $allow);
}
return $node;
}
private function visibleBuilding(): array
{
$building = $this->building();
if ($this->isAdministrator()) return $building;
$s = $this->scope();
// Admin-owned executable UI configuration is never part of a user view.
$building['settings']['plugins'] = []; $building['settings']['buttons'] = [];
foreach (['custom_buttons', 'media_presets', 'announce_phrases'] as $key) unset($building['settings'][$key]);
foreach ($building['floors'] as &$floor) {
$panels = [];
foreach (['furniture', 'openings', 'placements'] as $group) foreach ($floor[$group] ?? [] as $i => $item) {
$id = (string) ($item['id'] ?? $item['entity_id'] ?? '');
$granted = $s['view_all'] || isset($s['devices'][$this->planKey($group, $floor, $id)]);
$filtered = $granted ? $item : $this->maskRefs($item, $s['native_read']);
unset($filtered['tap']);
if (!$granted) {
unset($filtered['show_when'], $filtered['pictures'], $filtered['screen_pictures'], $filtered['picture']);
if (empty($item['entity'])) $filtered['entity'] = 'none';
if (!$this->entityRefs($filtered)) { $filtered['power_card'] = false; $filtered['hydronic']['card'] = false; }
}
$floor[$group][$i] = $filtered;
$room = $this->itemRoom($floor, $item);
if ($room) foreach ($this->entityRefs($filtered) as $native) $panels[$room['id']][$native] = true;
}
foreach ($floor['rooms'] as &$room) {
$key = $this->planKey('room', $floor, (string) $room['id']);
if ($s['view_all'] || isset($s['rooms'][$key])) continue;
$room = $this->maskRefs($room, []);
$room['area_id'] = null; $room['sub_areas'] = []; $room['climate_card'] = false;
$room['symcon_read_room'] = false;
$room['climate'] = ['temperature' => 'none', 'humidity' => 'none', 'co2' => 'none', 'illuminance' => 'none'];
$room['hvac'] = null; $room['utility_meters'] = null; $room['moods'] = []; $room['floor_heating'] = 'none';
$room['panel'] = array_values(array_filter(array_map(static fn(int $id): ?string => $s['entities'][$id] ?? null, array_keys($panels[$room['id']] ?? []))));
}
unset($room);
if (!$s['view_all']) { $floor['power_entity'] = 'none'; $floor['utility_meters'] = null; }
foreach ($floor['outdoor'] ?? [] as $i => $area) if (!$s['view_all']) {
$floor['outdoor'][$i] = $this->maskRefs($area, $s['native_read']); $floor['outdoor'][$i]['area_id'] = null;
}
}
unset($floor);
if (!$s['view_all']) {
$building['presence'] = []; $building['energy'] = []; $building['settings']['weather_variables'] = [];
foreach ($building['settings'] as $key => $value) if (is_string($value) && $this->variableIdForEntity($value) !== null) $building['settings'][$key] = 'none';
}
return $building;
}
}