<?php
Class SecurityManager {
	public function setFirstSecurityLayer() {
		$this->initHttpHeaders();
	}

	public function setSecondSecurityLayer($postData) {
		return $this->processHttpPostData($postData);
	}

	public function initHttpHeaders() {
		$trusteddomain = '*';
		header('Access-Control-Allow-Origin: '.$trusteddomain);
		header('Content-Type: application/json; charset=utf-8');
	}

	public function processHttpPostDataBackup($postData) {
		if(!isset($postData['action'])) {
			$content = trim(file_get_contents('php://input'));
			$postData = json_decode($content, true);
			if(!isset($postData['action'])) $postData = $postData['data'];
		}

		$postData = $this->decodeReqData($postData);

		return $postData;
	}

	public function processHttpPostData($postData) {
		if(!isset($postData['action'])) {
			try {
				$rawData = trim(file_get_contents('php://input'));
				$jsonDecodedData = json_decode($rawData, true);

				if(json_last_error() === JSON_ERROR_NONE) {
					$postData = $jsonDecodedData;
				} else {
					throw new Exception(json_last_error_msg());
				}
			} catch(Exception $e) {
				$postData = [];
			}
		}

		return $this->decodeReqData($postData);
	}

	private function decodeReqData($postData) {
		$decodedReqData = [];
		foreach($postData as $key => $value) {
			$temp = NULL;
			if(is_string($value)) $temp = json_decode($value, true);
			if($temp != NULL) $decodedReqData[$key] = $temp;
			else $decodedReqData[$key] = $value;
		}

		return $decodedReqData;
	}

	/**
	 * It applies an AntiSQL and AntiXSS filter to an AJAX request data array
	 * passed as parameter
	 *
	 * @param array $reqData contains an AJAX request data
	 *
	 * @return array $reqDataSafe contains a sanitized AJAX request data
	*/
	/*
	private function sanitizeReqData($reqData) {
		//Open connection with mysql DDBB
		$db = new DatabaseManager();

		//Loop over each request data key-value pair
		$reqDataSafe = [];
		foreach($reqData as $key => $value) {
			if(is_array($value)) {
				$reqDataSafe[$key] = $this->sanitizeReqData($value);
			}
			else {
				//Apply AntiSQL Injection filter to value data
				$escValue = $db->getDB()->real_escape_string(trim($value));
				//Apply AntiXSS filter to AntiSQL'd value data
				$reqDataSafe[$key] = htmlspecialchars($escValue);
			}
		}

		//Close connection with mysql DDBB
		$db->closeDB();
		//Return of AntiSQL/XSS request data struct
		return $reqDataSafe;
	}
	*/
}
?>