#!/usr/bin/env php
<?php
/*************************************
 * SPDX-FileCopyrightText: 2009-present Vtenext S.r.l. Società Benefit
 * SPDX-License-Identifier: LicenseRef-vtenext-business-license
 ************************************/
// crmv@370640

require(__DIR__ . '/../config.inc.php');
if (empty($root_directory)) {
	Update::log("");
	Update::warn("Vtenext not installed\n");
	exit(1);
}

chdir($root_directory);
require_once('include/utils/utils.php');

$it = new RecursiveDirectoryIterator('./');
$exts = ['php', 'inc'];

$includeDirs = ['./hub', './include/utils', './modules'];
$excludeDirs = ['./hub/oidc', './hub/saml', './modules/Update/changes'];

$excludeFiles = [
	'./hub/app_extlogin.php',
	'./hub/oauthret.php',
	'./include/utils/RequestHandler.php',
	'./include/utils/VTEProperties.php',
	'./modules/Touch/MessageContent.php',
];

$patterns = [
	'/(?<!unset\()\$_REQUEST\s*\[\s*[\'"]([^\'\"]+)[\'"]\s*\](?!\s*=)/',
];

$foundKeys = [];

if (file_exists('config/request.config.override.php')) {
	$success = rename('config/request.config.override.php', 'config/request.config.override.php.bak');
	if (!$success) {
		Update::log("");
		Update::warn("Unable to rename config/request.config.override.php. Please check the file permissions and rename it manually to config/request.config.override.php.bak\n");
		exit(1);
	}
}

$predefinedFilters = [];
if (file_exists('config/request.config.php')) {
	$defaultConfig = include 'config/request.config.php';
	if (isset($defaultConfig['safe_keys']) && is_array($defaultConfig['safe_keys'])) {
		$predefinedFilters = $defaultConfig['safe_keys'];
	}
}

foreach (new RecursiveIteratorIterator($it) as $file) {
	$ext = strtolower(array_pop(explode('.', $file)));
	$dir = dirname($file);
	$filePath = (string)$file;

	if (!in_array($ext, $exts)) {
		continue;
	}

	$inIncludeDir = false;
	foreach ($includeDirs as $idir) {
		if (substr($dir, 0, strlen($idir)) === $idir) {
			$inIncludeDir = true;
			break;
		}
	}
	if (!$inIncludeDir) {
		continue;
	}

	foreach ($excludeDirs as $edir) {
		if (substr($dir, 0, strlen($edir)) === $edir) {
			continue 2;
		}
	}

	if (in_array($filePath, $excludeFiles)) {
		continue;
	}

	$content = file_get_contents($filePath);
	if ($content === false) {
		continue;
	}

	foreach ($patterns as $pattern) {
		if (preg_match_all($pattern, $content, $matches)) {
			foreach ($matches[1] as $key) {
				if (!isset($foundKeys[$key]) && !array_key_exists($key, $predefinedFilters)) {
					$filter = 'F::html';
					$foundKeys[$key] = [$filter, $filePath];
				}
			}
		}
	}
}

if (!empty($foundKeys)) {
	$configContent = "<?php\n";
	$configContent .= "/*************************************\n";
	$configContent .= " * SPDX-FileCopyrightText: 2009-present Vtenext S.r.l. Società Benefit \n";
	$configContent .= " * SPDX-License-Identifier: LicenseRef-vtenext-business-license \n";
	$configContent .= " ************************************/\n\n";
	$configContent .= "// mycrmv@updater\n\n";
	$configContent .= "return [\n";
	$configContent .= "\t'safe_keys' => [\n";

	ksort($foundKeys);

	foreach ($foundKeys as $key => $info) {
		$filter = $info[0];
		$path = $info[1];
		$configContent .= "\t\t'$key' => $filter, // $path\n";
	}

	$configContent .= "\t],\n";
	$configContent .= "];\n";

	$overrideFilePath = './config/request.config.override.php';
	file_put_contents($overrideFilePath, $configContent);

	Update::log("");
	Update::warn("The file 'config/request.config.override.php' has been generated with the \$_REQUEST keys found in the code that are not yet filtered.");
	Update::warn("Please review the file and adjust the filters as needed to ensure proper input sanitization.");
} else {
    Update::log("");
    Update::log("No unfiltered \$_REQUEST keys found in the code.");
}