Skip to content

Commit

Permalink
Validator for CRM URL
Browse files Browse the repository at this point in the history
  • Loading branch information
uryvskiy-dima authored Nov 25, 2022
1 parent 6623f1e commit 4edd426
Show file tree
Hide file tree
Showing 21 changed files with 494 additions and 149 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
## 2022-11-09 4.5.2
* Add validator for CRM URL

## 2022-11-09 4.5.1
* Correction of RAM overflow during ICMP product catalog generation.

Expand Down
2 changes: 1 addition & 1 deletion VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
4.5.1
4.5.2
37 changes: 32 additions & 5 deletions resources/pot/retailcrm-es_ES.pot
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,6 @@ msgstr "Los clientes y pedidos están subidos"
msgid "Enter the correct API key"
msgstr "Introduce la llave API correcta"

msgid "Enter the correct URL of Simla.com"
msgstr "Introduce el enlace del Simla.com correcto"

msgid "This functionality allows to generate ICML products catalog for uploading to Simla.com"
msgstr "Esta función permite generar los catálogos de pedidos ICML para subida al Simla.com"

Expand Down Expand Up @@ -163,7 +160,7 @@ msgstr "Ajustes de API"
msgid "Enter your API key. You can find it in the administration section of Simla.com"
msgstr "Introduce la llave API. Puede encontrarla en apartado administrativo del Simla.com"

msgid "Enter API of URL (https://yourdomain.simla.com)"
msgid "Enter API URL (https://yourdomain.simla.com)"
msgstr "Introduce enlace de API (https://yourdomain.simla.com)"

msgid "Integration with Simla.com management system"
Expand Down Expand Up @@ -341,4 +338,34 @@ msgid "Cron tasks cleared"
msgstr "Trabajos cron borrados"

msgid "Untitled"
msgstr "Intitulado"
msgstr "Intitulado"

msgid "Incorrect protocol. Only https is allowed."
msgstr "Protocolo incorrecto. Sólo se permite https."

msgid "The domain path must be empty."
msgstr "La ruta del dominio debe estar vacía."

msgid "An invalid domain is specified."
msgstr "Se especifica un dominio no válido."

msgid "The port does not need to be specified."
msgstr "No es necesario especificar el puerto."

msgid "Incorrect Host URL."
msgstr "URL del Host incorrecta."

msgid "Incorrect URL."
msgstr "URL incorrecta."

msgid "The query must be blank."
msgstr "La consulta debe estar en blanco."

msgid "The fragment should be blank."
msgstr "El fragmento debe estar en blanco."

msgid "No need to provide authorization data."
msgstr "No es necesario proporcionar datos de autorización."

msgid "Unable to obtain reference values."
msgstr "No se pueden obtener valores de referencia."
34 changes: 30 additions & 4 deletions resources/pot/retailcrm-ru_RU.pot
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,6 @@ msgstr "Клиенты и заказы были выгружены"
msgid "Enter the correct API key"
msgstr "Введите корректный API ключ"

msgid "Enter the correct URL of Simla.com"
msgstr "Введите корректный адрес Simla.com"

msgid "This functionality allows to generate ICML products catalog for uploading to Simla.com"
msgstr "Эта функция позволяет сгенерировать ICML каталог товаров для выгрузки в Simla.com"

Expand Down Expand Up @@ -172,7 +169,7 @@ msgstr "Настройки API"
msgid "Enter your API key. You can find it in the administration section of Simla.com"
msgstr "Введите API ключ. Вы можете найти его в административном разделе Simla.com"

msgid "Enter API of URL (https://yourdomain.simla.com)"
msgid "Enter API URL (https://yourdomain.simla.com)"
msgstr "Введите API URL (https://yourdomain.simla.com)"

msgid "Integration with Simla.com management system"
Expand Down Expand Up @@ -352,3 +349,32 @@ msgstr "Cron задачи очищены"
msgid "Untitled"
msgstr "Без названия"

msgid "Incorrect protocol. Only https is allowed."
msgstr "Некорректный протокол. Допускается только https."

msgid "The domain path must be empty."
msgstr "Путь к домену должен быть пустым."

msgid "An invalid domain is specified."
msgstr "Указан недопустимый домен."

msgid "The port does not need to be specified."
msgstr "Не нужно указывать порт."

msgid "Incorrect Host URL."
msgstr "Некорректный URL хоста"

msgid "Incorrect URL."
msgstr "Некорректный URL."

msgid "The query must be blank."
msgstr "Запрос должен быть пустым."

msgid "The fragment should be blank."
msgstr "Фрагмент должен быть пустым."

msgid "No need to provide authorization data."
msgstr "Нет необходимости предоставлять авторизационные данные."

msgid "Unable to obtain reference values."
msgstr "Не удалось получить эталонное значение"
63 changes: 24 additions & 39 deletions src/include/abstracts/class-wc-retailcrm-abstracts-settings.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,12 @@ abstract class WC_Retailcrm_Abstracts_Settings extends WC_Integration
/** @var string */
public static $option_key;

/** @var WC_Retailcrm_Url_Validator*/
private $urlValidator;

/** @var string */
private $crmUrl;

/**
* WC_Retailcrm_Abstracts_Settings constructor.
*/
Expand All @@ -39,6 +45,9 @@ public function __construct()
) {
add_action('init', [$this, 'init_settings_fields'], 99);
}

// Initialization validator
$this->urlValidator = new WC_Retailcrm_Url_Validator();
}

/**
Expand Down Expand Up @@ -75,7 +84,7 @@ public function init_form_fields()
'api_url' => [
'title' => __('API of URL', 'retailcrm'),
'type' => 'text',
'description' => __( 'Enter API of URL (https://yourdomain.simla.com)', 'retailcrm' ),
'description' => __('Enter API URL (https://yourdomain.simla.com)', 'retailcrm'),
'desc_tip' => true,
'default' => ''
],
Expand All @@ -88,10 +97,6 @@ public function init_form_fields()
]
];

$post = $this->get_post_data();
$apiUrl = !empty($post[$this->plugin_id . $this->id . '_api_url']) ? $post[$this->plugin_id . $this->id . '_api_url'] : null;
$apiKey = !empty($post[$this->plugin_id . $this->id . '_api_key']) ? $post[$this->plugin_id . $this->id . '_api_key'] : null;

if ($this->apiClient) {
if (
isset($_GET['page']) && $_GET['page'] == 'wc-settings'
Expand Down Expand Up @@ -153,7 +158,6 @@ public function init_form_fields()
'type' => 'checkbox',
'desc_tip' => true,
];

}

/**
Expand Down Expand Up @@ -579,18 +583,6 @@ public function init_form_fields()
'id' => 'clear_cron_tasks'
];
}
} elseif (empty($apiUrl) === false && empty($apiKey) === false) {
$api = new WC_Retailcrm_Proxy(
$apiUrl,
$apiKey,
$this->get_option('corporate_enabled', 'no') === 'yes'
);

$response = $api->apiVersions();

if ($response->isSuccessful()) {
header("Refresh:0");
}
}
}

Expand Down Expand Up @@ -686,7 +678,7 @@ public function validate_online_assistant_field($key, $value)
}

/**
* Validate API url
* Validate CRM URL.
*
* @param string $key
* @param string $value
Expand All @@ -697,14 +689,17 @@ public function validate_online_assistant_field($key, $value)
*/
public function validate_api_url_field($key, $value)
{
$crmUrl = validateUrl($value);
$validateMessage = $this->urlValidator->validateUrl($value);

if (validateUrl($crmUrl) == '') {
WC_Admin_Settings::add_error(esc_html__('Enter the correct URL of Simla.com', 'retailcrm'));
header("Refresh:3");
if ('' !== $validateMessage) {
$value = '';

WC_Admin_Settings::add_error(esc_html__($validateMessage, 'retailcrm'));
}

return $crmUrl;
$this->crmUrl = $value;

return $value;
}

/**
Expand All @@ -719,30 +714,20 @@ public function validate_api_url_field($key, $value)
*/
public function validate_api_key_field($key, $value)
{
$crmUrl = $_POST['woocommerce_integration-retailcrm_api_url'];

// If entered the wrong URL, don't need to validate the API key.
if (validateUrl($crmUrl) == '') {
if ('' === $this->crmUrl) {
return $value;
}

$api = new WC_Retailcrm_Proxy(
$crmUrl,
$value,
$this->get_option('corporate_enabled', 'no') === 'yes'
);

$api = new WC_Retailcrm_Proxy($this->crmUrl, $value);
$response = $api->apiVersions();

if (!is_object($response)) {
if (empty($response) || !$response->isSuccessful()) {
$value = '';
}

if (empty($response) || !$response->isSuccessful()) {
WC_Admin_Settings::add_error(esc_html__('Enter the correct API key', 'retailcrm'));
header("Refresh:3");

$value = '';
} else {
header("Refresh:0");
}

return $value;
Expand Down
3 changes: 0 additions & 3 deletions src/include/api/class-wc-retailcrm-client-v5.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,6 @@ class WC_Retailcrm_Client_V5
* @param string $url api url
* @param string $apiKey api key
* @param string $site site code
*
* @throws InvalidArgumentException
*
*/
public function __construct($url, $apiKey, $site = null)
{
Expand Down
2 changes: 1 addition & 1 deletion src/include/api/class-wc-retailcrm-proxy.php
Original file line number Diff line number Diff line change
Expand Up @@ -138,4 +138,4 @@ public function __call($method, $arguments)
return !empty($response) ? $response : new WC_Retailcrm_Response(900, '{}');
}
}
endif;
endif;
9 changes: 1 addition & 8 deletions src/include/api/class-wc-retailcrm-request.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,16 +33,9 @@ class WC_Retailcrm_Request
* @param string $url api url
* @param array $defaultParameters array of parameters
*
* @throws \InvalidArgumentException
*/
public function __construct($url, array $defaultParameters = array())
public function __construct($url, array $defaultParameters = [])
{
if (false === stripos($url, 'https://')) {
throw new \InvalidArgumentException(
'API schema requires HTTPS protocol'
);
}

$this->url = $url;
$this->defaultParameters = $defaultParameters;
}
Expand Down
13 changes: 0 additions & 13 deletions src/include/functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -137,19 +137,6 @@ function is_wplogin()
);
}


/**
* Validate API url.
*
* @param string $url URL of Simla.com.
*
* @return string
*/
function validateUrl(string $url)
{
return (preg_match("/https:\/\/(.*).(retailcrm.(pro|ru|es)|simla.com)/", $url)) ? $url : '';
}

/**
* Get shipping rate.
*
Expand Down
10 changes: 10 additions & 0 deletions src/include/validators/class-wc-retailcrm-validator-exception.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

class ValidatorException extends Exception
{
public function __construct(string $message = '', int $code = 0)
{
// Add filter, if you need customization message of exception
parent::__construct(apply_filters('retailcrm_validator_message', $message), $code);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
<?php

if (!class_exists('WC_Retailcrm_Url_Constraint')) :
/**
* PHP version 7.0
*
* Class WC_Retailcrm_Url_Constraint - Constraint for CRM URL.
*
* @category Integration
* @author RetailCRM <[email protected]>
* @license http://retailcrm.ru Proprietary
* @link http://retailcrm.ru
* @see http://help.retailcrm.ru
*/
class WC_Retailcrm_Url_Constraint
{
/**
* @var string
*/
public $schemeFail = 'Incorrect protocol. Only https is allowed.';

/**
* @var string
*/
public $pathFail = 'The domain path must be empty.';

/**
* @var string
*/
public $portFail = 'The port does not need to be specified.';

/**
* @var string
*/
public $domainFail = 'An invalid domain is specified.';

/**
* @var string
*/
public $noValidUrlHost = 'Incorrect Host URL.';

/**
* @var string
*/
public $noValidUrl = 'Incorrect URL.';

/**
* @var string
*/
public $queryFail = 'The query must be blank.';

/**
* @var string
*/
public $fragmentFail = 'The fragment should be blank.';

/**
* @var string
*/
public $authFail = 'No need to provide authorization data.';

/**
* @var string
*/
public $getFileError = 'Unable to obtain reference values.';
}
endif;
Loading

0 comments on commit 4edd426

Please sign in to comment.