219 lines
6.9 KiB
PHP
219 lines
6.9 KiB
PHP
<?php
|
||
// error_reporting(E_ALL | E_STRICT);
|
||
// ini_set('display_errors', 1);
|
||
require_once($_SERVER['DOCUMENT_ROOT']."/ajax/vue_php_function.php");
|
||
require_once($_SERVER['DOCUMENT_ROOT']."/api/complex/Controllers/MediaController.php");
|
||
|
||
function handleCors() {
|
||
header("Access-Control-Allow-Origin: *");
|
||
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
|
||
header("Access-Control-Allow-Headers: Content-Type, Authorization");
|
||
header('Content-Type: application/json');
|
||
|
||
|
||
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
|
||
http_response_code(200);
|
||
exit();
|
||
}
|
||
}
|
||
|
||
handleCors();
|
||
|
||
$authUser = null;
|
||
$method = $_SERVER['REQUEST_METHOD'];
|
||
$uri = $_SERVER['REQUEST_URI'];
|
||
|
||
$uri = str_replace('/api/complex', '', $uri);
|
||
$uri = strtok($uri, '?');
|
||
|
||
$segments = explode('/', trim($uri, '/'));
|
||
|
||
$controller = new MediaController();
|
||
|
||
$routes = [
|
||
'home/{homeId}/media/completion' => [
|
||
'GET' => ['action' => 'getHouseMediaCompletionPercentage', 'middleware' => ['auth', 'can:view|modify']],
|
||
],
|
||
'home/{homeId}/media/thumbnails' => [
|
||
'GET' => ['action' => 'getMediaThumbnails', 'middleware' => ['auth', 'can:view|modify']],
|
||
],
|
||
'home/{homeId}/media/{media_id}' => [
|
||
'DELETE' => ['action' => 'delete', 'middleware' => ['auth', 'can:modify']],
|
||
],
|
||
'home/{homeId}/media' => [
|
||
'GET' => ['action' => 'index', 'middleware' => ['auth', 'can:view|modify']],
|
||
'POST' => ['action' => 'store', 'middleware' => ['auth', 'can:modify']],
|
||
],
|
||
'home/{homeId}/media-sets/{set_id}/rooms' => [
|
||
'POST' => ['action' => 'connectSetToRooms', 'middleware' => ['auth', 'can:modify']],
|
||
],
|
||
'home/{homeId}/media-sets/{set_id}' => [
|
||
'DELETE' => ['action' => 'deleteMediaSet', 'middleware' => ['auth', 'can:modify']],
|
||
'PUT' => ['action' => 'updateMediaSet', 'middleware' => ['auth', 'can:modify']],
|
||
],
|
||
'home/{homeId}/media-sets' => [
|
||
'POST' => ['action' => 'createMediaSet', 'middleware' => ['auth', 'can:modify']],
|
||
'GET' => ['action' => 'getMediaSets', 'middleware' => ['auth', 'can:view|modify']],
|
||
],
|
||
'home/{homeId}/room/{roomId}/media' => [
|
||
'GET' => ['action' => 'getMediaSetForRoom', 'middleware' => ['auth', 'can:view|modify']],
|
||
],
|
||
];
|
||
|
||
$segmentCount = count($segments);
|
||
$queryParams = [];
|
||
if (!empty($_SERVER['QUERY_STRING'])) {
|
||
parse_str($_SERVER['QUERY_STRING'], $queryParams);
|
||
}
|
||
|
||
|
||
foreach ($routes as $pattern => $methods) {
|
||
$patternSegments = explode('/', $pattern);
|
||
|
||
// Quick segment count check
|
||
if ($segmentCount !== count($patternSegments)) continue;
|
||
|
||
$params = [];
|
||
$match = true;
|
||
foreach ($patternSegments as $i => $patSegment) {
|
||
if (substr($patSegment, 0, 1) === '{' && substr($patSegment, -1) === '}') {
|
||
$paramName = trim($patSegment, '{}');
|
||
$params[$paramName] = $segments[$i];
|
||
} elseif ($patSegment !== $segments[$i]) {
|
||
$match = false;
|
||
break;
|
||
}
|
||
}
|
||
|
||
if ($match && isset($methods[$method])) {
|
||
$routeConfig = $methods[$method];
|
||
$action = null;
|
||
|
||
if (is_string($routeConfig)) {
|
||
$action = $routeConfig;
|
||
$middlewares = [];
|
||
} else {
|
||
$action = $routeConfig['action'];
|
||
$middlewares = isset($routeConfig['middleware']) ? $routeConfig['middleware'] : [];
|
||
}
|
||
|
||
foreach ($middlewares as $mw) {
|
||
switch ($mw) {
|
||
case 'auth':
|
||
authenticate($params);
|
||
break;
|
||
case 'can:view|modify':
|
||
if (!canModifyResource($authUser) && !canViewResource($authUser)) {
|
||
unauthorized('Неправильные доступы.');
|
||
}
|
||
break;
|
||
case 'can:modify':
|
||
if ($_SESSION['pay']) {
|
||
unauthorized('Вы не сможете отредактировать медиаматериалы, так как у вас не оплачен тариф.');
|
||
}
|
||
|
||
if (!canModifyResource($authUser)) {
|
||
unauthorized('Неправильные доступы отредактирования.');
|
||
}
|
||
|
||
break;
|
||
}
|
||
}
|
||
|
||
$body = null;
|
||
if ($method === 'POST' || $method === 'PUT') {
|
||
// For form-urlencoded or multipart/form-data
|
||
$body = [
|
||
'fields' => $_POST
|
||
];
|
||
|
||
// If you expect JSON payload
|
||
$input = file_get_contents('php://input');
|
||
if ($input) {
|
||
$decoded = json_decode($input, true);
|
||
if ($decoded) {
|
||
$body = [
|
||
'fields' => $decoded
|
||
];
|
||
}
|
||
}
|
||
|
||
if (count($_FILES)) {
|
||
$body['files'] = $_FILES;
|
||
}
|
||
}
|
||
|
||
// Call the controller dynamically
|
||
if (strpos($action, 'delete') !== false) {
|
||
$entityId = isset($segments[3]) ? (int)$segments[3] : null;
|
||
$controller->$action((int)$params['homeId'], $entityId);
|
||
} elseif ($method === 'POST' || $method === 'PUT') {
|
||
$controller->$action($params, $body);
|
||
} else {
|
||
$controller->$action($params, $queryParams);
|
||
}
|
||
}
|
||
}
|
||
|
||
function authenticate($params)
|
||
{
|
||
global $controller, $authUser;
|
||
|
||
$sessionId = null;
|
||
$session = $_SESSION;
|
||
|
||
if (!isset($session['id']) || !$session['id']) {
|
||
unauthorized('Требуется авторизация.');
|
||
}
|
||
|
||
$sessionId = $session['id'];
|
||
|
||
$authUser = $controller->findUser($sessionId);
|
||
|
||
if (!validateSession($sessionId, $authUser, $params)) {
|
||
unauthorized('Invalid session');
|
||
}
|
||
}
|
||
|
||
function unauthorized($message = 'Unauthorized')
|
||
{
|
||
http_response_code(401);
|
||
echo json_encode(['error' => $message]);
|
||
exit;
|
||
}
|
||
|
||
function validateSession($sessionId, $authUser, $params)
|
||
{
|
||
global $controller;
|
||
|
||
if (!isset($authUser['id']))
|
||
return false;
|
||
|
||
$houseComplexAgencyId = $controller->findHouseComplexAgency($params['homeId']);
|
||
|
||
return $authUser && ($authUser['id'] == $sessionId) && $houseComplexAgencyId === $_SESSION['agency_id'];
|
||
}
|
||
|
||
function canModifyResource($authUser)
|
||
{
|
||
if (!isset($_SESSION['ahatnc']))
|
||
return false;
|
||
|
||
$agenciesHaveAccessToNewComplexes = unserialize(base64_decode($_SESSION['ahatnc']));
|
||
|
||
$userModel = new User;
|
||
$hasMenuPermission = $userModel->checkMenuPermissions("menu_complexes");
|
||
$authUserHasPermission = ($authUser['agency'] || $authUser['users_admin'] || $hasMenuPermission);
|
||
$agencyHasPermission = in_array($_SESSION['agency_id'] , $agenciesHaveAccessToNewComplexes);
|
||
|
||
if ($hasMenuPermission || ($authUserHasPermission && $agencyHasPermission)) {
|
||
return true;
|
||
}
|
||
|
||
return false;
|
||
}
|
||
|
||
function canViewResource($authUser)
|
||
{
|
||
return $authUser['role_developer'];
|
||
} |