--------------------
BitFacet
--------------------
Author: Ivan K.
--------------------

Faceted filtering on bitmaps for MODX 3: resources, TVs, MiniShop3, ms3Variants and custom tables.
Фасетная фильтрация на битовых картах для MODX 3: ресурсы, TV, MiniShop3, ms3Variants и свои таблицы.

Full documentation: manager → BitFacet → Documentation tab (quick start, filter sets, site output, SEO, index, turbo mode, access, developers, troubleshooting).
Полная документация: админка → BitFacet → вкладка «Документация» (быстрый старт, наборы, вывод на сайте, SEO, индекс, турборежим, права, разработчикам, вопросы).

Quick check / Быстрая проверка:
1. The installer creates the example filter set core/components/bitfacet/data/sets/example.json.
   Установщик создаёт набор фильтров примера core/components/bitfacet/data/sets/example.json.
2. Assign the "bitfacet.example" template to a catalog section and open it on the site.
   Назначьте разделу каталога шаблон «bitfacet.example» и откройте его на сайте.
3. Rebuild from the console / пересборка из консоли:
   php core/components/bitfacet/cli/rebuild.php [set] [--if-due]

Filter sets / Наборы фильтров (manager tab / вкладка «Наборы фильтров»):
- Visual editor: products (classes, templates, sections, contexts), filters (order, title, URL name, type, sources), ranges, sorting, search;
  rare settings (sql, providers, variants, batch) — JSON tab.
  Визуальный редактор: товары (классы, шаблоны, разделы, контексты), фильтры (порядок, название, имя в адресе, тип, источники), диапазоны,
  сортировки, поиск; редкие настройки (sql, providers, variants, batch) — вкладка JSON.
- Values tab: check values → "Merge" (duplicates, typos) or "Hide"; pencil — custom label. Stored in the set:
  Вкладка «Значения»: отметьте значения → «Объединить» (дубли, опечатки) или «Скрыть»; карандаш — своя подпись. Хранится в наборе:
  "ms:vendor": {"merge": {"nike inc": "nike"}, "hide": ["без бренда"], "labels": {"nike": "Nike"}}  (keys — lowercase / ключи в нижнем регистре)

Filter keys in the set / Ключи фильтра в наборе (the set editor writes them, JSON tab — the same / редактор набора пишет их сам, во вкладке JSON — то же):
  "facets": {
    "ms:vendor": {"label": "Brand", "alias": "brand", "order": "count", "show": 10, "collapsed": true},
    "ms:tags":   {"type": "multi", "mode": "and"},
    "opt:size":  {"order": "manual", "values_order": ["xs", "s", "m", "l", "xl"]}
  },
  "numbers": {"ms:price": {"step": 100, "collapsed": true}}
- label — title / название; alias — name in the URL path / имя в адресе (/katalog/brand-nike/); type — facet | multi | bool | tree (default — from the source / по умолчанию из источника).
- mode — "or" (default: any checked value) or "and" (all checked values; only multi product fields: features, tags, materials).
  "or" (по умолчанию: любое из отмеченных) или "and" (все отмеченные сразу; только поля товара с несколькими значениями — свойства, теги, материалы).
  With "and" a count shows how many products remain if the value is added / при «and» счётчик — сколько товаров останется, если добавить значение.
- order — "" (as in the source / как в источнике), "alpha", "count" (by products in the whole catalog / по числу товаров во всём каталоге), "manual" (values_order).
- values_order — custom order, value keys (lowercase); the Values tab writes it when rows are dragged / свой порядок, ключи значений; пишет вкладка «Значения» перетаскиванием.
- show — show N values first, the rest under "Show all (M)"; 0 — all / сначала N значений, остальные под «Показать все (M)»; 0 — все.
- collapsed — the group is collapsed until something is checked in it / группа свёрнута, пока в ней ничего не выбрано.
- step (ranges / диапазоны) — step of the from/to fields; the hints are rounded to it / шаг полей «от/до», подсказки округляются до него.
- order, show, values_order are not used by tree facets (categories) / у дерева (категорий) не используются.
Display keys are stored in the index: after changing them in JSON rebuild the index (saving in the manager does it itself).
Ключи вывода хранятся в индексе: после правки в файле набора пересоберите индекс (сохранение в админке делает это само).

Index tab / Вкладка «Индекс»:
- Rebuild: the button answers at once, the build runs after the response; stage and percent are shown on Overview and Index until it ends.
  Пересборка: кнопка отвечает сразу, сборка идёт после ответа; этап и процент видны в «Обзоре» и «Индексе», пока она не закончится.
- Build history: when, set, started by (manually, cron, console, after changes), reason, result, products, time, memory, error;
  a build whose process died (memory, time limit) is shown as "aborted". Kept bitfacet.build_keep_days days (30; 0 — forever).
  История сборок: когда, набор, кто запустил (вручную, крон, консоль, после правок), причина, итог, товаров, время, память, ошибка;
  сборка, процесс которой упал (память, лимит времени), — «прервана». Хранится bitfacet.build_keep_days дней (30; 0 — всегда).
- Storage and updates: index settings and the batch size of each set (products per database query: less — less memory).
  Хранение и обновление: настройки индекса и размер пачки у каждого набора (товаров за один запрос к базе: меньше — меньше памяти).
- Cron: on/off (bitfacet.cron_enabled), interval (bitfacet.cron_interval), the crontab line and the same fields for a hosting panel,
  last run (rebuild.php --if-due writes core/components/bitfacet/data/index/cron.json). The component does not edit crontab.
  Крон: вкл/выкл, интервал, строка crontab и поля для панели хостинга, последний запуск. Компонент сам crontab не меняет.
- Error log: errors of rebuilds, event updates, the filter, the endpoint, SEO, cron and turbo mode (data/index/errors.log, also in the MODX error log).
  Журнал ошибок: пересборка, обновление по событиям, фильтр, эндпоинт, SEO, крон, турборежим (data/index/errors.log, и в журнале MODX).

Settings tab / Вкладка «Настройки» (only with the MODX "settings" permission / только с правом MODX «settings»):
- General: index and sets folders (checked: absolute, creatable, writable, not a MODX site folder), drop tables on uninstall, speed log.
  Общие параметры: папки индексов и наборов (проверяются: абсолютный путь, создаётся, доступна запись, не папка сайта MODX), удаление таблиц с пакетом, журнал скорости.
- Turbo mode: address (empty — off), process state, "Check connection" — the socket directly and the same address through the site (nginx):
  shows whether nginx reaches the process or falls back to the regular endpoint.
  Турборежим: адрес (пусто — выключен), состояние процесса, «Проверить связь» — сокет напрямую и тот же адрес через сайт (nginx):
  видно, доходит ли nginx до процесса или отдаёт запрос запасному пути.
- Tab access: user groups for each tab (setting bitfacet.tab_access; empty — everyone with bitfacet_view; sudo — everything).
  Checked on the server too: requests of a closed tab get 403. Overview and Documentation are always open.
  Права доступа к вкладкам: группы пользователей у каждой вкладки (empty — все с bitfacet_view; sudo — всё).
  Проверяется и на сервере: запросы закрытой вкладки получают 403. «Обзор» и «Документация» открыты всегда.

Categories, pagination, contexts / Категории, страницы, контексты:
- &categories=`1` (default) — "Categories" group: catalog tree of links (current branch expanded, current section highlighted), the filter is kept.
  Группа «Категории»: дерево каталога ссылками (ветка текущей страницы раскрыта, текущий раздел выделен), фильтр сохраняется; &categories=`0` — не показывать.
- Pagination: first / last page links and the "Show more" button (chunk &tplMore) that appends the next page under the products.
  Страницы: «Первая» / «Последняя» и кнопка «Показать ещё» (чанк &tplMore) — следующая страница дописывается под товарами.
- MODX contexts: a filter set may cover several contexts; the filter, links and language follow the page context (also in turbo mode).
  Контексты MODX: набор может охватывать несколько контекстов; фильтр, ссылки и язык — по контексту страницы (и в турборежиме).

SEO (manager tab SEO / вкладка «SEO»):
- Rules: set, catalog pages, facets in URL order, title/H1/description/text templates ({pagetitle} {count} {values} {ms:color}).
  Правила: набор, страницы каталога, фасеты в порядке адреса, шаблоны title/H1/description/текста.
- The filter lives in the URL path: /katalog/color-belyj,sinij/price-1000-5000/sort-price-desc/page-2/, rule pages — /katalog/krasnyj/nike/
  (plugin bitfacet.seo); filter names — "alias" in the set; only rule pages with products are indexed, other filters — noindex + canonical.
  Фильтр — в пути адреса: /katalog/color-belyj,sinij/price-1000-5000/sort-price-desc/page-2/, страницы правил — /katalog/krasnyj/nike/
  (плагин bitfacet.seo); имена фильтров — "alias" в наборе; индексируются только страницы правил с товарами, остальные — noindex + canonical.
- Template: [[!BitFacetSeo? &set=`auto`]] first in <head>; <title>[[!+bitfacet.title:default=`[[*pagetitle]]`]]</title>; [[!+bitfacet.h1]], [[!+bitfacet.text]].
- Sitemap / карта сайта: /bitfacet-sitemap.xml (per context / по контексту).

Search / Поиск:
Add to a filter set / добавьте в набор: "search": {"fields": {"ms:article": 5, "res:pagetitle": 3, "ms:vendor": 2}, "synonyms": {"кроссовки": ["кеды"]}}
Search box parameter search (q is taken by MODX): all words, Russian stemmer, word start, transliteration, keyboard layout, typos, synonyms; relevance sort.
Поле поиска search (q занят MODX): все слова, окончания, начало слова, транслит, раскладка, опечатки, синонимы; сортировка по релевантности.
Manager tab Search: query check and query log / вкладка «Поиск»: проверка запроса и журнал.

Large catalogs / Большие каталоги:
The index lives in opcache and is rebuilt from PHP. Measured on 369k products (15 facets): rebuild 8–12 s, ~410 MB of memory,
index 52 MB, filter query 2–11 ms, page 21–34 ms. Raise for large catalogs:
Индекс держится в opcache и пересобирается из PHP. Замер на 369 тыс. товаров (15 фасетов): пересборка 8–12 с, ~410 МБ памяти,
индекс 52 МБ, запрос фильтра 2–11 мс, страница 21–34 мс. Для больших каталогов поднимите:

  products / товаров   memory_limit   opcache.memory_consumption
  up to / до  50 000      256M             128M
  up to / до 150 000      256M             256M
  up to / до 400 000      512M             512M

Server and component settings:
- opcache.enable = 1 (php-fpm) — the index is served from opcache shared memory without copying: opening the index takes 0.1 ms. Without opcache the index is read from files on every request (file mode) — several times slower.
- opcache.memory_consumption — opcache memory, MB. Needed: code of all sites on this php-fpm + index size × 1.5 + a margin: every full rebuild leaves wasted opcache memory the size of the index until opcache resets itself. If it is short, BitFacet switches to reading files by itself and says so on Overview. Default 128.
- opcache.interned_strings_buffer — the default (8) is fine: index strings that do not fit into the buffer stay in opcache script memory, it works.
- opcache.max_accelerated_files — a set has about 30 index files, two builds are kept; the default (10000) is enough.
- opcache.validate_timestamps / revalidate_freq — any: every build is written to a new folder, so opcache never serves an old version even with validate_timestamps = 0. Fresh build files get an old date so opcache.file_update_protection does not delay them.
- opcache.file_cache_only = 1 — not suitable (no shared memory): BitFacet works in file mode. opcache.restrict_api — if it closes opcache_get_status, BitFacet cannot see free memory and assumes the index fits.
- memory_limit (php-fpm pool) — for rebuilds after the response and the Rebuild button: about 1 KB per product + 0.3 KB per variant + 64 MB (369k products — 410 MB, 512M needed). If it is short, the rebuild is not started in php-fpm — cron or the console does it; Overview warns. A regular filter request with the index in opcache needs almost no memory.
- max_execution_time (php-fpm pool) — a rebuild in php-fpm must fit into it: 100k products — 2–6 s, 369k — 8–12 s. Use cron for large catalogs.
- Cron: */5 * * * * php …/core/components/bitfacet/cli/rebuild.php --if-due — the console has no memory or time limits; it rebuilds only when due (index outdated, long journal, changes older than the delay, build older than bitfacet.rebuild_max_age). The ready line with this site's paths and the cron status — Index tab.
- bitfacet.storage — auto (opcache if enabled and it has room, otherwise files), opcache, file.
- bitfacet.journal_max (100) and bitfacet.rebuild_delay (300 s) — changed products are visible at once via the journal on top of the index; a long journal slows down every request, so the index is rebuilt when there are more than journal_max changes or the first change is older than rebuild_delay seconds.
- bitfacet.index_path, bitfacet.sets_path — where indexes and filter sets live; an index can be deleted, it will be rebuilt.

Настройки сервера и компонента:
- opcache.enable = 1 (php-fpm) — индекс отдаётся из общей памяти opcache без копирования: открыть индекс — 0,1 мс. Без opcache индекс читается из файлов на каждый запрос (режим file) — в несколько раз медленнее.
- opcache.memory_consumption — сколько памяти у opcache, МБ. Нужно: код всех сайтов этого php-fpm + размер индекса × 1,5 + запас: каждая полная пересборка оставляет в opcache «потерянную» память размером с индекс, пока opcache сам не сбросится. Не хватает — BitFacet сам переходит на чтение из файлов и пишет об этом в «Обзоре». По умолчанию 128.
- opcache.interned_strings_buffer — можно оставить по умолчанию (8): строки индекса, не поместившиеся в буфер, хранятся в памяти скрипта opcache, это работает.
- opcache.max_accelerated_files — у набора около 30 файлов индекса, хранятся две сборки; значения по умолчанию (10000) хватает.
- opcache.validate_timestamps / revalidate_freq — любые: каждая сборка пишется в новую папку, поэтому opcache не отдаст старую версию даже при validate_timestamps = 0. Свежие файлы сборки помечаются старой датой, чтобы их не задерживала opcache.file_update_protection.
- opcache.file_cache_only = 1 — не подходит (нет общей памяти): BitFacet работает в режиме file. opcache.restrict_api — если закрывает opcache_get_status, BitFacet не видит свободную память и считает, что индекс помещается.
- memory_limit (пул php-fpm) — для пересборки после ответа и кнопки «Пересобрать»: около 1 КБ на товар + 0,3 КБ на вариант + 64 МБ (369 тыс. товаров — 410 МБ, нужно 512M). Не хватает — пересборка в php-fpm не запускается, её делает крон или консоль; «Обзор» предупреждает. Обычный запрос фильтра при индексе в opcache памяти почти не тратит.
- max_execution_time (пул php-fpm) — пересборка в php-fpm должна в него уложиться: 100 тыс. товаров — 2–6 с, 369 тыс. — 8–12 с. Для больших каталогов — крон.
- Крон: */5 * * * * php …/core/components/bitfacet/cli/rebuild.php --if-due — в консоли нет ограничений по памяти и времени; пересобирает, только если пора (индекс устарел, длинный журнал правок, правки старше задержки, сборка старше bitfacet.rebuild_max_age). Готовая строка с путями сайта и состояние крона — вкладка «Индекс».
- bitfacet.storage — auto (opcache, если включён и в нём хватает места, иначе файлы), opcache, file.
- bitfacet.journal_max (100) и bitfacet.rebuild_delay (300 с) — изменённые товары сразу видны через журнал поверх индекса; длинный журнал замедляет каждый запрос, поэтому индекс пересобирается, когда правок больше journal_max или первой правке больше rebuild_delay секунд.
- bitfacet.index_path, bitfacet.sets_path — где лежат индексы и наборы фильтров; индекс можно удалить, он соберётся заново.

Turbo mode (VDS) / Турборежим (VDS):
A persistent process (cli/turbo.php, pcntl) keeps indexes in memory and answers filter AJAX requests without MODX: 500k products — 17–27 ms instead of 37–45 ms, repeated request ~4 ms.
Setup: systemd service + nginx location /bitfacet-turbo (ready-made text with this site's paths — manager, tab Documentation) + setting bitfacet.turbo_url = /bitfacet-turbo.
If the process is down, nginx and bitfacet.js fall back to publicConnector.php. Only simple chunks (placeholders); chunks with MODX tags/Fenom are handled by the regular endpoint.
Settings, lexicons, sets and the section tree are read at start and on a new build; after changing them — Overview → "Clear cache".
Постоянный процесс (cli/turbo.php, pcntl) держит индексы в памяти и отвечает на AJAX-запросы фильтра без MODX: 500 тыс. товаров — 17–27 мс вместо 37–45 мс, повтор ~4 мс.
Настройка: служба systemd + location /bitfacet-turbo в nginx (готовый текст с путями сайта — в админке, вкладка «Документация») + настройка bitfacet.turbo_url = /bitfacet-turbo.
Процесс не работает — nginx и bitfacet.js отдают запрос publicConnector.php. Только простые чанки (плейсхолдеры); чанки с тегами MODX/Fenom обрабатывает обычный эндпоинт.
Настройки, лексиконы, наборы и дерево разделов читаются при запуске и при новой сборке; поменяли — «Обзор» → «Сбросить кэш».

For MODX Revolution 3.x, PHP 8.3+.
