/*
   +----------------------------------------------------------------------+
   | Copyright © The PHP Group and Contributors.                          |
   +----------------------------------------------------------------------+
   | This source file is subject to the Modified BSD License that is      |
   | bundled with this package in the file LICENSE, and is available      |
   | through the World Wide Web at <https://www.php.net/license/>.        |
   |                                                                      |
   | SPDX-License-Identifier: BSD-3-Clause                                |
   +----------------------------------------------------------------------+
   | Authors: Scott MacVicar <scottmac@php.net>                           |
   +----------------------------------------------------------------------+
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#if __cplusplus >= 201703L
#include <string_view>
#include <unicode/unistr.h>
#endif

extern "C" {
#include "php_intl.h"
#include "intl_convert.h"
}
#include "spoofchecker_class.h"

/* {{{ Checks if a given text contains any suspicious characters */
U_CFUNC PHP_METHOD(Spoofchecker, isSuspicious)
{
	int32_t ret, errmask;
	zend_string *text;
	zval *error_code = NULL;
	SPOOFCHECKER_METHOD_INIT_VARS;

	ZEND_PARSE_PARAMETERS_START(1, 2)
		Z_PARAM_STR(text)
		Z_PARAM_OPTIONAL
		Z_PARAM_ZVAL(error_code)
	ZEND_PARSE_PARAMETERS_END();

	SPOOFCHECKER_METHOD_FETCH_OBJECT;

	ret = intl_icu_compat_uspoof_check_utf8(co->uspoof, ZSTR_VAL(text), ZSTR_LEN(text), co->uspoofres, SPOOFCHECKER_ERROR_CODE_P(co));

	if (U_FAILURE(SPOOFCHECKER_ERROR_CODE(co))) {
		php_error_docref(NULL, E_WARNING, "(%d) %s", SPOOFCHECKER_ERROR_CODE(co), u_errorName(SPOOFCHECKER_ERROR_CODE(co)));

		if (intl_icu_compat_uspoof_check_result_mismatch(co->uspoofres, ret, &errmask, SPOOFCHECKER_ERROR_CODE_P(co))) {
			php_error_docref(NULL, E_WARNING, "unexpected error (%d), does not relate to the flags passed to setChecks (%d)", ret, errmask);
		}
		RETURN_TRUE;
	}

	if (error_code) {
		ZEND_TRY_ASSIGN_REF_LONG(error_code, ret);
	}
	RETVAL_BOOL(ret != 0);
}
/* }}} */

/* {{{ Checks if a given text contains any confusable characters */
U_CFUNC PHP_METHOD(Spoofchecker, areConfusable)
{
	int ret;
	zend_string *s1, *s2;
	zval *error_code = NULL;
	SPOOFCHECKER_METHOD_INIT_VARS;

	ZEND_PARSE_PARAMETERS_START(2, 3)
		Z_PARAM_STR(s1)
		Z_PARAM_STR(s2)
		Z_PARAM_OPTIONAL
		Z_PARAM_ZVAL(error_code)
	ZEND_PARSE_PARAMETERS_END();

	SPOOFCHECKER_METHOD_FETCH_OBJECT;
	if (UNEXPECTED(ZSTR_LEN(s1) > INT32_MAX || ZSTR_LEN(s2) > INT32_MAX)) {
		SPOOFCHECKER_ERROR_CODE(co) = U_BUFFER_OVERFLOW_ERROR;
	} else {
		ret = uspoof_areConfusableUTF8(co->uspoof, ZSTR_VAL(s1), (int32_t)ZSTR_LEN(s1), ZSTR_VAL(s2), (int32_t)ZSTR_LEN(s2), SPOOFCHECKER_ERROR_CODE_P(co));
	}
	if (U_FAILURE(SPOOFCHECKER_ERROR_CODE(co))) {
		php_error_docref(NULL, E_WARNING, "(%d) %s", SPOOFCHECKER_ERROR_CODE(co), u_errorName(SPOOFCHECKER_ERROR_CODE(co)));
		RETURN_TRUE;
	}

	if (error_code) {
		ZEND_TRY_ASSIGN_REF_LONG(error_code, ret);
	}
	RETVAL_BOOL(ret != 0);
}
/* }}} */

/* {{{ Locales to use when running checks */
U_CFUNC PHP_METHOD(Spoofchecker, setAllowedLocales)
{
	zend_string *locales;
	SPOOFCHECKER_METHOD_INIT_VARS;

	ZEND_PARSE_PARAMETERS_START(1, 1)
		Z_PARAM_STR(locales)
	ZEND_PARSE_PARAMETERS_END();

	SPOOFCHECKER_METHOD_FETCH_OBJECT;

	uspoof_setAllowedLocales(co->uspoof, ZSTR_VAL(locales), SPOOFCHECKER_ERROR_CODE_P(co));

	if (U_FAILURE(SPOOFCHECKER_ERROR_CODE(co))) {
		php_error_docref(NULL, E_WARNING, "(%d) %s", SPOOFCHECKER_ERROR_CODE(co), u_errorName(SPOOFCHECKER_ERROR_CODE(co)));
		return;
	}
}
/* }}} */

/* {{{ Set the checks to run */
U_CFUNC PHP_METHOD(Spoofchecker, setChecks)
{
	zend_long checks;
	SPOOFCHECKER_METHOD_INIT_VARS;

	ZEND_PARSE_PARAMETERS_START(1, 1)
		Z_PARAM_LONG(checks)
	ZEND_PARSE_PARAMETERS_END();

	SPOOFCHECKER_METHOD_FETCH_OBJECT;

	uspoof_setChecks(co->uspoof, checks, SPOOFCHECKER_ERROR_CODE_P(co));

	if (U_FAILURE(SPOOFCHECKER_ERROR_CODE(co))) {
		php_error_docref(NULL, E_WARNING, "(%d) %s", SPOOFCHECKER_ERROR_CODE(co), u_errorName(SPOOFCHECKER_ERROR_CODE(co)));
	}
}
/* }}} */

/* TODO Document this method on PHP.net */
/* {{{ Set the loosest restriction level allowed for strings. */
U_CFUNC PHP_METHOD(Spoofchecker, setRestrictionLevel)
{
	zend_long level;
	SPOOFCHECKER_METHOD_INIT_VARS;

	ZEND_PARSE_PARAMETERS_START(1, 1)
		Z_PARAM_LONG(level)
	ZEND_PARSE_PARAMETERS_END();

	SPOOFCHECKER_METHOD_FETCH_OBJECT;

	if (USPOOF_ASCII != level &&
			USPOOF_SINGLE_SCRIPT_RESTRICTIVE != level &&
			USPOOF_HIGHLY_RESTRICTIVE != level &&
			USPOOF_MODERATELY_RESTRICTIVE != level &&
			USPOOF_MINIMALLY_RESTRICTIVE != level &&
			USPOOF_UNRESTRICTIVE != level) {
		zend_argument_value_error(1, "must be one of Spoofchecker::ASCII, Spoofchecker::SINGLE_SCRIPT_RESTRICTIVE, "
			"Spoofchecker::HIGHLY_RESTRICTIVE, Spoofchecker::MODERATELY_RESTRICTIVE, "
			"Spoofchecker::MINIMALLY_RESTRICTIVE, or Spoofchecker::UNRESTRICTIVE");
		RETURN_THROWS();
	}

	uspoof_setRestrictionLevel(co->uspoof, (URestrictionLevel)level);
}
/* }}} */

U_CFUNC PHP_METHOD(Spoofchecker, setAllowedChars)
{
	zend_string *pattern;
	UChar *upattern = NULL;
	int32_t upattern_len = 0;
	zend_long pattern_option = 0;
	SPOOFCHECKER_METHOD_INIT_VARS;

	ZEND_PARSE_PARAMETERS_START(1, 2)
		Z_PARAM_STR(pattern)
		Z_PARAM_OPTIONAL
		Z_PARAM_LONG(pattern_option)
	ZEND_PARSE_PARAMETERS_END();
	SPOOFCHECKER_METHOD_FETCH_OBJECT;

	if (UNEXPECTED(ZSTR_LEN(pattern) > INT32_MAX)) {
		zend_argument_value_error(1, "must be less than or equal to " ZEND_LONG_FMT " bytes long", INT32_MAX);
		RETURN_THROWS();
	}

	/* uset_applyPattern requires to start with a regex range char */
	if (ZSTR_VAL(pattern)[0] != '[' || ZSTR_VAL(pattern)[ZSTR_LEN(pattern) -1] != ']') {
		zend_argument_value_error(1, "must be a valid regular expression character set pattern");
		RETURN_THROWS();
	}

	intl_convert_utf8_to_utf16(&upattern, &upattern_len, ZSTR_VAL(pattern), ZSTR_LEN(pattern), SPOOFCHECKER_ERROR_CODE_P(co));
	if (U_FAILURE(SPOOFCHECKER_ERROR_CODE(co))) {
		zend_argument_value_error(1, "string conversion to unicode encoding failed (%d) %s", SPOOFCHECKER_ERROR_CODE(co), u_errorName(SPOOFCHECKER_ERROR_CODE(co)));
		RETURN_THROWS();
	}

	USet *set = uset_openEmpty();

	/* pattern is either USE_IGNORE_SPACE alone or in conjunction with the following flags (but mutually exclusive) */
	if (!intl_icu_compat_uspoof_is_allowed_chars_pattern_option(pattern_option)) {
		zend_argument_value_error(2, "%s", intl_icu_compat_uspoof_allowed_chars_pattern_option_error_message());
		uset_close(set);
		efree(upattern);
		RETURN_THROWS();
	}

	uset_applyPattern(set, upattern, upattern_len, (uint32_t)pattern_option, SPOOFCHECKER_ERROR_CODE_P(co));
	if (U_FAILURE(SPOOFCHECKER_ERROR_CODE(co))) {
		zend_argument_value_error(1, "must be a valid regular expression character set pattern (%d) %s", SPOOFCHECKER_ERROR_CODE(co), u_errorName(SPOOFCHECKER_ERROR_CODE(co)));
		uset_close(set);
		efree(upattern);
		RETURN_THROWS();
	}

	uset_compact(set);
	uspoof_setAllowedChars(co->uspoof, set, SPOOFCHECKER_ERROR_CODE_P(co));
	uset_close(set);
	efree(upattern);

	if (U_FAILURE(SPOOFCHECKER_ERROR_CODE(co))) {
		php_error_docref(NULL, E_WARNING, "(%d) %s", SPOOFCHECKER_ERROR_CODE(co), u_errorName(SPOOFCHECKER_ERROR_CODE(co)));
	}
}

/* {{{ Runs an ICU skeleton generator over a UTF-8 string, preflighting the result buffer */
template <typename F>
static zend_string *spoofchecker_skeleton(Spoofchecker_object *co, zend_string *string, F&& skeletonfn)
{
	if (UNEXPECTED(ZSTR_LEN(string) > INT32_MAX)) {
		SPOOFCHECKER_ERROR_CODE(co) = U_BUFFER_OVERFLOW_ERROR;
		intl_errors_set(SPOOFCHECKER_ERROR_P(co), SPOOFCHECKER_ERROR_CODE(co),
			"Failed to convert input string to UTF-16");
		return nullptr;
	}

	u_strFromUTF8(nullptr, 0, nullptr, ZSTR_VAL(string), (int32_t) ZSTR_LEN(string),
		SPOOFCHECKER_ERROR_CODE_P(co));
	if (U_FAILURE(SPOOFCHECKER_ERROR_CODE(co)) && SPOOFCHECKER_ERROR_CODE(co) != U_BUFFER_OVERFLOW_ERROR) {
		intl_errors_set(SPOOFCHECKER_ERROR_P(co), SPOOFCHECKER_ERROR_CODE(co),
			"Failed to convert input string to UTF-16");
		return nullptr;
	}
	SPOOFCHECKER_ERROR_CODE(co) = U_ZERO_ERROR;

	int32_t result_len = skeletonfn(nullptr, 0, SPOOFCHECKER_ERROR_CODE_P(co));
	if (U_FAILURE(SPOOFCHECKER_ERROR_CODE(co)) && SPOOFCHECKER_ERROR_CODE(co) != U_BUFFER_OVERFLOW_ERROR) {
		intl_errors_set(SPOOFCHECKER_ERROR_P(co), SPOOFCHECKER_ERROR_CODE(co),
			"Failed to generate skeleton");
		return nullptr;
	}

	zend_string *result = zend_string_alloc(result_len, false);
	int32_t result_capacity = result_len < INT32_MAX ? result_len + 1 : result_len;
	SPOOFCHECKER_ERROR_CODE(co) = U_ZERO_ERROR;
	result_len = skeletonfn(ZSTR_VAL(result), result_capacity, SPOOFCHECKER_ERROR_CODE_P(co));
	if (U_FAILURE(SPOOFCHECKER_ERROR_CODE(co))) {
		zend_string_release(result);
		intl_errors_set(SPOOFCHECKER_ERROR_P(co), SPOOFCHECKER_ERROR_CODE(co),
			"Failed to generate skeleton");
		return nullptr;
	}
	SPOOFCHECKER_ERROR_CODE(co) = U_ZERO_ERROR;
	ZSTR_LEN(result) = result_len;
	ZSTR_VAL(result)[result_len] = '\0';
	return result;
}
/* }}} */

/* {{{ Get the confusable skeleton for an identifier */
U_CFUNC PHP_METHOD(Spoofchecker, getSkeleton)
{
	zend_string *string;
	SPOOFCHECKER_METHOD_INIT_VARS;

	ZEND_PARSE_PARAMETERS_START(1, 1)
		Z_PARAM_STR(string)
	ZEND_PARSE_PARAMETERS_END();

	SPOOFCHECKER_METHOD_FETCH_OBJECT;

	zend_string *result = spoofchecker_skeleton(co, string,
		[&](char *dest, int32_t capacity, UErrorCode *status) {
			/* The type parameter is deprecated since ICU 58 and must be 0. */
			return uspoof_getSkeletonUTF8(co->uspoof, 0, ZSTR_VAL(string),
				(int32_t) ZSTR_LEN(string), dest, capacity, status);
		});
	if (result == nullptr) {
		RETURN_FALSE;
	}
	RETURN_STR(result);
}
/* }}} */

#if U_ICU_VERSION_MAJOR_NUM >= 74
/* {{{ Get the confusable skeleton for an identifier in a given text direction */
U_CFUNC PHP_METHOD(Spoofchecker, getBidiSkeleton)
{
	zend_long direction;
	zend_string *string;
	SPOOFCHECKER_METHOD_INIT_VARS;

	ZEND_PARSE_PARAMETERS_START(2, 2)
		Z_PARAM_LONG(direction)
		Z_PARAM_STR(string)
	ZEND_PARSE_PARAMETERS_END();

	SPOOFCHECKER_METHOD_FETCH_OBJECT;

	if (direction != UBIDI_LTR && direction != UBIDI_RTL) {
		zend_argument_value_error(1, "must be either Spoofchecker::LTR or Spoofchecker::RTL");
		RETURN_THROWS();
	}

	zend_string *result = spoofchecker_skeleton(co, string,
		[&](char *dest, int32_t capacity, UErrorCode *status) {
			return uspoof_getBidiSkeletonUTF8(co->uspoof, (UBiDiDirection) direction,
				ZSTR_VAL(string), (int32_t) ZSTR_LEN(string), dest, capacity, status);
		});
	if (result == nullptr) {
		RETURN_FALSE;
	}
	RETURN_STR(result);
}
/* }}} */

/* {{{ Checks if a given text contains any confusable characters, for a given text direction */
U_CFUNC PHP_METHOD(Spoofchecker, areBidiConfusable)
{
	uint32_t ret = 0;
	zend_long direction;
	zend_string *s1, *s2;
	zval *error_code = NULL;
	SPOOFCHECKER_METHOD_INIT_VARS;

	ZEND_PARSE_PARAMETERS_START(3, 4)
		Z_PARAM_LONG(direction)
		Z_PARAM_STR(s1)
		Z_PARAM_STR(s2)
		Z_PARAM_OPTIONAL
		Z_PARAM_ZVAL(error_code)
	ZEND_PARSE_PARAMETERS_END();

	SPOOFCHECKER_METHOD_FETCH_OBJECT;

	if (direction != UBIDI_LTR && direction != UBIDI_RTL) {
		zend_argument_value_error(1, "must be either Spoofchecker::LTR or Spoofchecker::RTL");
		RETURN_THROWS();
	}

	if (UNEXPECTED(ZSTR_LEN(s1) > INT32_MAX || ZSTR_LEN(s2) > INT32_MAX)) {
		SPOOFCHECKER_ERROR_CODE(co) = U_BUFFER_OVERFLOW_ERROR;
	} else {
		ret = uspoof_areBidiConfusableUTF8(co->uspoof, (UBiDiDirection)direction, ZSTR_VAL(s1), (int32_t)ZSTR_LEN(s1), ZSTR_VAL(s2), (int32_t)ZSTR_LEN(s2), SPOOFCHECKER_ERROR_CODE_P(co));
	}
	if (U_FAILURE(SPOOFCHECKER_ERROR_CODE(co))) {
		php_error_docref(NULL, E_WARNING, "(%d) %s", SPOOFCHECKER_ERROR_CODE(co), u_errorName(SPOOFCHECKER_ERROR_CODE(co)));
		RETURN_TRUE;
	}

	if (error_code) {
		ZEND_TRY_ASSIGN_REF_LONG(error_code, ret);
	}
	RETVAL_BOOL(ret != 0);
}
/* }}} */
#endif
