Skip to content
Snippets Groups Projects
context.php 2.37 KiB
Newer Older
<?php

namespace SmartData;
require_once('../bin/smartdata/SmartAPI.php');
require_once('../bin/smartdata/Config.php');

use SmartData\Exception\CustomException;

function context($url, $domain, $content) {

    if (substr( $url, 0, 5 ) != "/docs" && substr( $url, 0, 8 ) != "/openapi") {
        $url = $url . "/$domain";
        header('Content-Type: application/json');
    }

    if (substr( $url, 0, 4 ) == "/get") {
        $url = $url . "/" . $content['smartDataContextId'];
    }

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL,  Config::config()::SMARTDATACONTEXT_API . "$url");

    if (substr( $url, 0, 4 ) != "/get" && substr( $url, 0, 5 ) != "/docs" && substr( $url, 0, 8 ) != "/openapi") {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($content));
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json'
        ));
    }

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $response = curl_exec($ch);
    $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    if ($http_status == 0) {
        # Could not connect to the smartdatacontext API
        $http_status = 503; # Service Unavailable
        $response = '{"errors": ["SmartDataContext API not available"]}';
    }

    http_response_code($http_status);
    return $response;
}

try {
    if (array_key_exists('docs', $_GET)) {
        echo context("/docs", null, null);
    } else if (array_key_exists('openapi', $_GET)) {
        echo context("/openapi", null, null);
    } else {
        $content = file_get_contents('php://input');
        $json = json_decode($content, false, 512, JSON_BIGINT_AS_STRING);

        // Validate certificate usage and domain usage
        $credentials = null;
        if(isset($json->credentials))
            $credentials = Credentials::fromJson($json->credentials);
        $backend = new Backend($credentials);

        $json = json_decode($content, true, 512, JSON_BIGINT_AS_STRING);

        // Pass the request to the smartdatacontext backend and retrieve result
        echo context($json['command'], $backend->domainInUse(), $json['request']);    }
} catch (CustomException $e) {
    http_response_code($e->getHTTPCodeError());
    header('X-Message: ' . $e->getMessage(), false);
    return false;
} catch (\Exception $e) {
    http_response_code(HttpStatusCode::BAD_REQUEST);
    return false;
}