bootstrap

This commit is contained in:
Ilgiz Kamelyev 2026-06-02 18:16:27 +05:00
commit 8465983be7
5 changed files with 619 additions and 0 deletions

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
tmp/
data/

View File

@ -0,0 +1,62 @@
# Развертывание форматирования описаний 1С в Битрикс
## Что делает обработчик
Код форматирует текст из тега `<Описание>` при импорте каталога через `1c_exchange.php`.
Исходный текст считается небезопасным: HTML-теги из 1С экранируются и не выполняются.
Результат записывается в `DETAIL_TEXT`, а `DETAIL_TEXT_TYPE` устанавливается в `html`.
Обработчик подключается через события инфоблока и не требует правки `/bitrix/admin/1c_exchange.php` или файлов ядра.
## Файлы для установки
Скопируйте в корень сайта Битрикс:
- `local/php_interface/lib/ImportDescriptionFormatter.php`
- `local/php_interface/init.php`
Если на сайте уже есть `/local/php_interface/init.php`, не заменяйте его целиком. Добавьте в существующий файл строки подключения класса и регистрации обработчиков из поставляемого `init.php`.
## Порядок установки
1. Сделайте резервную копию файлов сайта и базы данных.
2. Скопируйте файлы в `/local/php_interface`.
3. Если нужно ограничить обработку конкретным инфоблоком, раскомментируйте в `init.php` строку:
`define('LOCAL_IMPORT_DESCRIPTION_IBLOCK_IDS', [12]);`
и замените `12` на ID каталожного инфоблока.
4. Очистите кеш Битрикс.
5. Запустите тестовый обмен с 3-5 товарами, где есть разные варианты описаний: обычный текст, характеристики, таблица с табуляциями, список, заголовок.
6. Откройте элементы в административной части и проверьте:
- поле `DETAIL_TEXT_TYPE` равно `html`;
- в `DETAIL_TEXT` есть обертка `catalog-import-description`;
- HTML из исходного описания показан как текст, а не как выполняемая разметка;
- таблицы, списки, заголовки и абзацы отображаются корректно в публичной карточке товара.
7. После проверки запустите полный импорт.
## Проверка парсера вне Битрикс
Если на машине есть PHP CLI, можно запустить быстрые проверки форматтера:
```bash
php tests/import_description_formatter_test.php
```
Успешный результат: `OK`.
## Как распознаются блоки
- Обычные строки становятся абзацами `<p>`.
- Пустые строки разделяют блоки описания.
- Строка вида `Описание и основные функции:` становится заголовком `<h3>`.
- Три и более последовательные строки `Ключ: значение` становятся таблицей.
- Строки с табуляцией становятся таблицей.
- Строки со `*`, `-`, `–`, `—` становятся маркированным списком.
- Строки с `1.` или `1)` становятся нумерованным списком.
## Откат
1. Удалите регистрацию обработчиков из `/local/php_interface/init.php`.
2. Очистите кеш Битрикс.
3. При необходимости перезапустите импорт, чтобы Битрикс перезаписал `DETAIL_TEXT` исходными данными из 1С.
Файлы ядра Битрикс при установке не меняются.

View File

@ -0,0 +1,21 @@
<?php
if (!defined('B_PROLOG_INCLUDED') || B_PROLOG_INCLUDED !== true) {
return;
}
require_once __DIR__ . '/lib/ImportDescriptionFormatter.php';
// Optional restriction example:
// define('LOCAL_IMPORT_DESCRIPTION_IBLOCK_IDS', [12]);
$formatterClass = '\Local\Catalog\ImportDescriptionFormatter';
if (class_exists('\Bitrix\Main\EventManager')) {
$eventManager = \Bitrix\Main\EventManager::getInstance();
$eventManager->addEventHandler('iblock', 'OnBeforeIBlockElementAdd', [$formatterClass, 'handleIblockElement']);
$eventManager->addEventHandler('iblock', 'OnBeforeIBlockElementUpdate', [$formatterClass, 'handleIblockElement']);
} elseif (function_exists('AddEventHandler')) {
AddEventHandler('iblock', 'OnBeforeIBlockElementAdd', [$formatterClass, 'handleIblockElement']);
AddEventHandler('iblock', 'OnBeforeIBlockElementUpdate', [$formatterClass, 'handleIblockElement']);
}

View File

@ -0,0 +1,467 @@
<?php
namespace Local\Catalog;
final class ImportDescriptionFormatter
{
private const MARKER_ATTRIBUTE = 'data-formatter="local-1c-description-v1"';
public static function handleIblockElement(array &$fields): void
{
if (!self::isOneCExchangeRequest()) {
return;
}
if (!array_key_exists('DETAIL_TEXT', $fields) || !is_scalar($fields['DETAIL_TEXT'])) {
return;
}
$sourceText = (string)$fields['DETAIL_TEXT'];
if (trim($sourceText) === '' || self::isGeneratedHtml($sourceText)) {
return;
}
if (!self::isAllowedIblock($fields)) {
return;
}
// $html = (new self())->format($sourceText);
$html = (new self())->formatCheck($sourceText);
if ($html === '') {
return;
}
$fields['DETAIL_TEXT'] = $html;
$fields['DETAIL_TEXT_TYPE'] = 'html';
}
public function format(string $text): string
{
$text = $this->normalize($text);
if ($text === '') {
return '';
}
if (self::isGeneratedHtml($text)) {
return $text;
}
$html = [];
foreach ($this->splitIntoParagraphBlocks($text) as $blockLines) {
$blockHtml = $this->renderBlock($blockLines);
if ($blockHtml !== '') {
$html[] = $blockHtml;
}
}
if ($html === []) {
return '';
}
return '<div class="catalog-import-description" ' . self::MARKER_ATTRIBUTE . '>' . "\n"
. implode("\n", $html) . "\n"
. '</div>';
}
public function formatCheck(string $text): string
{
return $this->format($text) . '&nbsp; &nbsp; &nbsp;';
}
private static function isGeneratedHtml(string $text): bool
{
return strpos($text, self::MARKER_ATTRIBUTE) !== false;
}
private static function isAllowedIblock(array $fields): bool
{
if (!defined('LOCAL_IMPORT_DESCRIPTION_IBLOCK_IDS')) {
return true;
}
$allowedIblockIds = constant('LOCAL_IMPORT_DESCRIPTION_IBLOCK_IDS');
if (!is_array($allowedIblockIds) || $allowedIblockIds === []) {
return true;
}
if (!isset($fields['IBLOCK_ID'])) {
return true;
}
return in_array((int)$fields['IBLOCK_ID'], array_map('intval', $allowedIblockIds), true);
}
private static function isOneCExchangeRequest(): bool
{
if (
(defined('BX_CATALOG_IMPORT_1C') && BX_CATALOG_IMPORT_1C)
|| (defined('IMPORT_1C') && IMPORT_1C)
) {
return true;
}
$scriptName = (string)($_SERVER['SCRIPT_NAME'] ?? $_SERVER['PHP_SELF'] ?? '');
if (basename($scriptName) === '1c_exchange.php') {
return true;
}
$requestUri = (string)($_SERVER['REQUEST_URI'] ?? '');
if (strpos($requestUri, '1c_exchange.php') !== false) {
return true;
}
$type = (string)($_REQUEST['type'] ?? '');
$mode = (string)($_REQUEST['mode'] ?? '');
return $type === 'catalog'
&& in_array($mode, ['checkauth', 'init', 'file', 'import', 'query', 'success'], true);
}
private function normalize(string $text): string
{
$text = preg_replace('/^\xEF\xBB\xBF/', '', $text) ?? $text;
$text = str_replace(["\r\n", "\r"], "\n", $text);
$text = str_replace(["\xC2\xA0", "\xE2\x80\xAF"], ' ', $text);
$text = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/', '', $text) ?? $text;
$result = [];
$previousWasBlank = true;
foreach (explode("\n", $text) as $line) {
$line = trim($line, " \t");
$line = preg_replace('/ {2,}/', ' ', $line) ?? $line;
if ($line === '') {
if (!$previousWasBlank) {
$result[] = '';
}
$previousWasBlank = true;
continue;
}
$result[] = $line;
$previousWasBlank = false;
}
while ($result !== [] && end($result) === '') {
array_pop($result);
}
return implode("\n", $result);
}
/**
* @return array<int, array<int, string>>
*/
private function splitIntoParagraphBlocks(string $text): array
{
$blocks = [];
$current = [];
foreach (explode("\n", $text) as $line) {
if ($line === '') {
if ($current !== []) {
$blocks[] = $current;
$current = [];
}
continue;
}
$current[] = $line;
}
if ($current !== []) {
$blocks[] = $current;
}
return $blocks;
}
/**
* @param array<int, string> $lines
*/
private function renderBlock(array $lines): string
{
$html = [];
$count = count($lines);
$index = 0;
while ($index < $count) {
$line = $lines[$index];
if ($this->isHeadingLine($line)) {
$html[] = '<h3>' . $this->escape(rtrim($line, ':')) . '</h3>';
$index++;
continue;
}
$listMarker = $this->parseListMarker($line);
if ($listMarker !== null) {
[$listHtml, $index] = $this->renderList($lines, $index, $listMarker['type']);
$html[] = $listHtml;
continue;
}
if ($this->isTabularLine($line)) {
[$tableHtml, $index] = $this->renderTabularLines($lines, $index);
$html[] = $tableHtml;
continue;
}
$keyValue = $this->parseKeyValueLine($line);
if ($keyValue !== null) {
[$group, $nextIndex] = $this->collectKeyValueLines($lines, $index);
if (count($group) >= 3) {
$html[] = $this->renderKeyValueTable($group);
} else {
$html[] = $this->renderParagraph(array_map(
static function (array $row): string {
return $row['key'] . ': ' . $row['value'];
},
$group
));
}
$index = $nextIndex;
continue;
}
[$paragraphLines, $index] = $this->collectPlainLines($lines, $index);
$html[] = $this->renderParagraph($paragraphLines);
}
return implode("\n", array_filter($html, static function (string $part): bool {
return $part !== '';
}));
}
private function isHeadingLine(string $line): bool
{
if (substr($line, -1) !== ':') {
return false;
}
$heading = trim(rtrim($line, ':'));
if ($heading === '' || strlen($heading) > 120) {
return false;
}
return strpos($heading, "\t") === false
&& strpos($heading, '.') === false
&& strpos($heading, ';') === false;
}
/**
* @return array{type: string, value: string}|null
*/
private function parseListMarker(string $line): ?array
{
if (preg_match('/^\s*(?:\*|-|–|—)\s+(.+)$/', $line, $matches) === 1) {
return ['type' => 'ul', 'value' => trim($matches[1])];
}
if (preg_match('/^\s*\d+[.)]\s+(.+)$/', $line, $matches) === 1) {
return ['type' => 'ol', 'value' => trim($matches[1])];
}
return null;
}
/**
* @param array<int, string> $lines
* @return array{0: string, 1: int}
*/
private function renderList(array $lines, int $index, string $type): array
{
$items = [];
$count = count($lines);
while ($index < $count) {
$marker = $this->parseListMarker($lines[$index]);
if ($marker === null || $marker['type'] !== $type) {
break;
}
$items[] = '<li>' . $this->escape($marker['value']) . '</li>';
$index++;
}
return ['<' . $type . '>' . "\n" . implode("\n", $items) . "\n" . '</' . $type . '>', $index];
}
private function isTabularLine(string $line): bool
{
if (strpos($line, "\t") !== false) {
$cells = array_values(array_filter(array_map('trim', explode("\t", $line)), 'strlen'));
return count($cells) >= 2;
}
if (strpos($line, '|') === false || strpos($line, ':') !== false) {
return false;
}
$cells = array_values(array_filter(array_map('trim', explode('|', $line)), 'strlen'));
return count($cells) >= 2;
}
/**
* @param array<int, string> $lines
* @return array{0: string, 1: int}
*/
private function renderTabularLines(array $lines, int $index): array
{
$rows = [];
$count = count($lines);
while ($index < $count && $this->isTabularLine($lines[$index])) {
$separator = strpos($lines[$index], "\t") !== false ? "\t" : '|';
$rows[] = array_values(array_filter(
array_map([$this, 'normalizeCell'], explode($separator, $lines[$index])),
'strlen'
));
$index++;
}
return [$this->renderTable($rows), $index];
}
/**
* @return array{key: string, value: string}|null
*/
private function parseKeyValueLine(string $line): ?array
{
$colonPosition = strpos($line, ':');
if ($colonPosition === false) {
return null;
}
$key = trim(substr($line, 0, $colonPosition));
$value = trim(substr($line, $colonPosition + 1));
if ($key === '' || $value === '' || strlen($key) > 100) {
return null;
}
if (preg_match('/[.!?]$/', $key) === 1) {
return null;
}
return ['key' => $key, 'value' => $value];
}
/**
* @param array<int, string> $lines
* @return array{0: array<int, array{key: string, value: string}>, 1: int}
*/
private function collectKeyValueLines(array $lines, int $index): array
{
$rows = [];
$count = count($lines);
while ($index < $count) {
$row = $this->parseKeyValueLine($lines[$index]);
if ($row === null) {
break;
}
$rows[] = $row;
$index++;
}
return [$rows, $index];
}
/**
* @param array<int, array{key: string, value: string}> $rows
*/
private function renderKeyValueTable(array $rows): string
{
$tableRows = [];
foreach ($rows as $row) {
$tableRows[] = [$row['key'], $row['value']];
}
return $this->renderTable($tableRows);
}
/**
* @param array<int, string> $lines
* @return array{0: array<int, string>, 1: int}
*/
private function collectPlainLines(array $lines, int $index): array
{
$result = [];
$count = count($lines);
while ($index < $count) {
$line = $lines[$index];
if (
$this->isHeadingLine($line)
|| $this->parseListMarker($line) !== null
|| $this->isTabularLine($line)
|| $this->parseKeyValueLine($line) !== null
) {
break;
}
$result[] = $line;
$index++;
}
return [$result, $index];
}
/**
* @param array<int, string> $lines
*/
private function renderParagraph(array $lines): string
{
$lines = array_values(array_filter(array_map('trim', $lines), 'strlen'));
if ($lines === []) {
return '';
}
return '<p>' . implode("<br>\n", array_map([$this, 'escape'], $lines)) . '</p>';
}
/**
* @param array<int, array<int, string>> $rows
*/
private function renderTable(array $rows): string
{
$html = ['<table class="catalog-import-description__table">', '<tbody>'];
foreach ($rows as $row) {
if ($row === []) {
continue;
}
$html[] = '<tr>';
foreach (array_values($row) as $cellIndex => $cell) {
$tag = $cellIndex === 0 ? 'th' : 'td';
$scope = $cellIndex === 0 ? ' scope="row"' : '';
$html[] = '<' . $tag . $scope . '>' . $this->escape($cell) . '</' . $tag . '>';
}
$html[] = '</tr>';
}
$html[] = '</tbody>';
$html[] = '</table>';
return implode("\n", $html);
}
private function normalizeCell(string $cell): string
{
$cell = trim($cell);
return preg_replace('/ {2,}/', ' ', $cell) ?? $cell;
}
private function escape(string $text): string
{
if (function_exists('htmlspecialcharsbx')) {
return htmlspecialcharsbx($text);
}
return htmlspecialchars($text, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
}

View File

@ -0,0 +1,67 @@
<?php
require_once __DIR__ . '/../local/php_interface/lib/ImportDescriptionFormatter.php';
$formatter = new \Local\Catalog\ImportDescriptionFormatter();
function assertContainsText(string $needle, string $haystack, string $message): void
{
if (strpos($haystack, $needle) === false) {
fwrite(STDERR, $message . PHP_EOL);
fwrite(STDERR, 'Missing: ' . $needle . PHP_EOL);
fwrite(STDERR, $haystack . PHP_EOL);
exit(1);
}
}
function assertEndsWithText(string $suffix, string $haystack, string $message): void
{
if (substr($haystack, -strlen($suffix)) !== $suffix) {
fwrite(STDERR, $message . PHP_EOL);
fwrite(STDERR, 'Expected suffix: ' . $suffix . PHP_EOL);
fwrite(STDERR, $haystack . PHP_EOL);
exit(1);
}
}
$singleLine = $formatter->format('Корзина (600*300*100мм)');
assertContainsText('<p>Корзина (600*300*100мм)</p>', $singleLine, 'Single line description must become a paragraph.');
$paragraphs = $formatter->format("Первый абзац\n\nВторой абзац");
assertContainsText('<p>Первый абзац</p>', $paragraphs, 'First paragraph is missing.');
assertContainsText('<p>Второй абзац</p>', $paragraphs, 'Second paragraph is missing.');
$keyValue = $formatter->format("Торговая марка: BRITA\nАртикул: 102828\nВес нетто, кг: 1,90");
assertContainsText('<table class="catalog-import-description__table">', $keyValue, 'Key-value block must become a table.');
assertContainsText('<th scope="row">Артикул</th>', $keyValue, 'Key cell is missing.');
assertContainsText('<td>102828</td>', $keyValue, 'Value cell is missing.');
$tabular = $formatter->format("Длина\t2400 мм\nЦвет\tхром");
assertContainsText('<th scope="row">Длина</th>', $tabular, 'Tabular first column must become row heading.');
assertContainsText('<td>2400 мм</td>', $tabular, 'Tabular value is missing.');
$unordered = $formatter->format("* Первый пункт\n- Второй пункт");
assertContainsText('<ul>', $unordered, 'Unordered list is missing.');
assertContainsText('<li>Первый пункт</li>', $unordered, 'Unordered list item is missing.');
$ordered = $formatter->format("1. Первый пункт\n2) Второй пункт");
assertContainsText('<ol>', $ordered, 'Ordered list is missing.');
assertContainsText('<li>Второй пункт</li>', $ordered, 'Ordered list item is missing.');
$heading = $formatter->format("Описание и основные функции:\nСодержит 4 ступени фильтрации.");
assertContainsText('<h3>Описание и основные функции</h3>', $heading, 'Heading is missing.');
assertContainsText('<p>Содержит 4 ступени фильтрации.</p>', $heading, 'Paragraph after heading is missing.');
$unsafeHtml = $formatter->format('<script>alert(1)</script><p>Текст</p>');
assertContainsText('&lt;script&gt;alert(1)&lt;/script&gt;&lt;p&gt;Текст&lt;/p&gt;', $unsafeHtml, 'Unsafe HTML must be escaped.');
$empty = $formatter->format(" \n\t ");
if ($empty !== '') {
fwrite(STDERR, 'Empty description must stay empty.' . PHP_EOL);
exit(1);
}
$checkVersion = $formatter->formatCheck('Проверка');
assertEndsWithText('&nbsp; &nbsp; &nbsp;', $checkVersion, 'Check version must append the tail.');
echo 'OK' . PHP_EOL;