<?php

error_reporting(0);

try {
    //      Parse JSON
    $json = file_get_contents('php://input');
    if ($json === FALSE)
        throw new Exception('Bad Request');

    //      Decode JSON
    $estple = json_decode($json, TRUE);
    if (is_null($estple))
        throw new Exception('Bad JSON Violation');

    //      Create a connection to MySQL Database
    $mysql = mysqli_connect('localhost', 'cspviolationshj', 'ASDFasdjh;la4h', 'cspviolations');

    //	    Look for unexpected keys
    $known_keys = array('date-time' => 1, 'hostname' => 1, 'port' => 1, 'response-status' => 1, 'ocsp-response' => 1, 'cert-status' => 1, 'served-certificate-chain' => 1, 'validated-certificate-chain' => 1);
    $diff = array_diff_key($estple, $known_keys);
    if(count($diff) > 0)
    	$newDirectives = mysqli_real_escape_string($mysql, var_export($diff, true));
    else
	$newDirectives = "";
    

    //      Escape your data
    $dateTime = mysqli_real_escape_string($mysql, $estple['date-time']);
    $hostname = mysqli_real_escape_string($mysql, $estple['hostname']);
    $port = mysqli_real_escape_string($mysql, $estple['port']);
    $responseStatus = mysqli_real_escape_string($mysql, $estple['response-status']);
    $ocspResponse = mysqli_real_escape_string($mysql, $estple['ocsp-response']);
    $certStatus = mysqli_real_escape_string($mysql, $estple['cert-status']);
    $servedCertificateChain = mysqli_real_escape_string($mysql, implode("\n\n", $estple['served-certificate-chain']));
    $validatedCertificateChain = mysqli_real_escape_string($mysql, implode("\n\n", $estple['validated-certificate-chain']));
    $ip = mysqli_real_escape_string($mysql, $_SERVER['REMOTE_ADDR']);

    //      Log Violations
    $query = "
INSERT INTO
    expectstapleViolations_tbl
SET
    dateTime = '$dateTime',
    hostname = '$hostname',
    port = '$port',
    responseStatus = '$responseStatus',
    ocspResponse = '$ocspResponse',
    certStatus = '$certStatus',
    servedCertificateChain = '$servedCertificateChain',
    validatedCertificateChain = '$validatedCertificateChain',
    createdDateTime = NOW(),
    ipAddress = '$ip',
    newDirectives = '$newDirectives' ";

    if(!mysqli_query($mysql, $query)) echo("Error description: " . mysqli_error($mysql));
    mysqli_close($mysql);


} catch(Exception $e) {
}

?>