Vinoteca: модуль, шаблон и компоненты интернет-магазина вина на 1С-Битрикс

This commit is contained in:
jimagie committed 2026-10-22 03:32:28 +05:00
commit f6ba0d2174
470 files changed
+26454

No files matched your search

@@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca;
use Bitrix\Main\Engine\CurrentUser;
use Bitrix\Main\Localization\Loc;
class Account
{
public static function isAuthorized(): bool
{
return (int)CurrentUser::get()->getId() > 0;
}
public static function url(): string
{
return SITE_DIR . (self::isAuthorized() ? "personal/" : "login/");
}
public static function label(string $accountCode, string $loginCode): string
{
$code = self::isAuthorized() ? $accountCode : $loginCode;
$text = (string)Loc::getMessage($code);
return $text !== "" ? $text : (string)Loc::getMessage($accountCode);
}
}
@@ -0,0 +1,85 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca;
use AltchaOrg\Altcha\Algorithm\Pbkdf2;
use AltchaOrg\Altcha\Altcha as Library;
use AltchaOrg\Altcha\CreateChallengeOptions;
use AltchaOrg\Altcha\Payload;
use AltchaOrg\Altcha\VerifySolutionOptions;
use Bitrix\Main\Application;
class Altcha
{
private const COST = 2000;
private const COUNTER_MIN = 1000;
private const COUNTER_MAX = 2000;
private const TTL = 1200;
private const MAX_PAYLOAD = 4000;
public static function challenge(): ?array
{
$library = self::library();
if ($library === null) {
return null;
}
return $library->createChallenge(new CreateChallengeOptions(
algorithm: new Pbkdf2(),
cost: self::COST,
counter: random_int(self::COUNTER_MIN, self::COUNTER_MAX),
expiresAt: time() + self::TTL,
))->toArray();
}
public static function verify(string $raw): bool
{
$library = self::library();
if ($library === null || $raw === "" || strlen($raw) > self::MAX_PAYLOAD) {
return false;
}
try {
$payload = Payload::fromBase64($raw);
$result = $library->verifySolution(new VerifySolutionOptions(algorithm: new Pbkdf2(), payload: $payload));
} catch (\Throwable) {
return false;
}
if (!$result->verified || $payload->challenge->signature === null) {
return false;
}
return self::markUsed($payload->challenge->signature);
}
private static function markUsed(string $signature): bool
{
$handle = @fopen(self::dir() . "/altcha-used/" . hash("sha256", $signature), "x");
if (!$handle) {
return false;
}
fclose($handle);
if (random_int(1, 50) === 1) {
foreach (glob(self::dir() . "/altcha-used/*") ?: [] as $old) {
if (filemtime($old) < time() - 3600) {
@unlink($old);
}
}
}
return true;
}
private static function library(): ?Library
{
$key = trim((string)@file_get_contents(self::dir() . "/altcha.key"));
return $key === "" ? null : new Library(hmacSignatureSecret: $key);
}
private static function dir(): string
{
return dirname(Application::getDocumentRoot()) . "/data";
}
}
@@ -0,0 +1,81 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca;
final class ArticleSchema
{
private const CONTEXT = "https://schema.org";
public static function list(array $items, string $path, string $name, string $description): array
{
$url = Config::host() . $path;
$list = [];
foreach (array_values($items) as $index => $item) {
$list[] = ["@type" => "ListItem", "position" => $index + 1, "url" => $item["url"], "name" => $item["name"]];
}
return [
"@context" => self::CONTEXT,
"@graph" => [
[
"@type" => "CollectionPage",
"@id" => $url . "#webpage",
"url" => $url,
"name" => $name,
"description" => $description,
"inLanguage" => LANGUAGE_ID,
"about" => ["@id" => Config::host() . "/#store"],
"mainEntity" => ["@id" => $url . "#items"],
"workTranslation" => PageSchema::translations($path, "CollectionPage"),
],
[
"@type" => "ItemList",
"@id" => $url . "#items",
"url" => $url,
"numberOfItems" => count($list),
"itemListElement" => $list,
],
],
];
}
public static function detail(array $article): array
{
$url = Config::host() . $article["path"];
$store = ["@id" => Config::host() . "/#store"];
$node = [
"@type" => "Article",
"@id" => $url . "#article",
"url" => $url,
"headline" => $article["name"],
"description" => $article["description"],
"inLanguage" => LANGUAGE_ID,
"datePublished" => $article["published"],
"dateModified" => $article["modified"],
"author" => $store,
"publisher" => $store,
"wordCount" => $article["words"],
];
$page = [
"@type" => "WebPage",
"@id" => $url . "#webpage",
"url" => $url,
"name" => $article["name"],
"description" => $article["description"],
"inLanguage" => LANGUAGE_ID,
"mainEntity" => ["@id" => $url . "#article"],
"datePublished" => $article["published"],
"dateModified" => $article["modified"],
"workTranslation" => PageSchema::translations($article["path"], "WebPage"),
];
if ($article["image"]) {
$image = PageSchema::image($url . "#image", $article["image"]["url"], $article["image"]["width"], $article["image"]["height"]);
$node["image"] = $image;
$page["primaryImageOfPage"] = ["@id" => $url . "#image"];
}
return ["@context" => self::CONTEXT, "@graph" => [$page, $node]];
}
}
@@ -0,0 +1,53 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca;
use Bitrix\Main\Localization\Loc;
Loc::loadMessages(__FILE__);
class Breadcrumbs
{
public static function show(array $items): void
{
global $APPLICATION;
$APPLICATION->AddChainItem((string)Loc::getMessage("VINO_BREADCRUMBS_HOME"), SITE_DIR);
foreach ($items as $item) {
$link = (string)($item[1] ?? "");
if ($link !== "" && str_starts_with($link, "/") && !str_starts_with($link, SITE_DIR)) {
$link = SITE_DIR . ltrim($link, "/");
}
$APPLICATION->AddChainItem((string)$item[0], $link);
}
$APPLICATION->IncludeComponent("bitrix:breadcrumb", "vinoteca", [
"START_FROM" => "0",
"PATH" => "",
"SITE_ID" => SITE_ID,
], false, ["HIDE_ICONS" => "Y"]);
}
public static function schema(array $chain, string $self): array
{
$last = count($chain) - 1;
$items = [];
foreach ($chain as $i => $item) {
$link = (string)$item["LINK"];
$items[] = [
"@type" => "ListItem",
"position" => $i + 1,
"name" => $item["TITLE"],
"item" => $i < $last && $link !== "" ? Config::host() . $link : $self,
];
}
return [
"@context" => "https://schema.org",
"@type" => "BreadcrumbList",
"@id" => $self . "#breadcrumb",
"itemListElement" => $items,
];
}
}
@@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca;
use Bitrix\Main\Application;
use Bitrix\Main\Data\Cache;
final class Cached
{
public static function remember(string $dir, string $id, int $ttl, array $tags, callable $load): mixed
{
$cache = Cache::createInstance();
if ($cache->initCache($ttl, $id, $dir)) {
return $cache->getVars();
}
$cache->startDataCache();
$taggedCache = Application::getInstance()->getTaggedCache();
$taggedCache->startTagCache($dir);
try {
foreach ($tags as $tag) {
$taggedCache->registerTag($tag);
}
$value = $load();
} catch (\Throwable $e) {
$taggedCache->abortTagCache();
$cache->abortDataCache();
throw $e;
}
$taggedCache->endTagCache();
$cache->endDataCache($value);
return $value;
}
}
+273
View File
@@ -0,0 +1,273 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca;
use Bitrix\Catalog\Product\Basket as ProductBasket;
use Bitrix\Currency\CurrencyManager;
use Bitrix\Main\Loader;
use Bitrix\Main\Localization\Loc;
use Bitrix\Sale\Basket;
use Bitrix\Sale\BasketBase;
use Bitrix\Sale\Basket\RefreshFactory;
use Bitrix\Sale\BasketItemBase;
use Bitrix\Sale\Discount;
use Bitrix\Sale\Discount\Context\Fuser as FuserContext;
use Bitrix\Sale\DiscountCouponsManager;
use Bitrix\Sale\Fuser;
use Jinove\Vinoteca\Catalog\Media;
use Jinove\Vinoteca\Catalog\Prices;
use Jinove\Vinoteca\Catalog\Related;
use Jinove\Vinoteca\Catalog\SearchMeta;
Loc::loadMessages(__FILE__);
final class Cart
{
public const MAX_QUANTITY = 99;
public const SHARE_MAX_ITEMS = 50;
private const THUMB_WIDTH = 160;
private const THUMB_HEIGHT = 200;
public static function load(): ?BasketBase
{
if (!Loader::includeModule("sale") || !Loader::includeModule("catalog")) {
return null;
}
return Basket::loadItemsForFUser(Fuser::getId(true), Config::basketSiteId());
}
public static function setQuantity(BasketBase $basket, int $productId, int $quantity): bool
{
$quantity = max(0, min(self::MAX_QUANTITY, $quantity));
$item = self::findItem($basket, $productId);
if ($item === null) {
if ($quantity === 0) {
return true;
}
return ProductBasket::addProduct(["PRODUCT_ID" => $productId, "QUANTITY" => $quantity], ["LID" => Config::basketSiteId()])->isSuccess();
}
if ($quantity === 0) {
$item->delete();
} elseif (!$item->setField("QUANTITY", $quantity)->isSuccess()) {
return false;
}
return $basket->save()->isSuccess();
}
public static function addMany(BasketBase $basket, array $items): bool
{
$ok = true;
foreach ($items as $productId => $quantity) {
$item = self::findItem($basket, (int)$productId);
$current = $item === null ? 0 : (int)$item->getQuantity();
$ok = self::setQuantity($basket, (int)$productId, $current + (int)$quantity) && $ok;
}
return $ok;
}
public static function parseShare(string $code): array
{
if (!preg_match('/^\d{1,9}-\d{1,2}(\.\d{1,9}-\d{1,2}){0,' . (self::SHARE_MAX_ITEMS - 1) . '}$/', $code)) {
return [];
}
$items = [];
foreach (explode(".", $code) as $pair) {
[$productId, $quantity] = array_map("intval", explode("-", $pair));
if ($productId > 0 && $quantity > 0) {
$items[$productId] = min(self::MAX_QUANTITY, ($items[$productId] ?? 0) + $quantity);
}
}
return $items;
}
public static function shared(array $items): array
{
$productIds = array_keys($items);
$products = Related::summariesById($productIds);
$prices = Prices::optimal(array_keys($products), Config::basketSiteId());
$meta = SearchMeta::get($productIds);
$images = Media::thumbs($productIds, self::THUMB_WIDTH, self::THUMB_HEIGHT);
$list = [];
$sum = 0.0;
$currency = "";
foreach ($items as $productId => $quantity) {
if (!isset($products[$productId], $prices[$productId])) {
continue;
}
$price = $prices[$productId];
$currency = $price["currency"];
$sum += $price["price"] * $quantity;
$list[] = [
"id" => $productId,
"name" => $products[$productId]["name"],
"url" => $products[$productId]["url"],
"brand" => (string)($meta[$productId]["BRAND"] ?? ""),
"image" => (string)($images[$productId] ?? ""),
"quantity" => $quantity,
"sum" => Money::format($price["price"] * $quantity, $currency),
];
}
return [
"items" => $list,
"code" => implode(".", array_map(static fn(array $row): string => $row["id"] . "-" . $row["quantity"], $list)),
"total" => $list ? Money::format($sum, $currency) : "",
];
}
public static function clear(BasketBase $basket): bool
{
foreach ($basket as $item) {
if (!$item->isDelay()) {
$item->delete();
}
}
return $basket->save()->isSuccess();
}
public static function addCoupon(string $code): bool
{
DiscountCouponsManager::init();
return DiscountCouponsManager::add($code);
}
public static function removeCoupon(string $code): bool
{
DiscountCouponsManager::init();
return DiscountCouponsManager::delete($code);
}
public static function state(BasketBase $basket): array
{
$items = [];
$count = 0;
foreach ($basket as $item) {
if (!$item->canBuy() || $item->isDelay()) {
continue;
}
$productId = (int)$item->getProductId();
$quantity = (int)$item->getQuantity();
$items[$productId] = ($items[$productId] ?? 0) + $quantity;
$count += $quantity;
}
return ["count" => $count, "items" => (object)$items];
}
public static function view(BasketBase $basket, bool $refresh = true): array
{
DiscountCouponsManager::init();
if ($refresh) {
$basket->refresh(RefreshFactory::create(RefreshFactory::TYPE_FULL));
$basket->save();
}
self::applyDiscounts($basket);
$productIds = [];
foreach ($basket as $item) {
if (!$item->isDelay()) {
$productIds[] = (int)$item->getProductId();
}
}
$products = Related::summariesById($productIds);
$meta = SearchMeta::get($productIds);
$images = Media::thumbs($productIds, self::THUMB_WIDTH, self::THUMB_HEIGHT);
$currency = "";
$items = [];
$count = 0;
$lines = 0;
$sum = 0.0;
$base = 0.0;
foreach ($basket as $item) {
if ($item->isDelay()) {
continue;
}
$productId = (int)$item->getProductId();
$quantity = (int)$item->getQuantity();
$price = (float)$item->getPrice();
$basePrice = max($price, (float)$item->getBasePrice());
$currency = (string)$item->getCurrency();
$available = $item->canBuy();
if ($available) {
$lines++;
$count += $quantity;
$sum += $price * $quantity;
$base += $basePrice * $quantity;
}
$items[] = [
"id" => $productId,
"name" => (string)($products[$productId]["name"] ?? $item->getField("NAME")),
"url" => (string)($products[$productId]["url"] ?? ""),
"meta" => (string)($meta[$productId]["META"] ?? ""),
"brand" => (string)($meta[$productId]["BRAND"] ?? ""),
"image" => (string)($images[$productId] ?? ""),
"quantity" => $quantity,
"available" => $available,
"price" => Money::format($price, $currency),
"basePrice" => $basePrice > $price ? Money::format($basePrice, $currency) : "",
"sum" => Money::format($price * $quantity, $currency),
];
}
if ($currency === "") {
$currency = Loader::includeModule("currency") ? (string)CurrencyManager::getBaseCurrency() : "";
}
return [
"count" => $count,
"summary" => Loc::getMessagePlural("VINO_CART_LINES", $lines, ["#COUNT#" => $lines]) . ", " . Loc::getMessagePlural("VINO_CART_BOTTLES", $count, ["#COUNT#" => $count]),
"items" => $items,
"base" => Money::format($base, $currency),
"discount" => $base > $sum ? "\u{2212}" . Money::format($base - $sum, $currency) : "",
"total" => Money::format($sum, $currency),
"coupons" => self::coupons(),
];
}
private static function coupons(): array
{
$coupons = [];
foreach ((array)DiscountCouponsManager::get(true, [], true, true) as $coupon) {
$coupons[] = [
"code" => (string)$coupon["COUPON"],
"applied" => (int)$coupon["STATUS"] === DiscountCouponsManager::STATUS_APPLYED,
];
}
return $coupons;
}
private static function applyDiscounts(BasketBase $basket): void
{
$discount = Discount::buildFromBasket($basket, new FuserContext((int)$basket->getFUserId(true)));
if ($discount === null) {
return;
}
$result = $discount->calculate();
if ($result->isSuccess()) {
$data = $result->getData();
if (isset($data["BASKET_ITEMS"])) {
$basket->applyDiscount($data["BASKET_ITEMS"]);
}
}
}
private static function findItem(BasketBase $basket, int $productId): ?BasketItemBase
{
foreach ($basket as $item) {
if ((int)$item->getProductId() === $productId && !$item->isDelay()) {
return $item;
}
}
return null;
}
}
@@ -0,0 +1,143 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca\Catalog;
use Bitrix\Iblock\ElementPropertyTable;
use Bitrix\Iblock\ElementTable;
use Bitrix\Iblock\PropertyTable;
use Bitrix\Main\Loader;
use Bitrix\Main\Type\DateTime;
use Jinove\Vinoteca\Config;
use Jinove\Vinoteca\PageSchema;
class BrandSchema
{
private const CONTEXT = "https://schema.org";
private const WINES_LIMIT = 24;
public static function list(array $items, string $name, string $description): array
{
$url = Config::host() . SITE_DIR . "brands/";
$list = [];
foreach (array_values($items) as $index => $item) {
$list[] = ["@type" => "ListItem", "position" => $index + 1, "url" => $item["url"], "name" => $item["name"]];
}
$page = [
"@type" => "CollectionPage",
"@id" => $url . "#webpage",
"url" => $url,
"name" => $name,
"description" => $description,
"inLanguage" => LANGUAGE_ID,
"about" => ["@id" => Config::host() . "/#store"],
"mainEntity" => ["@id" => $url . "#items"],
"workTranslation" => PageSchema::translations(SITE_DIR . "brands/", "CollectionPage"),
];
$itemList = ["@type" => "ItemList", "@id" => $url . "#items", "numberOfItems" => count($list), "itemListElement" => $list];
return ["@context" => self::CONTEXT, "@graph" => [$page, $itemList]];
}
public static function detail(array $brand, array $wines, int $winesTotal): array
{
$url = $brand["url"];
$node = [
"@type" => ["Brand", "Winery"],
"@id" => $url . "#brand",
"name" => $brand["name"],
"url" => $url,
];
if ($brand["description"] !== "") {
$node["description"] = $brand["description"];
}
if ($brand["logo"] !== "") {
$node["logo"] = PageSchema::image($url . "#logo", $brand["logo"], $brand["logoWidth"], $brand["logoHeight"]);
}
$address = ["@type" => "PostalAddress"];
if ($brand["country"] !== "") {
$address["addressCountry"] = $brand["country"];
}
if ($brand["region"] !== "") {
$address["addressRegion"] = $brand["region"];
}
if (count($address) > 1) {
$node["address"] = $address;
}
if (preg_match('/^\d{4}$/', $brand["founded"])) {
$node["foundingDate"] = $brand["founded"];
}
$list = [];
foreach (array_values($wines) as $index => $wine) {
$list[] = ["@type" => "ListItem", "position" => $index + 1, "url" => Config::host() . $wine["url"], "name" => $wine["name"]];
}
$page = [
"@type" => "CollectionPage",
"@id" => $url . "#webpage",
"url" => $url,
"name" => $brand["name"],
"description" => $brand["pageDescription"],
"inLanguage" => LANGUAGE_ID,
"mainEntity" => ["@id" => $url . "#brand"],
"workTranslation" => PageSchema::translations($brand["path"], "CollectionPage"),
];
$graph = [$page, $node];
if ($list) {
$graph[] = ["@type" => "ItemList", "@id" => $url . "#items", "numberOfItems" => $winesTotal, "itemListElement" => $list];
}
return ["@context" => self::CONTEXT, "@graph" => $graph];
}
public static function countryCode(string $englishName): string
{
return [
"Argentina" => "AR", "Australia" => "AU", "France" => "FR", "Hungary" => "HU", "Italy" => "IT",
"New Zealand" => "NZ", "Portugal" => "PT", "Spain" => "ES", "USA" => "US",
][trim($englishName)] ?? "";
}
public static function wines(int $brandId): array
{
$catalogId = Config::iblockId("catalog");
if ($brandId <= 0 || $catalogId <= 0 || !Loader::includeModule("iblock")) {
return ["items" => [], "total" => 0];
}
\CIBlock::registerWithTagCache($catalogId);
$property = PropertyTable::getRow(["select" => ["ID"], "filter" => ["=IBLOCK_ID" => $catalogId, "=CODE" => "BRAND"]]);
if ($property === null) {
return ["items" => [], "total" => 0];
}
$ids = [];
$rows = ElementPropertyTable::getList([
"select" => ["IBLOCK_ELEMENT_ID"],
"filter" => ["=IBLOCK_PROPERTY_ID" => (int)$property["ID"], "=VALUE_NUM" => $brandId],
]);
while ($row = $rows->fetch()) {
$ids[] = (int)$row["IBLOCK_ELEMENT_ID"];
}
if (!$ids) {
return ["items" => [], "total" => 0];
}
$now = new DateTime();
$ordered = ElementTable::getList([
"select" => ["ID"],
"filter" => [
"=IBLOCK_ID" => $catalogId,
"=ID" => $ids,
"=ACTIVE" => "Y",
["LOGIC" => "OR", ["=ACTIVE_FROM" => false], ["<=ACTIVE_FROM" => $now]],
["LOGIC" => "OR", ["=ACTIVE_TO" => false], [">=ACTIVE_TO" => $now]],
],
"order" => ["SORT" => "ASC", "ID" => "DESC"],
])->fetchAll();
$sortedIds = array_map(static fn(array $row): int => (int)$row["ID"], $ordered);
$summaries = Related::summariesById(array_slice($sortedIds, 0, self::WINES_LIMIT));
return [
"items" => array_values(array_filter(array_map(static fn(int $id): ?array => $summaries[$id] ?? null, array_slice($sortedIds, 0, self::WINES_LIMIT)))),
"total" => count($sortedIds),
];
}
}
@@ -0,0 +1,240 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca\Catalog;
use Bitrix\Catalog\ProductTable;
use Bitrix\Main\Application;
use Bitrix\Main\Loader;
use Bitrix\Main\Localization\Loc;
use Jinove\Vinoteca\Config;
use Jinove\Vinoteca\Money;
Loc::loadMessages(__FILE__);
final class Comparison
{
public const SESSION_KEY = "CATALOG_COMPARE_LIST";
public const MAX = 4;
private const ROWS = ["WINE_COLOR", "COUNTRY", "REGION", "BRAND", "GRAPE", "SUGAR", "ABV", "VOLUME", "VINTAGE", "AGING", "SERVE_TEMP"];
public static function folder(): string
{
return SITE_DIR . "compare/";
}
public static function preparePage(): void
{
global $APPLICATION;
self::prune();
$APPLICATION->SetTitle((string)Loc::getMessage("VINO_COMPARE_H1"));
$APPLICATION->SetPageProperty("title", (string)Loc::getMessage("VINO_COMPARE_H1"));
$APPLICATION->SetPageProperty("robots", "noindex, follow");
$APPLICATION->SetPageProperty("vino_alternates", "N");
}
public static function isEmpty(): bool
{
return !self::read();
}
public static function read(): array
{
$list = Application::getInstance()->getSession()[self::SESSION_KEY] ?? [];
return (array)($list[Config::iblockId("catalog")]["ITEMS"] ?? []);
}
public static function write(array $items): void
{
$session = Application::getInstance()->getSession();
$list = (array)($session[self::SESSION_KEY] ?? []);
$list[Config::iblockId("catalog")]["ITEMS"] = $items;
$session[self::SESSION_KEY] = $list;
}
public static function prune(): array
{
$items = self::read();
if (!$items || !Loader::includeModule("iblock")) {
return $items;
}
$active = array_flip(array_map("intval", array_column(\Bitrix\Iblock\ElementTable::getList([
"select" => ["ID"],
"filter" => ["=ID" => array_map("intval", array_keys($items)), "=IBLOCK_ID" => Config::iblockId("catalog"), "=ACTIVE" => "Y"],
])->fetchAll(), "ID")));
$kept = array_intersect_key($items, $active);
if (count($kept) !== count($items)) {
self::write($kept);
}
return $kept;
}
public static function params(): array
{
$catalog = Listing::catalogParams();
return [
"NAME" => self::SESSION_KEY,
"IBLOCK_TYPE" => $catalog["IBLOCK_TYPE"],
"IBLOCK_ID" => $catalog["IBLOCK_ID"],
"FIELD_CODE" => [],
"PROPERTY_CODE" => [],
"OFFERS_FIELD_CODE" => [],
"OFFERS_PROPERTY_CODE" => [],
"PRICE_CODE" => $catalog["PRICE_CODE"],
"USE_PRICE_COUNT" => "N",
"SHOW_PRICE_COUNT" => "1",
"PRICE_VAT_INCLUDE" => "Y",
"CONVERT_CURRENCY" => "N",
"BASKET_URL" => $catalog["BASKET_URL"],
"ACTION_VARIABLE" => $catalog["ACTION_VARIABLE"],
"PRODUCT_ID_VARIABLE" => $catalog["PRODUCT_ID_VARIABLE"],
"SECTION_ID_VARIABLE" => "SECTION_ID",
"DETAIL_URL" => $catalog["SEF_FOLDER"] . $catalog["SEF_URL_TEMPLATES"]["element"],
"DISPLAY_ELEMENT_SELECT_BOX" => "N",
"ELEMENT_SORT_FIELD" => "sort",
"ELEMENT_SORT_ORDER" => "asc",
"HIDE_NOT_AVAILABLE" => "N",
"TEMPLATE_THEME" => "",
];
}
public static function build(array $compareItems): array
{
$ids = [];
foreach ($compareItems as $item) {
$ids[] = (int)($item["ID"] ?? 0);
}
$ids = array_values(array_filter($ids));
if (!$ids || !Loader::includeModule("iblock")) {
return ["ITEMS" => [], "ROWS" => []];
}
$summaries = Related::summariesById($ids);
$prices = Prices::optimal($ids);
$available = self::availability($ids);
$catalogId = Config::iblockId("catalog");
$elements = [];
$rows = \CIBlockElement::GetList([], ["ID" => $ids, "IBLOCK_ID" => $catalogId], false, false, ["ID", "IBLOCK_ID", "NAME", "PREVIEW_PICTURE", "DETAIL_PICTURE"]);
while ($row = $rows->Fetch()) {
$row["PROPERTIES"] = [];
$elements[(int)$row["ID"]] = $row;
}
if ($elements) {
$properties = array_fill_keys(array_keys($elements), []);
\CIBlockElement::GetPropertyValuesArray($properties, $catalogId, ["ID" => array_keys($elements)]);
foreach ($properties as $id => $values) {
$elements[$id]["PROPERTIES"] = $values;
}
}
$brands = self::brandNames($elements);
$items = [];
$values = [];
foreach ($ids as $id) {
$element = $elements[$id] ?? null;
$summary = $summaries[$id] ?? null;
if ($element === null || $summary === null) {
continue;
}
$items[] = self::item($element, $summary, $prices[$id] ?? null, $available[$id] ?? false);
foreach (self::ROWS as $code) {
$values[$code][] = self::value($code, $element["PROPERTIES"], $brands);
}
}
$table = [];
foreach (self::ROWS as $code) {
$cells = $values[$code] ?? [];
if (!array_filter($cells, static fn(string $cell): bool => $cell !== "")) {
continue;
}
$same = count($cells) > 1 && count(array_unique($cells)) === 1;
$table[] = ["LABEL" => (string)Loc::getMessage("VINO_COMPARE_ROW_" . $code), "VALUES" => $cells, "SAME" => $same];
}
return ["ITEMS" => $items, "ROWS" => $table];
}
private static function item(array $element, array $summary, ?array $price, bool $available): array
{
$pictureId = (int)($element["PREVIEW_PICTURE"] ?: $element["DETAIL_PICTURE"]);
$prices = [];
if ($price) {
$prices[] = [
"RATIO_PRICE" => $price["price"],
"PRINT_RATIO_PRICE" => htmlspecialcharsbx(Money::format($price["price"], $price["currency"])),
"RATIO_BASE_PRICE" => $price["base"],
"PRINT_RATIO_BASE_PRICE" => htmlspecialcharsbx(Money::format($price["base"], $price["currency"])),
"PERCENT" => $price["base"] > 0 ? round(100 - $price["price"] / $price["base"] * 100) : 0,
];
}
return [
"ID" => (int)$element["ID"],
"NAME" => htmlspecialcharsbx((string)$summary["name"]),
"~NAME" => (string)$summary["name"],
"DETAIL_PAGE_URL" => htmlspecialcharsbx((string)$summary["url"]),
"~DETAIL_PAGE_URL" => (string)$summary["url"],
"PREVIEW_PICTURE" => $pictureId > 0 ? ["ID" => $pictureId] : null,
"DETAIL_PICTURE" => null,
"PROPERTIES" => $element["PROPERTIES"],
"ITEM_PRICES" => $prices,
"ITEM_PRICE_SELECTED" => 0,
"CAN_BUY" => $available && $prices !== [],
];
}
private static function value(string $code, array $properties, array $brands): string
{
$raw = $properties[$code]["~VALUE"] ?? $properties[$code]["VALUE"] ?? "";
if (is_array($raw) && !isset($raw["TEXT"])) {
$raw = implode(", ", array_filter($raw));
}
$plain = trim(is_array($raw) ? (string)($raw["TEXT"] ?? "") : (string)$raw);
$number = static fn(string $value): string => LANGUAGE_ID === "en" ? $value : str_replace(".", ",", $value);
return match ($code) {
"WINE_COLOR", "COUNTRY", "REGION", "GRAPE", "SUGAR" => EnumNames::fromProperty($properties[$code] ?? []),
"BRAND" => $brands[(int)$plain] ?? "",
"ABV" => $plain !== "" ? $number((string)(float)$plain) . "%" : "",
"VOLUME" => $plain !== "" ? (string)Loc::getMessage("VINO_COMPARE_VOLUME", ["#VALUE#" => $number($plain)]) : "",
"AGING" => LocalizedText::property($properties, $code),
default => $plain,
};
}
private static function brandNames(array $elements): array
{
$ids = [];
foreach ($elements as $element) {
$value = $element["PROPERTIES"]["BRAND"]["VALUE"] ?? 0;
$ids[] = (int)(is_array($value) ? reset($value) : $value);
}
$ids = array_values(array_unique(array_filter($ids)));
if (!$ids) {
return [];
}
$names = [];
$rows = \Bitrix\Iblock\ElementTable::getList(["select" => ["ID", "NAME"], "filter" => ["=ID" => $ids]]);
while ($row = $rows->fetch()) {
$names[(int)$row["ID"]] = (string)$row["NAME"];
}
return $names;
}
private static function availability(array $ids): array
{
if (!Loader::includeModule("catalog")) {
return [];
}
$available = [];
$rows = ProductTable::getList(["select" => ["ID", "AVAILABLE"], "filter" => ["=ID" => $ids]]);
while ($row = $rows->fetch()) {
$available[(int)$row["ID"]] = $row["AVAILABLE"] === "Y";
}
return $available;
}
}
@@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca\Catalog;
use Jinove\Vinoteca\Config;
use Jinove\Vinoteca\Cached;
class Countries
{
private const CACHE_TTL = 86400;
private const CACHE_DIR = "/jinove.vinoteca/countries";
private static ?array $names = null;
public static function names(): array
{
if (self::$names !== null) {
return self::$names;
}
$catalogId = Config::iblockId("catalog");
return self::$names = (array)Cached::remember(self::CACHE_DIR, "names-" . $catalogId, self::CACHE_TTL, ["iblock_id_" . $catalogId], static function () use ($catalogId): array {
$names = [];
$rows = \CIBlockPropertyEnum::GetList(["SORT" => "ASC", "VALUE" => "ASC"], ["IBLOCK_ID" => $catalogId, "CODE" => "COUNTRY"]);
while ($row = $rows->Fetch()) {
$names[(string)$row["XML_ID"]] = (string)$row["VALUE"];
}
return $names;
});
}
}
@@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca\Catalog;
use Bitrix\Main\Localization\Loc;
Loc::loadMessages(__FILE__);
class EnumNames
{
public static function name(string $propertyCode, string $xmlId, string $fallback = "", ?string $language = null): string
{
$key = "VINO_ENUM_" . $propertyCode . "_" . strtoupper(str_replace("-", "_", $xmlId));
$message = Loc::getMessage($key, null, $language);
return $message !== null && $message !== "" ? $message : $fallback;
}
public static function fromProperty(array $property): string
{
$xmlIds = (array)($property["VALUE_XML_ID"] ?? []);
$values = (array)($property["~VALUE"] ?? $property["VALUE"] ?? []);
$names = [];
foreach ($xmlIds as $index => $xmlId) {
if ((string)$xmlId === "") {
continue;
}
$names[] = self::name((string)$property["CODE"], (string)$xmlId, (string)($values[$index] ?? ""));
}
return implode(", ", $names);
}
}
@@ -0,0 +1,95 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca\Catalog;
use Bitrix\Iblock\ElementTable;
use Bitrix\Main\Loader;
use Bitrix\Main\ORM\Data\DataManager;
use Bitrix\Sale\Fuser;
use Jinove\Vinoteca\Config;
use Bitrix\Main\ORM\Fields\DatetimeField;
use Bitrix\Main\ORM\Fields\IntegerField;
use Bitrix\Main\Type\DateTime;
class FavoriteTable extends DataManager
{
private static int $guestFuser = 0;
public static function getTableName(): string
{
return "jinove_vinoteca_favorite";
}
public static function getMap(): array
{
return [
(new IntegerField("ID"))->configurePrimary()->configureAutocomplete(),
(new IntegerField("FUSER_ID"))->configureRequired(),
(new IntegerField("PRODUCT_ID"))->configureRequired(),
(new DatetimeField("DATE_CREATE"))->configureDefaultValue(static fn(): DateTime => new DateTime()),
];
}
public static function productIds(int $fuserId): array
{
if ($fuserId <= 0) {
return [];
}
$ids = array_map("intval", array_column(self::getList([
"select" => ["PRODUCT_ID"],
"filter" => ["=FUSER_ID" => $fuserId],
"order" => ["ID" => "ASC"],
])->fetchAll(), "PRODUCT_ID"));
if (!$ids || !Loader::includeModule("iblock")) {
return [];
}
$active = array_flip(array_map("intval", array_column(ElementTable::getList([
"select" => ["ID"],
"filter" => ["=ID" => $ids, "=IBLOCK_ID" => Config::iblockId("catalog"), "=ACTIVE" => "Y"],
])->fetchAll(), "ID")));
return array_values(array_filter($ids, static fn(int $id): bool => isset($active[$id])));
}
public static function onElementDelete(array $fields): void
{
$productId = (int)($fields["ID"] ?? 0);
if ($productId <= 0) {
return;
}
$rows = self::getList(["select" => ["ID"], "filter" => ["=PRODUCT_ID" => $productId]]);
while ($row = $rows->fetch()) {
self::delete((int)$row["ID"]);
}
}
public static function rememberGuest(): void
{
if (Loader::includeModule("sale")) {
self::$guestFuser = (int)Fuser::getId(true);
}
}
public static function mergeGuest(): void
{
if (self::$guestFuser <= 0 || !Loader::includeModule("sale")) {
return;
}
$userFuser = (int)Fuser::getId(true);
if ($userFuser <= 0 || $userFuser === self::$guestFuser) {
return;
}
$owned = array_flip(array_map("intval", array_column(self::getList(["select" => ["PRODUCT_ID"], "filter" => ["=FUSER_ID" => $userFuser]])->fetchAll(), "PRODUCT_ID")));
$rows = self::getList(["select" => ["ID", "PRODUCT_ID"], "filter" => ["=FUSER_ID" => self::$guestFuser]]);
while ($row = $rows->fetch()) {
if (isset($owned[(int)$row["PRODUCT_ID"]])) {
self::delete((int)$row["ID"]);
} else {
self::update((int)$row["ID"], ["FUSER_ID" => $userFuser]);
}
}
self::$guestFuser = 0;
}
}
@@ -0,0 +1,88 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca\Catalog;
use Bitrix\Main\Loader;
use Bitrix\Main\Localization\Loc;
use Bitrix\Main\Page\Asset;
use Bitrix\Sale\Fuser;
Loc::loadMessages(__FILE__);
final class Favorites
{
public const FILTER = "vinoFavoritesFilter";
public static function preparePage(): void
{
global $APPLICATION;
$APPLICATION->SetTitle((string)Loc::getMessage("VINO_FAVORITES_H1"));
$APPLICATION->SetPageProperty("title", (string)Loc::getMessage("VINO_FAVORITES_H1"));
$APPLICATION->SetPageProperty("robots", "noindex, follow");
$APPLICATION->SetPageProperty("vino_alternates", "N");
Asset::getInstance()->addCss(SITE_TEMPLATE_PATH . "/catalog-styles.css");
Asset::getInstance()->addJs(SITE_TEMPLATE_PATH . "/assets/js/vino-favorites.js");
}
public static function ids(): array
{
if (!Loader::includeModule("sale")) {
return [];
}
return FavoriteTable::productIds((int)Fuser::getId(true));
}
public static function params(array $ids): array
{
$GLOBALS[self::FILTER] = ["ID" => $ids ?: [0]];
$catalog = Listing::catalogParams();
return [
"IBLOCK_TYPE" => $catalog["IBLOCK_TYPE"],
"IBLOCK_ID" => $catalog["IBLOCK_ID"],
"SECTION_ID" => 0,
"SHOW_ALL_WO_SECTION" => "Y",
"FILTER_NAME" => self::FILTER,
"PRICE_CODE" => $catalog["PRICE_CODE"],
"BASKET_URL" => $catalog["BASKET_URL"],
"PAGE_ELEMENT_COUNT" => "24",
"LINE_ELEMENT_COUNT" => "4",
"INCLUDE_SUBSECTIONS" => "Y",
"ELEMENT_SORT_FIELD" => "SORT",
"ELEMENT_SORT_ORDER" => "ASC",
"ELEMENT_SORT_FIELD2" => "ID",
"ELEMENT_SORT_ORDER2" => "DESC",
"PROPERTY_CODE" => $catalog["LIST_PROPERTY_CODE"],
"CACHE_TYPE" => $catalog["CACHE_TYPE"],
"CACHE_TIME" => $catalog["CACHE_TIME"],
"CACHE_GROUPS" => $catalog["CACHE_GROUPS"],
"CACHE_FILTER" => "Y",
"SET_TITLE" => "N",
"SET_BROWSER_TITLE" => "N",
"SET_META_KEYWORDS" => "N",
"SET_META_DESCRIPTION" => "N",
"SET_STATUS_404" => "N",
"SHOW_404" => "N",
"ADD_SECTIONS_CHAIN" => "N",
"ACTION_VARIABLE" => $catalog["ACTION_VARIABLE"],
"PRODUCT_ID_VARIABLE" => $catalog["PRODUCT_ID_VARIABLE"],
"USE_PRODUCT_QUANTITY" => "Y",
"ADD_TO_BASKET_ACTION" => "ADD",
"SHOW_OLD_PRICE" => "Y",
"SHOW_DISCOUNT_PERCENT" => "Y",
"DISPLAY_TOP_PAGER" => "N",
"DISPLAY_BOTTOM_PAGER" => "Y",
"PAGER_TEMPLATE" => "vinoteca",
"PAGER_SHOW_ALWAYS" => "N",
"PAGER_TITLE" => (string)Loc::getMessage("VINO_FAVORITES_PAGER_TITLE"),
"SECTION_URL" => $catalog["SEF_FOLDER"] . $catalog["SEF_URL_TEMPLATES"]["section"],
"DETAIL_URL" => $catalog["SEF_FOLDER"] . $catalog["SEF_URL_TEMPLATES"]["element"],
"HIDE_NOT_AVAILABLE" => "N",
"VINO_TITLE_TAG" => "h2",
"VINO_GRID_FULL" => "Y",
];
}
}
@@ -0,0 +1,186 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca\Catalog;
class Listing
{
public const SORTS = ["new", "price_asc", "price_desc", "name"];
public static function catalogParams(): array
{
return [
"IBLOCK_TYPE" => "catalog",
"IBLOCK_ID" => VINO_CATALOG_IBLOCK,
"SEF_MODE" => "Y",
"SEF_FOLDER" => SITE_DIR . "catalog/",
"SEF_URL_TEMPLATES" => [
"sections" => "",
"section" => "#SECTION_CODE#/",
"element" => "#SECTION_CODE#/#ELEMENT_CODE#/",
"smart_filter" => "#SECTION_CODE#/filter/#SMART_FILTER_PATH#/apply/",
],
"PRICE_CODE" => ["BASE"],
"BASKET_URL" => SITE_DIR . "personal/cart/",
"ACTION_VARIABLE" => "action",
"PRODUCT_ID_VARIABLE" => "id",
"CACHE_TYPE" => "A",
"CACHE_TIME" => "3600",
"CACHE_GROUPS" => "N",
"SET_STATUS_404" => "Y",
"SHOW_404" => "Y",
"MESSAGE_404" => "",
"FILE_404" => "",
"LIST_PROPERTY_CODE" => ["WINE_COLOR", "SUGAR", "VOLUME", "REGION", "COUNTRY"],
"DETAIL_PROPERTY_CODE" => ["WINE_COLOR", "SUGAR", "GRAPE", "VOLUME", "ABV", "REGION", "COUNTRY", "BRAND", "ARTNUMBER", "VINTAGE", "AGING", "SERVE_TEMP", "FOOD_PAIRING", "TASTE_COLOR", "AROMA", "TASTE", "MORE_PHOTO"],
];
}
public static function sectionTilesParams(): array
{
$catalog = self::catalogParams();
return [
"IBLOCK_TYPE" => $catalog["IBLOCK_TYPE"],
"IBLOCK_ID" => $catalog["IBLOCK_ID"],
"SECTION_ID" => "",
"SECTION_CODE" => "",
"TOP_DEPTH" => "1",
"COUNT_ELEMENTS" => "Y",
"COUNT_ELEMENTS_FILTER" => "CNT_ACTIVE",
"HIDE_SECTIONS_WITH_ZERO_COUNT_ELEMENTS" => "Y",
"SECTION_FIELDS" => ["CODE", "PICTURE"],
"SECTION_USER_FIELDS" => [],
"ADD_SECTIONS_CHAIN" => "N",
"CACHE_TYPE" => $catalog["CACHE_TYPE"],
"CACHE_TIME" => $catalog["CACHE_TIME"],
"CACHE_GROUPS" => $catalog["CACHE_GROUPS"],
];
}
public static function prepareBestsellers(): array
{
$GLOBALS["bestsellersFilter"] = ["!PROPERTY_SALELEADER" => false];
$catalog = self::catalogParams();
return [
"IBLOCK_TYPE" => $catalog["IBLOCK_TYPE"],
"IBLOCK_ID" => $catalog["IBLOCK_ID"],
"ELEMENT_COUNT" => "12",
"FILTER_NAME" => "bestsellersFilter",
"ELEMENT_SORT_FIELD" => "SORT",
"ELEMENT_SORT_ORDER" => "asc",
"ELEMENT_SORT_FIELD2" => "PROPERTY_RATING",
"ELEMENT_SORT_ORDER2" => "desc",
"PROPERTY_CODE" => $catalog["LIST_PROPERTY_CODE"],
"PRICE_CODE" => $catalog["PRICE_CODE"],
"PRICE_VAT_INCLUDE" => "Y",
"USE_PRICE_COUNT" => "N",
"SHOW_PRICE_COUNT" => "1",
"CONVERT_CURRENCY" => "N",
"HIDE_NOT_AVAILABLE" => "N",
"DETAIL_URL" => SITE_DIR . "catalog/#SECTION_CODE#/#ELEMENT_CODE#/",
"SECTION_URL" => SITE_DIR . "catalog/#SECTION_CODE#/",
"CACHE_TYPE" => $catalog["CACHE_TYPE"],
"CACHE_TIME" => $catalog["CACHE_TIME"],
"CACHE_GROUPS" => $catalog["CACHE_GROUPS"],
"CACHE_FILTER" => "Y",
];
}
public static function filterParams(string $sectionCode, string $filterPath): array
{
$catalog = self::catalogParams();
return [
"IBLOCK_TYPE" => $catalog["IBLOCK_TYPE"],
"IBLOCK_ID" => $catalog["IBLOCK_ID"],
"SECTION_CODE" => $sectionCode,
"FILTER_NAME" => "wineFilter",
"PRICE_CODE" => $catalog["PRICE_CODE"],
"CACHE_TYPE" => $catalog["CACHE_TYPE"],
"CACHE_TIME" => $catalog["CACHE_TIME"],
"CACHE_GROUPS" => $catalog["CACHE_GROUPS"],
"SAVE_IN_SESSION" => "N",
"XML_EXPORT" => "N",
"SEF_MODE" => "Y",
"SEF_RULE" => $catalog["SEF_FOLDER"] . $catalog["SEF_URL_TEMPLATES"]["smart_filter"],
"SMART_FILTER_PATH" => $filterPath,
"INSTANT_RELOAD" => "N",
"TEMPLATE_THEME" => "",
"CONVERT_CURRENCY" => "N",
];
}
public static function countryCodeFromRoute(array $variables): ?string
{
$code = (string)($variables["ELEMENT_CODE"] ?? "");
return ($variables["SECTION_CODE"] ?? "") === "country" && $code !== "" ? $code : null;
}
public static function countryPath(string $countryCode): string
{
return self::catalogParams()["SEF_FOLDER"] . "country/" . rawurlencode($countryCode) . "/";
}
public static function sectionPath(string $sectionCode): string
{
return self::catalogParams()["SEF_FOLDER"] . $sectionCode . "/";
}
public static function basePath(string $sectionCode, string $filterPath): string
{
$sectionPath = self::sectionPath($sectionCode);
return $filterPath !== "" ? $sectionPath . "filter/" . $filterPath . "/apply/" : $sectionPath;
}
public static function pagePath(string $sectionCode, string $filterPath, string $sort, int $page): string
{
$sectionPath = self::sectionPath($sectionCode);
if ($filterPath === "" && $sort === "" && $page > 1) {
return $sectionPath . "?PAGEN_1=" . $page;
}
return $sectionPath;
}
public static function filterPathIsValid(string $sectionCode, string $filterPath): bool
{
if ($filterPath === "") {
return true;
}
global $APPLICATION;
ob_start();
try {
$result = $APPLICATION->IncludeComponent("bitrix:catalog.smart.filter", "", self::filterParams($sectionCode, $filterPath), null, [], true);
} finally {
ob_end_clean();
}
return (string)($result["JS_FILTER_PARAMS"]["SEF_SET_FILTER_URL"] ?? "") === self::basePath($sectionCode, $filterPath);
}
public static function parsePath(string $path): ?array
{
$catalog = self::catalogParams();
$variables = [];
$engine = new \CComponentEngine();
$engine->addGreedyPart("#SMART_FILTER_PATH#");
$page = $engine->guessComponentPath($catalog["SEF_FOLDER"], $catalog["SEF_URL_TEMPLATES"], $variables, str_ends_with($path, "/") ? $path . "index.php" : $path);
if ($page !== "section" && $page !== "smart_filter") {
return null;
}
$sectionCode = (string)($variables["SECTION_CODE"] ?? "");
if ($sectionCode === "" || $sectionCode !== strtolower($sectionCode) || Sections::byCode($sectionCode) === []) {
return null;
}
return [
"SECTION_CODE" => $sectionCode,
"FILTER_PATH" => (string)($variables["SMART_FILTER_PATH"] ?? ""),
];
}
}
@@ -0,0 +1,79 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca\Catalog;
class LocalizedText
{
private const BASE_LANGUAGE = "ru";
public static function property(array $properties, string $code): string
{
if (LANGUAGE_ID !== self::BASE_LANGUAGE) {
$translated = self::value($properties[$code . "_" . strtoupper(LANGUAGE_ID)] ?? []);
if ($translated !== "") {
return $translated;
}
}
return self::value($properties[$code] ?? []);
}
public static function detailText(array $element): string
{
return self::field($element, "DETAIL_TEXT");
}
public static function field(array $element, string $field): string
{
if (LANGUAGE_ID !== self::BASE_LANGUAGE) {
$translated = self::value($element["PROPERTIES"][$field . "_" . strtoupper(LANGUAGE_ID)] ?? []);
if ($translated !== "") {
return $translated;
}
}
return (string)($element["~" . $field] ?? $element[$field] ?? "");
}
public static function localizeItem(array $item, array $fields, array $properties = []): array
{
if (LANGUAGE_ID === self::BASE_LANGUAGE) {
return $item;
}
$suffix = "_" . strtoupper(LANGUAGE_ID);
foreach ($fields as $field) {
$value = self::value($item["PROPERTIES"][$field . $suffix] ?? []);
if ($value !== "") {
$item["~" . $field] = $value;
$item[$field] = htmlspecialcharsbx($value);
}
}
foreach ($properties as $code) {
$value = self::value($item["PROPERTIES"][$code . $suffix] ?? []);
if ($value === "" || !isset($item["PROPERTIES"][$code])) {
continue;
}
$item["PROPERTIES"][$code]["~VALUE"] = $value;
$item["PROPERTIES"][$code]["VALUE"] = htmlspecialcharsbx($value);
if (isset($item["DISPLAY_PROPERTIES"][$code])) {
$item["DISPLAY_PROPERTIES"][$code]["~VALUE"] = $value;
$item["DISPLAY_PROPERTIES"][$code]["VALUE"] = htmlspecialcharsbx($value);
$item["DISPLAY_PROPERTIES"][$code]["DISPLAY_VALUE"] = htmlspecialcharsbx($value);
}
}
return $item;
}
private static function value(array $property): string
{
$value = $property["~VALUE"] ?? $property["VALUE"] ?? "";
if (is_array($value)) {
$value = $value["TEXT"] ?? implode(", ", array_filter($value, "is_scalar"));
}
return trim((string)$value);
}
}
@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca\Catalog;
use Bitrix\Iblock\ElementTable;
use Bitrix\Main\Loader;
final class Media
{
public static function thumbs(array $productIds, int $width, int $height): array
{
$productIds = array_values(array_unique(array_filter(array_map("intval", $productIds))));
if (!$productIds || !Loader::includeModule("iblock")) {
return [];
}
$images = [];
$rows = ElementTable::getList(["select" => ["ID", "PREVIEW_PICTURE", "DETAIL_PICTURE"], "filter" => ["=ID" => $productIds]]);
while ($row = $rows->fetch()) {
$fileId = (int)($row["DETAIL_PICTURE"] ?: $row["PREVIEW_PICTURE"]);
if ($fileId > 0) {
$resized = \CFile::ResizeImageGet($fileId, ["width" => $width, "height" => $height], BX_RESIZE_IMAGE_PROPORTIONAL, false);
if (!empty($resized["src"])) {
$images[(int)$row["ID"]] = (string)$resized["src"];
}
}
}
return $images;
}
}
@@ -0,0 +1,130 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca\Catalog;
use Bitrix\Iblock\ElementPropertyTable;
use Bitrix\Iblock\ElementTable;
use Bitrix\Iblock\PropertyEnumerationTable;
use Bitrix\Iblock\PropertyTable;
use Bitrix\Iblock\SectionElementTable;
use Bitrix\Main\DI\ServiceLocator;
use Bitrix\Main\Loader;
use Bitrix\Main\ORM\Fields\ExpressionField;
use Jinove\Vinoteca\Config;
final class MegaMenu
{
public static function tags(int $iblockId): array
{
return ["iblock_id_" . $iblockId, "iblock_id_" . Config::iblockId("brands")];
}
public static function collect(int $iblockId, int $brandsLimit): array
{
$result = ["TYPES" => [], "COUNTRIES" => [], "BRANDS" => [], "TOTAL" => 0];
if (!Loader::includeModule("iblock")) {
return $result;
}
$result["TYPES"] = self::types($iblockId);
$result["COUNTRIES"] = self::countries($iblockId);
$result["BRANDS"] = array_slice(self::brands($iblockId), 0, $brandsLimit);
$result["TOTAL"] = ServiceLocator::getInstance()->get("jinove.vinoteca.wineStats")->getActiveCount();
return $result;
}
public static function types(int $iblockId): array
{
$counts = [];
$rows = SectionElementTable::getList([
"select" => ["IBLOCK_SECTION_ID", "CNT"],
"runtime" => [new ExpressionField("CNT", "COUNT(DISTINCT %s)", "IBLOCK_ELEMENT_ID")],
"filter" => ["=IBLOCK_ELEMENT.IBLOCK_ID" => $iblockId, "=IBLOCK_ELEMENT.ACTIVE" => "Y"],
"group" => ["IBLOCK_SECTION_ID"],
]);
while ($row = $rows->fetch()) {
$counts[(int)$row["IBLOCK_SECTION_ID"]] = (int)$row["CNT"];
}
$types = [];
foreach (Sections::all() as $code => $section) {
$count = $counts[$section["ID"]] ?? 0;
if ($section["ACTIVE"] && $section["DEPTH_LEVEL"] === 1 && $count > 0) {
$types[] = ["NAME" => $section["NAME"], "URL" => SITE_DIR . "catalog/" . $code . "/", "COUNT" => $count];
}
}
return $types;
}
private static function countries(int $iblockId): array
{
$propertyId = self::propertyId($iblockId, "COUNTRY");
if ($propertyId <= 0) {
return [];
}
$xmlIds = [];
$rows = PropertyEnumerationTable::getList(["select" => ["ID", "XML_ID"], "filter" => ["=PROPERTY_ID" => $propertyId]]);
while ($row = $rows->fetch()) {
$xmlIds[(int)$row["ID"]] = (string)$row["XML_ID"];
}
$names = Countries::names();
$countries = [];
foreach (self::counts($iblockId, $propertyId, "VALUE_ENUM") as $enumId => $count) {
$code = $xmlIds[$enumId] ?? "";
if ($code !== "" && isset($names[$code])) {
$countries[] = ["NAME" => EnumNames::name("COUNTRY", $code, $names[$code]), "URL" => Listing::countryPath($code), "COUNT" => $count];
}
}
usort($countries, static fn(array $a, array $b): int => $b["COUNT"] <=> $a["COUNT"]);
return $countries;
}
private static function brands(int $iblockId): array
{
$propertyId = self::propertyId($iblockId, "BRAND");
if ($propertyId <= 0) {
return [];
}
$counts = self::counts($iblockId, $propertyId, "VALUE_NUM");
if (!$counts) {
return [];
}
$brands = [];
$rows = ElementTable::getList([
"select" => ["ID", "NAME", "CODE"],
"filter" => ["=ID" => array_keys($counts), "=ACTIVE" => "Y"],
]);
while ($row = $rows->fetch()) {
$brands[] = ["NAME" => (string)$row["NAME"], "URL" => SITE_DIR . "brands/" . $row["CODE"] . "/", "COUNT" => $counts[(int)$row["ID"]]];
}
usort($brands, static fn(array $a, array $b): int => $b["COUNT"] <=> $a["COUNT"]);
return $brands;
}
private static function counts(int $iblockId, int $propertyId, string $valueField): array
{
$counts = [];
$rows = ElementPropertyTable::getList([
"select" => [$valueField, "CNT"],
"runtime" => [new ExpressionField("CNT", "COUNT(DISTINCT %s)", "IBLOCK_ELEMENT_ID")],
"filter" => ["=IBLOCK_PROPERTY_ID" => $propertyId, "=ELEMENT.IBLOCK_ID" => $iblockId, "=ELEMENT.ACTIVE" => "Y", ">" . $valueField => 0],
"group" => [$valueField],
]);
while ($row = $rows->fetch()) {
$counts[(int)$row[$valueField]] = (int)$row["CNT"];
}
return $counts;
}
private static function propertyId(int $iblockId, string $code): int
{
$row = PropertyTable::getRow(["select" => ["ID"], "filter" => ["=IBLOCK_ID" => $iblockId, "=CODE" => $code]]);
return (int)($row["ID"] ?? 0);
}
}
@@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca\Catalog;
use Bitrix\Iblock\ElementTable;
use Jinove\Vinoteca\Config;
class PhotoSort
{
public const WITH_PHOTO = 100;
public const WITHOUT_PHOTO = 500;
private static bool $busy = false;
public static function onElementChange(array &$fields): void
{
$id = (int)($fields["ID"] ?? 0);
$catalogId = Config::iblockId("catalog");
if (self::$busy || $id <= 0 || $catalogId <= 0 || (int)($fields["IBLOCK_ID"] ?? 0) !== $catalogId) {
return;
}
self::apply($id);
}
public static function apply(int $id): void
{
$row = ElementTable::getRow([
"select" => ["DETAIL_PICTURE", "SORT", "IBLOCK_ID"],
"filter" => ["=ID" => $id],
]);
if (!$row) {
return;
}
$sort = (int)$row["DETAIL_PICTURE"] > 0 ? self::WITH_PHOTO : self::WITHOUT_PHOTO;
if ((int)$row["SORT"] === $sort) {
return;
}
self::$busy = true;
(new \CIBlockElement())->Update($id, ["SORT" => $sort], false, false, false);
self::$busy = false;
}
}
@@ -0,0 +1,65 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca\Catalog;
use Bitrix\Catalog\GroupTable;
use Bitrix\Main\Loader;
use Jinove\Vinoteca\Cached;
class PricePresets
{
private const CACHE_TTL = 86400;
private const CACHE_DIR = "/jinove.vinoteca/pricepresets";
private const LIMITS = [3000, 5000, 10000];
public static function limits(int $iblockId, string $sectionCode, string $priceCode): array
{
return (array)Cached::remember(self::CACHE_DIR, "limits-" . $iblockId . "-" . $sectionCode . "-" . $priceCode, self::CACHE_TTL, ["iblock_id_" . $iblockId], static fn(): array => self::collect($iblockId, $sectionCode, $priceCode));
}
public static function groupId(string $priceCode): int
{
if (!Loader::includeModule("catalog")) {
return 0;
}
$group = GroupTable::getRow([
"select" => ["ID"],
"filter" => ["=NAME" => $priceCode],
"cache" => ["ttl" => self::CACHE_TTL],
]);
return $group === null ? 0 : (int)$group["ID"];
}
private static function collect(int $iblockId, string $sectionCode, string $priceCode): array
{
if (!Loader::includeModule("iblock")) {
return [];
}
$groupId = self::groupId($priceCode);
if ($groupId === 0) {
return [];
}
$filter = [
"IBLOCK_ID" => $iblockId,
"ACTIVE" => "Y",
"SECTION_CODE" => $sectionCode,
"INCLUDE_SUBSECTIONS" => "Y",
];
$total = (int)\CIBlockElement::GetList([], $filter, []);
$limits = [];
$previous = 0;
foreach (self::LIMITS as $limit) {
$count = (int)\CIBlockElement::GetList([], $filter + ["<=CATALOG_PRICE_" . $groupId => $limit], []);
if ($count > $previous && $count < $total) {
$limits[] = $limit;
$previous = $count;
}
}
return $limits;
}
}
@@ -0,0 +1,48 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca\Catalog;
use Bitrix\Catalog\PriceTable;
use Bitrix\Currency\CurrencyManager;
use Bitrix\Main\Entity\ExpressionField;
use Bitrix\Main\Loader;
use Jinove\Vinoteca\Config;
use Jinove\Vinoteca\Cached;
class PriceRange
{
private const CACHE_TTL = 86400;
private const CACHE_DIR = "/jinove.vinoteca/pricerange";
public static function get(string $priceCode = "BASE"): string
{
$catalogId = Config::iblockId("catalog");
return (string)Cached::remember(self::CACHE_DIR, "range-" . $catalogId . "-" . $priceCode, self::CACHE_TTL, ["iblock_id_" . $catalogId], static fn(): string => self::collect($priceCode));
}
private static function collect(string $priceCode): string
{
if (!Loader::includeModule("catalog") || !Loader::includeModule("currency")) {
return "";
}
$groupId = PricePresets::groupId($priceCode);
if ($groupId === 0) {
return "";
}
$row = PriceTable::getList([
"select" => ["MIN_PRICE", "MAX_PRICE"],
"filter" => ["=CATALOG_GROUP_ID" => $groupId, ">PRICE" => 0],
"runtime" => [
new ExpressionField("MIN_PRICE", "MIN(%s)", "PRICE"),
new ExpressionField("MAX_PRICE", "MAX(%s)", "PRICE"),
],
])->fetch();
if (!$row || $row["MIN_PRICE"] <= 0) {
return "";
}
return (int)round((float)$row["MIN_PRICE"]) . "-" . (int)round((float)$row["MAX_PRICE"]) . " " . CurrencyManager::getBaseCurrency();
}
}
@@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca\Catalog;
use Bitrix\Main\Engine\CurrentUser;
use Bitrix\Main\Loader;
final class Prices
{
public static function optimal(array $productIds, string $siteId = SITE_ID): array
{
$productIds = array_values(array_unique(array_filter(array_map("intval", $productIds))));
if (!$productIds || !Loader::includeModule("catalog") || !Loader::includeModule("currency")) {
return [];
}
$groups = CurrentUser::get()->getUserGroups();
$prices = [];
foreach ($productIds as $productId) {
$optimal = \CCatalogProduct::GetOptimalPrice($productId, 1, $groups, "N", [], $siteId);
$price = $optimal["RESULT_PRICE"] ?? null;
if (!$price || (float)$price["DISCOUNT_PRICE"] <= 0) {
continue;
}
$prices[$productId] = [
"price" => (float)$price["DISCOUNT_PRICE"],
"base" => max((float)$price["DISCOUNT_PRICE"], (float)$price["BASE_PRICE"]),
"currency" => (string)$price["CURRENCY"],
];
}
return $prices;
}
}
@@ -0,0 +1,110 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca\Catalog;
use Bitrix\Iblock\ElementPropertyTable;
use Bitrix\Iblock\ElementTable;
use Bitrix\Iblock\IblockTable;
use Bitrix\Iblock\PropertyTable;
use Bitrix\Iblock\SectionTable;
use Bitrix\Main\Loader;
use Jinove\Vinoteca\Config;
use Jinove\Vinoteca\Cached;
class Related
{
private const CACHE_TTL = 86400;
private const CACHE_DIR = "/jinove.vinoteca/related";
public static function ids(int $iblockId, int $elementId): array
{
if (!Loader::includeModule("iblock")) {
return [];
}
$property = PropertyTable::getRow(["select" => ["ID"], "filter" => ["=IBLOCK_ID" => $iblockId, "=CODE" => "RECOMMEND"]]);
if ($property === null) {
return [];
}
$linked = [];
$rows = ElementPropertyTable::getList([
"select" => ["VALUE"],
"filter" => ["=IBLOCK_ELEMENT_ID" => $elementId, "=IBLOCK_PROPERTY_ID" => (int)$property["ID"]],
"order" => ["ID" => "ASC"],
]);
while ($row = $rows->fetch()) {
$linked[] = (int)$row["VALUE"];
}
$linked = array_values(array_filter(array_unique($linked)));
if (!$linked) {
return [];
}
$active = [];
$items = ElementTable::getList(["select" => ["ID"], "filter" => ["=ID" => $linked, "=IBLOCK_ID" => $iblockId, "=ACTIVE" => "Y"]]);
while ($item = $items->fetch()) {
$active[(int)$item["ID"]] = true;
}
return array_values(array_filter($linked, fn(int $id): bool => isset($active[$id])));
}
public static function summaries(array $ids): array
{
$found = self::summariesById($ids);
return array_values(array_filter(array_map(static fn(int $id): ?array => $found[$id] ?? null, $ids)));
}
public static function summariesById(array $ids): array
{
$ids = array_values(array_unique(array_filter(array_map("intval", $ids))));
if (!$ids) {
return [];
}
return array_intersect_key(self::all(), array_flip($ids));
}
private static function all(): array
{
$iblockId = Config::iblockId("catalog");
if ($iblockId <= 0 || !Loader::includeModule("iblock")) {
return [];
}
return (array)Cached::remember(self::CACHE_DIR, "summaries-" . $iblockId . "-" . SITE_DIR, self::CACHE_TTL, ["iblock_id_" . $iblockId], static fn(): array => self::collect($iblockId));
}
private static function collect(int $iblockId): array
{
$template = (string)(IblockTable::getRowById($iblockId)["DETAIL_PAGE_URL"] ?? "");
$elements = ElementTable::getList([
"select" => ["ID", "NAME", "CODE", "IBLOCK_SECTION_ID"],
"filter" => ["=IBLOCK_ID" => $iblockId, "=ACTIVE" => "Y"],
])->fetchAll();
$sectionIds = array_values(array_unique(array_filter(array_map(static fn(array $row): int => (int)$row["IBLOCK_SECTION_ID"], $elements))));
$sectionCodes = [];
if ($sectionIds) {
$sections = SectionTable::getList(["select" => ["ID", "CODE"], "filter" => ["=ID" => $sectionIds]]);
while ($section = $sections->fetch()) {
$sectionCodes[(int)$section["ID"]] = (string)$section["CODE"];
}
}
$found = [];
foreach ($elements as $row) {
$found[(int)$row["ID"]] = [
"name" => (string)$row["NAME"],
"url" => (string)preg_replace('#/{2,}#', "/", strtr($template, [
"#SITE_DIR#" => SITE_DIR,
"#SECTION_CODE#" => $sectionCodes[(int)$row["IBLOCK_SECTION_ID"]] ?? "",
"#ELEMENT_CODE#" => (string)$row["CODE"],
"#CODE#" => (string)$row["CODE"],
"#ID#" => (string)$row["ID"],
"#ELEMENT_ID#" => (string)$row["ID"],
])),
];
}
return $found;
}
}
@@ -0,0 +1,150 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca\Catalog;
use Bitrix\Iblock\ElementPropertyTable;
use Bitrix\Iblock\ElementTable;
use Bitrix\Iblock\IblockTable;
use Bitrix\Iblock\PropertyTable;
use Bitrix\Main\Loader;
class ReviewStats
{
public const IBLOCK_TYPE = "catalog";
public const REVIEWS_CODE = "reviews";
public const CATALOG_CODE = "wine";
private static array $iblockIds = [];
private static array $deleting = [];
public static function iblockId(string $code): int
{
if (!isset(self::$iblockIds[$code])) {
if (!Loader::includeModule("iblock")) {
return 0;
}
$row = IblockTable::getRow([
"select" => ["ID"],
"filter" => ["=IBLOCK_TYPE_ID" => self::IBLOCK_TYPE, "=CODE" => $code],
]);
self::$iblockIds[$code] = (int)($row["ID"] ?? 0);
}
return self::$iblockIds[$code];
}
public static function onElementChange(array &$fields): void
{
$id = (int)($fields["ID"] ?? 0);
if ($id <= 0 || (int)($fields["IBLOCK_ID"] ?? 0) !== self::iblockId(self::REVIEWS_CODE)) {
return;
}
self::recalc(self::productOf($id));
}
public static function onBeforeDelete(int $id): void
{
$row = ElementTable::getRow(["select" => ["IBLOCK_ID"], "filter" => ["=ID" => $id]]);
if ((int)($row["IBLOCK_ID"] ?? 0) === self::iblockId(self::REVIEWS_CODE)) {
self::$deleting[$id] = self::productOf($id);
}
}
public static function onAfterDelete(array $fields): void
{
$id = (int)($fields["ID"] ?? 0);
if (isset(self::$deleting[$id])) {
self::recalc(self::$deleting[$id]);
unset(self::$deleting[$id]);
}
}
public static function summary(int $productId): ?array
{
$catalogId = self::iblockId(self::CATALOG_CODE);
if ($productId <= 0 || $catalogId <= 0) {
return null;
}
$values = [];
foreach (["REVIEW_COUNT", "REVIEW_RATING"] as $code) {
$property = PropertyTable::getRow(["select" => ["ID"], "filter" => ["=IBLOCK_ID" => $catalogId, "=CODE" => $code]]);
$row = $property === null ? null : ElementPropertyTable::getRow([
"select" => ["VALUE"],
"filter" => ["=IBLOCK_ELEMENT_ID" => $productId, "=IBLOCK_PROPERTY_ID" => (int)$property["ID"]],
]);
$values[$code] = $row === null ? 0.0 : (float)$row["VALUE"];
}
return ["count" => (int)$values["REVIEW_COUNT"], "avg" => round($values["REVIEW_RATING"], 1)];
}
public static function items(int $productId, int $limit = 50): array
{
$reviewsId = self::iblockId(self::REVIEWS_CODE);
if ($productId <= 0 || $reviewsId <= 0) {
return [];
}
$items = [];
$rows = \CIBlockElement::GetList(
["ACTIVE_FROM" => "DESC", "ID" => "DESC"],
["IBLOCK_ID" => $reviewsId, "ACTIVE" => "Y", "PROPERTY_PRODUCT" => $productId],
false,
["nTopCount" => $limit],
["ID", "PREVIEW_TEXT", "ACTIVE_FROM", "DATE_CREATE", "PROPERTY_AUTHOR", "PROPERTY_RATING"]
);
while ($row = $rows->Fetch()) {
$rating = (int)$row["PROPERTY_RATING_VALUE"];
$author = trim((string)$row["PROPERTY_AUTHOR_VALUE"]);
$text = trim((string)preg_replace('/\s+/u', " ", strip_tags((string)$row["PREVIEW_TEXT"])));
if ($rating < 1 || $rating > 5 || $author === "" || $text === "") {
continue;
}
$items[] = [
"author" => $author,
"rating" => $rating,
"text" => $text,
"date" => date("Y-m-d", MakeTimeStamp((string)($row["ACTIVE_FROM"] ?: $row["DATE_CREATE"]))),
];
}
return $items;
}
public static function recalc(int $productId): void
{
$catalogId = self::iblockId(self::CATALOG_CODE);
if ($productId <= 0 || $catalogId <= 0) {
return;
}
$sum = 0;
$count = 0;
$rows = \CIBlockElement::GetList(
[],
["IBLOCK_ID" => self::iblockId(self::REVIEWS_CODE), "ACTIVE" => "Y", "PROPERTY_PRODUCT" => $productId],
false,
false,
["ID", "PROPERTY_RATING"]
);
while ($row = $rows->Fetch()) {
$rating = (int)$row["PROPERTY_RATING_VALUE"];
if ($rating >= 1 && $rating <= 5) {
$sum += $rating;
$count++;
}
}
\CIBlockElement::SetPropertyValuesEx($productId, $catalogId, [
"REVIEW_COUNT" => $count,
"REVIEW_RATING" => $count > 0 ? round($sum / $count, 1) : false,
]);
\CIBlock::clearIblockTagCache($catalogId);
}
private static function productOf(int $reviewId): int
{
$value = \CIBlockElement::GetProperty(self::iblockId(self::REVIEWS_CODE), $reviewId, [], ["CODE" => "PRODUCT"])->Fetch();
return (int)($value["VALUE"] ?? 0);
}
}
@@ -0,0 +1,105 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca\Catalog;
use Bitrix\Iblock\ElementPropertyTable;
use Bitrix\Iblock\ElementTable;
use Bitrix\Iblock\PropertyEnumerationTable;
use Bitrix\Iblock\PropertyTable;
use Bitrix\Main\Loader;
use Jinove\Vinoteca\Config;
use Jinove\Vinoteca\Cached;
final class SearchMeta
{
private const CACHE_TTL = 86400;
private const CACHE_DIR = "/jinove.vinoteca/search-meta-v2";
private const PROPERTIES = ["REGION", "COUNTRY"];
public static function get(array $ids): array
{
return array_intersect_key(self::all(), array_flip(array_map("intval", $ids)));
}
private static function all(): array
{
$catalogId = Config::iblockId("catalog");
return (array)Cached::remember(self::CACHE_DIR, "meta-" . $catalogId . "-" . LANGUAGE_ID, self::CACHE_TTL, ["iblock_id_" . $catalogId, "iblock_id_" . Config::iblockId("brands")], static fn(): array => self::collect($catalogId));
}
private static function collect(int $catalogId): array
{
if ($catalogId <= 0 || !Loader::includeModule("iblock")) {
return [];
}
$propertyCodes = [];
$rows = PropertyTable::getList(["select" => ["ID", "CODE"], "filter" => ["=IBLOCK_ID" => $catalogId, "=CODE" => self::PROPERTIES]]);
while ($row = $rows->fetch()) {
$propertyCodes[(int)$row["ID"]] = (string)$row["CODE"];
}
$enums = [];
if ($propertyCodes) {
$rows = PropertyEnumerationTable::getList(["select" => ["ID", "XML_ID", "VALUE"], "filter" => ["@PROPERTY_ID" => array_keys($propertyCodes)]]);
while ($row = $rows->fetch()) {
$enums[(int)$row["ID"]] = ["XML_ID" => (string)$row["XML_ID"], "VALUE" => (string)$row["VALUE"]];
}
}
$parts = [];
if ($propertyCodes) {
$rows = ElementPropertyTable::getList([
"select" => ["IBLOCK_ELEMENT_ID", "IBLOCK_PROPERTY_ID", "VALUE_ENUM"],
"filter" => ["@IBLOCK_PROPERTY_ID" => array_keys($propertyCodes), ">VALUE_ENUM" => 0],
]);
while ($row = $rows->fetch()) {
$enum = $enums[(int)$row["VALUE_ENUM"]] ?? null;
if ($enum !== null) {
$code = $propertyCodes[(int)$row["IBLOCK_PROPERTY_ID"]];
$parts[(int)$row["IBLOCK_ELEMENT_ID"]][$code] = EnumNames::name($code, $enum["XML_ID"], $enum["VALUE"]);
}
}
}
$brands = self::brands($catalogId);
$meta = [];
$rows = ElementTable::getList(["select" => ["ID", "NAME"], "filter" => ["=IBLOCK_ID" => $catalogId]]);
while ($row = $rows->fetch()) {
$id = (int)$row["ID"];
$meta[$id] = [
"NAME" => (string)$row["NAME"],
"META" => implode(", ", array_filter([$parts[$id]["REGION"] ?? "", $parts[$id]["COUNTRY"] ?? ""])),
"BRAND" => $brands[$id] ?? "",
];
}
return $meta;
}
private static function brands(int $catalogId): array
{
$property = PropertyTable::getRow(["select" => ["ID"], "filter" => ["=IBLOCK_ID" => $catalogId, "=CODE" => "BRAND"]]);
if ($property === null) {
return [];
}
$links = [];
$rows = ElementPropertyTable::getList([
"select" => ["IBLOCK_ELEMENT_ID", "VALUE"],
"filter" => ["=IBLOCK_PROPERTY_ID" => (int)$property["ID"]],
]);
while ($row = $rows->fetch()) {
if ((int)$row["VALUE"] > 0) {
$links[(int)$row["IBLOCK_ELEMENT_ID"]] = (int)$row["VALUE"];
}
}
if (!$links) {
return [];
}
$names = [];
$rows = ElementTable::getList(["select" => ["ID", "NAME"], "filter" => ["=ID" => array_values(array_unique($links))]]);
while ($row = $rows->fetch()) {
$names[(int)$row["ID"]] = (string)$row["NAME"];
}
return array_filter(array_map(static fn(int $brandId): string => $names[$brandId] ?? "", $links));
}
}
@@ -0,0 +1,89 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca\Catalog;
use Bitrix\Iblock\InheritedProperty\SectionValues;
use Bitrix\Main\Loader;
use Jinove\Vinoteca\Config;
use Jinove\Vinoteca\Cached;
class Sections
{
private const CACHE_TTL = 86400;
private const CACHE_DIR = "/jinove.vinoteca/sections";
private const BASE_LANGUAGE = "ru";
private const FIELDS = ["NAME", "DESCRIPTION", "META_TITLE", "META_DESCRIPTION", "PAGE_TITLE"];
public static function byCode(string $code): array
{
return self::all()[$code] ?? [];
}
public static function name(string $code, string $fallback = ""): string
{
return (string)(self::byCode($code)["NAME"] ?? "") ?: $fallback;
}
public static function menuLinks(): array
{
$links = [];
foreach (self::all() as $code => $section) {
if (!$section["ACTIVE"] || $section["DEPTH_LEVEL"] !== 1) {
continue;
}
$links[] = [$section["NAME"], SITE_DIR . "catalog/" . $code . "/", [], [], ""];
}
return $links;
}
public static function all(): array
{
$catalogId = Config::iblockId("catalog");
$language = LANGUAGE_ID;
return (array)Cached::remember(self::CACHE_DIR, "sections-" . $catalogId . "-" . $language, self::CACHE_TTL, ["iblock_id_" . $catalogId], static fn(): array => self::collect($catalogId, $language));
}
private static function collect(int $catalogId, string $language): array
{
if (!Loader::includeModule("iblock")) {
return [];
}
$suffix = "_" . strtoupper($language);
$select = ["ID", "CODE", "NAME", "DESCRIPTION", "ACTIVE", "DEPTH_LEVEL"];
if ($language !== self::BASE_LANGUAGE) {
foreach (self::FIELDS as $field) {
$select[] = "UF_" . $field . $suffix;
}
}
$sections = [];
$rows = \CIBlockSection::GetList(["SORT" => "ASC"], ["IBLOCK_ID" => $catalogId], false, $select);
while ($row = $rows->Fetch()) {
$seo = (new SectionValues($catalogId, (int)$row["ID"]))->getValues();
$base = [
"NAME" => (string)$row["NAME"],
"DESCRIPTION" => (string)$row["DESCRIPTION"],
"META_TITLE" => (string)($seo["SECTION_META_TITLE"] ?? ""),
"META_DESCRIPTION" => (string)($seo["SECTION_META_DESCRIPTION"] ?? ""),
"PAGE_TITLE" => (string)($seo["SECTION_PAGE_TITLE"] ?? ""),
];
if ($language !== self::BASE_LANGUAGE) {
foreach (self::FIELDS as $field) {
$value = trim((string)($row["UF_" . $field . $suffix] ?? ""));
if ($value !== "") {
$base[$field] = $value;
}
}
}
$sections[(string)$row["CODE"]] = [
"ID" => (int)$row["ID"],
"ACTIVE" => $row["ACTIVE"] === "Y",
"DEPTH_LEVEL" => (int)$row["DEPTH_LEVEL"],
] + $base;
}
return $sections;
}
}
@@ -0,0 +1,151 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca\Catalog;
class WineSchema
{
private const CONTEXT = "https://schema.org";
public static function card(array $in): array
{
$url = (string)$in["url"];
$store = ["@id" => (string)$in["host"] . "/#store"];
$images = [];
foreach ((array)$in["images"] as $index => $image) {
$node = [
"@type" => "ImageObject",
"@id" => $url . "#image-" . ($index + 1),
"url" => $image["src"],
"contentUrl" => $image["src"],
"caption" => $image["alt"],
"inLanguage" => $in["language"],
];
if ($image["width"] > 0 && $image["height"] > 0) {
$node["width"] = ["@type" => "QuantitativeValue", "value" => $image["width"], "unitCode" => "E37"];
$node["height"] = ["@type" => "QuantitativeValue", "value" => $image["height"], "unitCode" => "E37"];
}
$images[] = $node;
}
$product = [
"@type" => "Product",
"@id" => $url . "#product",
"name" => $in["name"],
"url" => $url,
];
if ($in["description"] !== "") {
$product["description"] = $in["description"];
}
if ($images) {
$product["image"] = $images;
}
if ($in["sku"] !== "") {
$product["sku"] = $in["sku"];
}
if ($in["category"] !== "") {
$product["category"] = $in["category"];
}
if ($in["country"] !== "") {
$product["countryOfOrigin"] = ["@type" => "Country", "name" => $in["country"]];
}
if ($in["vintage"] !== "") {
$product["productionDate"] = $in["vintage"];
}
if (!empty($in["brand"]["name"])) {
$brand = ["@type" => "Brand", "name" => $in["brand"]["name"]];
if ($in["brand"]["url"] !== "") {
$brand["@id"] = $in["brand"]["url"] . "#brand";
$brand["url"] = $in["brand"]["url"];
}
$product["brand"] = $brand;
}
$properties = [];
foreach ((array)$in["properties"] as $row) {
$node = ["@type" => "PropertyValue", "name" => $row["name"], "value" => $row["value"]];
if (!empty($row["unitCode"])) {
$node["unitCode"] = $row["unitCode"];
}
$properties[] = $node;
}
if ($properties) {
$product["additionalProperty"] = $properties;
}
if ($in["price"] > 0 && $in["currency"] !== "") {
$offer = [
"@type" => "Offer",
"@id" => $url . "#offer",
"url" => $url,
"price" => $in["price"],
"priceCurrency" => $in["currency"],
"availability" => $in["canBuy"] ? "https://schema.org/InStock" : "https://schema.org/OutOfStock",
"itemCondition" => "https://schema.org/NewCondition",
"seller" => $store,
];
if ($in["listPrice"] > $in["price"]) {
$offer["priceSpecification"] = [
"@type" => "UnitPriceSpecification",
"priceType" => "https://schema.org/ListPrice",
"price" => $in["listPrice"],
"priceCurrency" => $in["currency"],
];
}
$product["offers"] = $offer;
}
if ($in["reviewCount"] > 0 && $in["reviewRating"] > 0) {
$product["aggregateRating"] = [
"@type" => "AggregateRating",
"ratingValue" => $in["reviewRating"],
"reviewCount" => $in["reviewCount"],
"bestRating" => 5,
"worstRating" => 1,
];
}
$reviews = [];
foreach ((array)$in["reviews"] as $review) {
$reviews[] = [
"@type" => "Review",
"author" => ["@type" => "Person", "name" => $review["author"]],
"datePublished" => $review["date"],
"reviewRating" => ["@type" => "Rating", "ratingValue" => $review["rating"], "bestRating" => 5, "worstRating" => 1],
"reviewBody" => $review["text"],
"inLanguage" => $review["language"],
];
}
if ($reviews) {
$product["review"] = $reviews;
}
$related = [];
foreach ((array)$in["related"] as $item) {
$related[] = ["@type" => "Product", "@id" => $item["url"] . "#product", "name" => $item["name"], "url" => $item["url"]];
}
if ($related) {
$product["isRelatedTo"] = $related;
}
$page = [
"@type" => "ItemPage",
"@id" => $url . "#webpage",
"url" => $url,
"name" => $in["name"],
"description" => $in["pageDescription"],
"inLanguage" => $in["language"],
"mainEntity" => ["@id" => $url . "#product"],
"datePublished" => $in["created"],
"dateModified" => $in["modified"],
];
if ($images) {
$page["primaryImageOfPage"] = ["@id" => $images[0]["@id"]];
}
$translations = [];
foreach ((array)$in["translations"] as $language => $translationUrl) {
$translations[] = ["@type" => "ItemPage", "@id" => $translationUrl . "#webpage", "url" => $translationUrl, "inLanguage" => $language];
}
if ($translations) {
$page["workTranslation"] = $translations;
}
return ["@context" => self::CONTEXT, "@graph" => [$page, $product]];
}
}
@@ -0,0 +1,75 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca\Catalog;
use Bitrix\Iblock\ElementTable;
use Bitrix\Iblock\IblockTable;
use Bitrix\Main\Application;
use Bitrix\Main\Data\Cache;
use Bitrix\Main\Loader;
use Bitrix\Main\SystemException;
class WineStats
{
private const CACHE_TTL = 86400;
private const CACHE_DIR = "/jinove.vinoteca/winestats";
private ?int $activeCount = null;
public function __construct(
private readonly string $iblockType,
private readonly string $iblockCode,
) {
}
public function getActiveCount(): int
{
if ($this->activeCount !== null) {
return $this->activeCount;
}
$cache = Cache::createInstance();
$cacheId = "active-count-" . $this->iblockType . "-" . $this->iblockCode;
if ($cache->initCache(self::CACHE_TTL, $cacheId, self::CACHE_DIR)) {
return $this->activeCount = (int)$cache->getVars()["count"];
}
$cache->startDataCache();
$taggedCache = Application::getInstance()->getTaggedCache();
$taggedCache->startTagCache(self::CACHE_DIR);
try {
$iblockId = $this->getIblockId();
$count = ElementTable::getCount([
"=IBLOCK_ID" => $iblockId,
"=ACTIVE" => "Y",
]);
$taggedCache->registerTag("iblock_id_" . $iblockId);
} catch (\Throwable $e) {
$taggedCache->abortTagCache();
$cache->abortDataCache();
throw $e;
}
$taggedCache->endTagCache();
$cache->endDataCache(["count" => $count]);
return $this->activeCount = $count;
}
private function getIblockId(): int
{
if (!Loader::includeModule("iblock")) {
throw new SystemException("Module iblock is not installed");
}
$iblock = IblockTable::getRow([
"select" => ["ID"],
"filter" => ["=IBLOCK_TYPE_ID" => $this->iblockType, "=CODE" => $this->iblockCode],
]);
if ($iblock === null) {
throw new SystemException("Iblock " . $this->iblockType . "/" . $this->iblockCode . " not found");
}
return (int)$iblock["ID"];
}
}
@@ -0,0 +1,351 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca;
use Bitrix\Main\Application;
use Bitrix\Main\Context;
use Bitrix\Main\Engine\CurrentUser;
use Bitrix\Main\HttpRequest;
use Bitrix\Main\Loader;
use Bitrix\Main\Localization\Loc;
use Bitrix\Main\Security\Sign\Signer;
use Bitrix\Main\Type\DateTime;
use Bitrix\Main\Web\HttpClient;
use Bitrix\Main\Web\Json;
use Bitrix\Sale\Basket\RefreshFactory;
use Bitrix\Sale\BasketBase;
use Bitrix\Sale\BusinessValue;
use Bitrix\Sale\Delivery\Services\Manager as DeliveryManager;
use Bitrix\Sale\Internals\PaymentTable;
use Bitrix\Sale\Internals\PersonTypeTable;
use Bitrix\Sale\Order;
use Bitrix\Sale\Payment;
use Bitrix\Sale\PaySystem\BaseServiceHandler;
use Bitrix\Sale\PaySystem\Logger;
use Bitrix\Sale\PaySystem\Manager as PaySystemManager;
use Bitrix\Sale\PaySystem\Service;
Loc::loadMessages(__FILE__);
final class Checkout
{
private const PERSON_CODE = "BUYER";
private const DELIVERY_CODE = "pickup";
private const PROPERTIES = ["NAME", "PHONE", "EMAIL"];
private const PAYPAL_ACTION = "jinove_paypal";
private const YOOKASSA_ACTION = "yandexcheckout";
private const HALYK_ACTION = "jinove_halyk";
private const UNPAID_HOURS = 24;
private const UNPAID_REASON = "Online payment was not completed within 24 hours";
private const YOOKASSA_API = "https://api.yookassa.ru/v3/payments/";
private const TOKEN_SALT = "vino-order";
private const LOCK_SECONDS = 10;
public static function methods(): array
{
$methods = [];
if (!Loader::includeModule("sale")) {
return $methods;
}
$rows = PaySystemManager::getList(["filter" => ["=ACTIVE" => "Y", "=ENTITY_REGISTRY_TYPE" => "ORDER"], "order" => ["SORT" => "ASC", "ID" => "ASC"]]);
while ($row = $rows->fetch()) {
$code = self::methodCode((string)$row["ACTION_FILE"]);
if ($code === "") {
continue;
}
$methods[] = [
"id" => (int)$row["ID"],
"code" => $code,
"name" => (string)Loc::getMessage("VINO_PAY_" . strtoupper($code)),
"hint" => (string)Loc::getMessage("VINO_PAY_" . strtoupper($code) . "_HINT"),
];
}
return $methods;
}
public static function create(BasketBase $basket, array $contacts, int $paySystemId, string $consentProof): array
{
$methods = array_column(self::methods(), null, "id");
if (!isset($methods[$paySystemId])) {
return ["error" => "pay"];
}
$person = PersonTypeTable::getRow(["filter" => ["=CODE" => self::PERSON_CODE, "=ACTIVE" => "Y"], "select" => ["ID"]]);
$delivery = \Bitrix\Sale\Delivery\Services\Table::getRow(["filter" => ["=CODE" => self::DELIVERY_CODE, "=ACTIVE" => "Y"], "select" => ["ID"]]);
if ($person === null || $delivery === null) {
return ["error" => "shop"];
}
$basket->refresh(RefreshFactory::create(RefreshFactory::TYPE_FULL));
$items = $basket->getOrderableItems();
if ($items->isEmpty()) {
return ["error" => "empty"];
}
$siteId = Config::basketSiteId();
$userId = (int)CurrentUser::get()->getId();
$order = Order::create($siteId, $userId > 0 ? $userId : (int)\CSaleUser::GetAnonymousUserID());
$order->setPersonTypeId((int)$person["ID"]);
$order->setBasket($items);
$shipments = $order->getShipmentCollection();
$shipment = $shipments->createItem(DeliveryManager::getObjectById((int)$delivery["ID"]));
$shipment->setField("CURRENCY", $order->getCurrency());
$shipmentItems = $shipment->getShipmentItemCollection();
foreach ($order->getBasket() as $basketItem) {
$shipmentItems->createItem($basketItem)->setQuantity($basketItem->getQuantity());
}
$shipments->calculateDelivery();
$properties = $order->getPropertyCollection();
$proof = $properties->getItemByOrderPropertyCode("CONSENT_PROOF");
if ($proof === null) {
return ["error" => "shop"];
}
$proof->setValue($consentProof);
foreach (self::PROPERTIES as $code) {
$property = $properties->getItemByOrderPropertyCode($code);
if ($property !== null) {
$property->setValue((string)($contacts[strtolower($code)] ?? ""));
}
}
$comment = (string)($contacts["comment"] ?? "");
if ($comment !== "") {
$order->setField("USER_DESCRIPTION", $comment);
}
$payment = $order->getPaymentCollection()->createItem(PaySystemManager::getObjectById($paySystemId));
$order->doFinalAction(true);
$payment->setField("SUM", $order->getPrice());
$payment->setField("CURRENCY", $order->getCurrency());
$result = $order->save();
if (!$result->isSuccess()) {
return ["error" => "save", "messages" => $result->getErrorMessages()];
}
return [
"order" => $order,
"payment" => $order->getPaymentCollection()->current(),
"method" => $methods[$paySystemId],
];
}
public static function token(Order $order): string
{
return (new Signer())->getSignature($order->getId() . ":" . $order->getField("ACCOUNT_NUMBER"), self::TOKEN_SALT);
}
public static function find(int $orderId, string $hash): ?Order
{
if ($orderId <= 0 || $hash === "" || !Loader::includeModule("sale")) {
return null;
}
$order = Order::load($orderId);
if ($order === null || !hash_equals(self::token($order), $hash)) {
return null;
}
return $order;
}
public static function doneUrl(Order $order, string $dir, array $extra = []): string
{
return Config::host() . $dir . "personal/order/done/?" . http_build_query(["id" => $order->getId(), "hash" => self::token($order)] + $extra);
}
public static function startPayment(Order $order, string $dir): array
{
$payment = $order->getPaymentCollection()->current();
if ($payment === null || $payment->isPaid()) {
return ["url" => ""];
}
$service = $payment->getPaySystem();
$code = $service !== null ? self::methodCode((string)$service->getField("ACTION_FILE")) : "";
if ($code === "" || $code === "cash") {
return ["url" => ""];
}
if ((string)$payment->getField("PS_INVOICE_ID") !== "" && self::finishPayment($order, [])) {
return ["url" => self::doneUrl($order, $dir)];
}
$order = Order::load($order->getId());
$payment = $order->getPaymentCollection()->current();
$service = $payment->getPaySystem();
$returnUrl = self::doneUrl($order, $dir, ["payment" => $payment->getId()]);
if ($code === "yookassa") {
$service->getContext()->setUrl($returnUrl);
}
$request = new HttpRequest(
Context::getCurrent()->getServer(),
["return_url" => $returnUrl, "cancel_url" => self::doneUrl($order, $dir, ["payment" => $payment->getId(), "cancel" => "Y"])],
[],
[],
[]
);
$result = $service->initiatePay($payment, $request, BaseServiceHandler::STRING);
$widget = $result->getData()["widget"] ?? null;
if (!$result->isSuccess() || ($result->getPaymentUrl() === "" && !is_array($widget))) {
return ["url" => ""];
}
if (!$order->save()->isSuccess()) {
return ["url" => ""];
}
return ["url" => $result->getPaymentUrl(), "widget" => is_array($widget) ? $widget : null];
}
public static function finishPayment(Order $order, array $query): bool
{
$connection = Application::getConnection();
$key = "vino_pay_" . $order->getId();
if (!$connection->lock($key, self::LOCK_SECONDS)) {
return false;
}
try {
$fresh = Order::load($order->getId());
return $fresh !== null && self::verify($fresh, $query);
} finally {
$connection->unlock($key);
}
}
public static function methodOf(Order $order): string
{
$payment = $order->getPaymentCollection()->current();
$service = $payment !== null ? $payment->getPaySystem() : null;
return $service !== null ? self::methodCode((string)$service->getField("ACTION_FILE")) : "";
}
public static function cancelUnpaid(): string
{
if (!Loader::includeModule("sale")) {
return __METHOD__ . "();";
}
$online = [];
foreach (self::methods() as $method) {
if ($method["code"] !== "cash") {
$online[] = $method["id"];
}
}
if (!$online) {
return __METHOD__ . "();";
}
$border = new DateTime();
$border->add("-" . self::UNPAID_HOURS . " hours");
$rows = PaymentTable::getList([
"filter" => ["=PAID" => "N", "@PAY_SYSTEM_ID" => $online, "=ORDER.CANCELED" => "N", "<ORDER.DATE_INSERT" => $border],
"select" => ["ORDER_ID"],
"order" => ["ID" => "ASC"],
"limit" => 200,
]);
while ($row = $rows->fetch()) {
$order = Order::load((int)$row["ORDER_ID"]);
if ($order === null || $order->isPaid() || $order->isCanceled()) {
continue;
}
$payment = $order->getPaymentCollection()->current();
if ($payment !== null && (string)$payment->getField("PS_INVOICE_ID") !== "" && self::finishPayment($order, [])) {
continue;
}
$order = Order::load($order->getId());
$order->setField("CANCELED", "Y");
$order->setField("REASON_CANCELED", self::UNPAID_REASON);
$order->save();
}
return __METHOD__ . "();";
}
public static function consentProof(string $page): string
{
return "consent=Y; version=" . Consent::VERSION . "; policy=" . Consent::POLICY_VERSION . "; page=" . $page . "; at=" . new DateTime();
}
public static function dir(string $requested): string
{
foreach (Config::languages() as $language) {
if ((string)($language["dir"] ?? "") === $requested) {
return $requested;
}
}
return "/";
}
private static function verify(Order $order, array $query): bool
{
$payment = $order->getPaymentCollection()->current();
if ($payment === null) {
return false;
}
if ($payment->isPaid()) {
return true;
}
$service = $payment->getPaySystem();
$code = $service !== null ? self::methodCode((string)$service->getField("ACTION_FILE")) : "";
if ($code === "yookassa") {
return self::finishYookassa($order, $payment, $service);
}
$token = (string)($query["token"] ?? "");
if ($code === "paypal" && $token === "") {
$token = (string)$payment->getField("PS_INVOICE_ID");
}
if ($code !== "halyk" && ($code !== "paypal" || $token === "")) {
return false;
}
$request = new HttpRequest(Context::getCurrent()->getServer(), ["payment" => $payment->getId(), "token" => $token], [], [], []);
$result = $service->processRequest($request);
return $result->isSuccess() && Order::load($order->getId())->getPaymentCollection()->current()->isPaid();
}
private static function finishYookassa(Order $order, Payment $payment, Service $service): bool
{
$invoice = (string)$payment->getField("PS_INVOICE_ID");
if ($invoice === "") {
return false;
}
$consumer = "PAYSYSTEM_" . (int)$service->getField("ID");
$client = new HttpClient(["socketTimeout" => 10, "streamTimeout" => 10]);
$client->setHeader("Authorization", "Basic " . base64_encode(trim((string)BusinessValue::get("YANDEX_CHECKOUT_SHOP_ID", $consumer)) . ":" . trim((string)BusinessValue::get("YANDEX_CHECKOUT_SECRET_KEY", $consumer))));
$body = $client->get(self::YOOKASSA_API . rawurlencode($invoice));
if ($body === false || $client->getStatus() !== 200) {
Logger::addError(__METHOD__ . ": status request failed, HTTP " . $client->getStatus());
return false;
}
try {
$data = Json::decode((string)$body);
} catch (\Throwable $exception) {
return false;
}
$amount = (float)($data["amount"]["value"] ?? 0);
$currency = (string)($data["amount"]["currency"] ?? "");
if (($data["status"] ?? "") !== "succeeded" || empty($data["paid"]) || $currency !== $payment->getCurrency() || abs($amount - (float)$payment->getSum()) > 0.01) {
return false;
}
$paid = $payment->setPaid("Y");
if (!$paid->isSuccess()) {
return false;
}
$payment->setFields(["PS_STATUS" => "Y", "PS_STATUS_CODE" => "succeeded", "PS_SUM" => $amount, "PS_CURRENCY" => $currency, "PS_RESPONSE_DATE" => new DateTime()]);
return $order->save()->isSuccess();
}
private static function methodCode(string $action): string
{
if ($action === self::PAYPAL_ACTION) {
return "paypal";
}
if ($action === self::YOOKASSA_ACTION) {
return "yookassa";
}
if ($action === self::HALYK_ACTION) {
return "halyk";
}
return $action === "cashondelivery" ? "cash" : "";
}
}
@@ -0,0 +1,58 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca;
use Bitrix\Main\Config\Configuration;
use Bitrix\Main\SystemException;
final class Config
{
private const MODULE_ID = "jinove.vinoteca";
public static function basketSiteId(): string
{
$siteId = (string)(self::get("basket")["siteId"] ?? "");
if ($siteId === "") {
throw new SystemException("Basket site is not configured in " . self::MODULE_ID . "/.settings.php");
}
return $siteId;
}
public static function host(): string
{
return (string)(self::get("site")["host"] ?? "");
}
public static function ageExitUrl(): string
{
return (string)(self::get("site")["ageExitUrl"] ?? "");
}
public static function figmaUrl(): string
{
return (string)(self::get("site")["figmaUrl"] ?? "");
}
public static function languages(): array
{
return (array)(self::get("site")["languages"] ?? []);
}
public static function contacts(): array
{
return self::get("contacts");
}
public static function iblockId(string $code): int
{
return (int)(self::get("site")["iblocks"][$code] ?? 0);
}
private static function get(string $name): array
{
return (array)Configuration::getInstance(self::MODULE_ID)->get($name);
}
}
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca;
final class Consent
{
public const VERSION = "09.10.2026";
public const POLICY_VERSION = "22.10.2026";
public static function timestamp(string $version): int
{
$date = \DateTimeImmutable::createFromFormat("d.m.Y|", $version);
return $date ? $date->getTimestamp() : 0;
}
}
@@ -0,0 +1,82 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca\Controller;
use Bitrix\Main\Application;
use Bitrix\Main\Engine\ActionFilter\Csrf;
use Bitrix\Main\Engine\ActionFilter\HttpMethod;
use Bitrix\Main\Engine\Controller;
use Bitrix\Main\Error;
use Bitrix\Main\UserTable;
use Jinove\Vinoteca\Controller\Filter\FormGuard;
use Jinove\Vinoteca\Redirect;
class Auth extends Controller
{
private const MAX_FAILS = 5;
private const BLOCK_SECONDS = 600;
public function configureActions(): array
{
return [
"login" => [
"prefilters" => [new HttpMethod([HttpMethod::METHOD_POST]), new Csrf(), new FormGuard(FormGuard::TIMING_ELAPSED)],
],
];
}
public function loginAction(
string $email,
string $password,
string $remember = "",
string $consent = "",
string $back = "",
string $lang = "en",
string $website = "",
int $elapsed = 0,
string $altcha = ""
): ?array {
$lang = Redirect::language($lang);
if ($website !== "") {
return ["ok" => true, "redirect" => Redirect::home($lang)];
}
$session = Application::getInstance()->getSession();
if ((int)($session->get("vino_login_block") ?? 0) > time()) {
$this->addError(new Error("Too many attempts", "too_often"));
return null;
}
$email = mb_strtolower(trim($email));
if ($consent !== "1" || !check_email($email) || $password === "" || mb_strlen($password) > 200) {
$this->addError(new Error("Invalid credentials", "invalid"));
return null;
}
$user = UserTable::getRow([
"select" => ["LOGIN"],
"filter" => ["=EMAIL" => $email, "=ACTIVE" => "Y"],
]);
$logged = false;
if ($user !== null) {
global $USER;
$logged = $USER->Login((string)$user["LOGIN"], $password, $remember === "1" ? "Y" : "N") === true;
}
if (!$logged) {
$fails = (int)($session->get("vino_login_fails") ?? 0) + 1;
if ($fails >= self::MAX_FAILS) {
$session->set("vino_login_block", time() + self::BLOCK_SECONDS);
$fails = 0;
}
$session->set("vino_login_fails", $fails);
$this->addError(new Error("Invalid credentials", "invalid"));
return null;
}
$session->remove("vino_login_fails");
$session->remove("vino_login_block");
return ["ok" => true, "redirect" => Redirect::back($back, $lang)];
}
}
@@ -0,0 +1,168 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca\Controller;
use Bitrix\Main\Engine\ActionFilter\Csrf;
use Bitrix\Main\Engine\ActionFilter\HttpMethod;
use Bitrix\Main\Engine\Controller;
use Bitrix\Main\Error;
use Bitrix\Sale\BasketBase;
use Jinove\Vinoteca\Cart;
class Basket extends Controller
{
private const COUPON_MAX_LENGTH = 64;
public function configureActions(): array
{
$read = ["prefilters" => [new HttpMethod([HttpMethod::METHOD_GET])]];
$write = ["prefilters" => [new HttpMethod([HttpMethod::METHOD_POST]), new Csrf()]];
return [
"state" => $read,
"cart" => $read,
"set" => $write,
"update" => $write,
"clear" => $write,
"coupon" => $write,
"couponRemove" => $write,
"addShared" => $write,
];
}
public function addSharedAction(string $code): ?array
{
$items = Cart::parseShare(trim($code));
if (!$items) {
$this->addError(new Error("Wrong share code", "share"));
return null;
}
$basket = $this->loadBasket();
if ($basket === null) {
return null;
}
$ok = Cart::addMany($basket, $items);
$basket = $this->loadBasket();
return $basket === null ? null : ["ok" => $ok] + Cart::state($basket);
}
public function stateAction(): ?array
{
$basket = $this->loadBasket();
return $basket === null ? null : ["ok" => true] + Cart::state($basket);
}
public function setAction(int $id, int $qty): ?array
{
$basket = $this->loadBasket();
if ($basket === null || !$this->validId($id)) {
return null;
}
$ok = Cart::setQuantity($basket, $id, $qty);
$basket = $this->loadBasket();
return $basket === null ? null : ["ok" => $ok] + Cart::state($basket);
}
public function cartAction(): ?array
{
$basket = $this->loadBasket();
return $basket === null ? null : $this->full($basket, true, true);
}
public function updateAction(int $id, int $qty): ?array
{
$basket = $this->loadBasket();
if ($basket === null || !$this->validId($id)) {
return null;
}
$ok = Cart::setQuantity($basket, $id, $qty);
$basket = $this->loadBasket();
return $basket === null ? null : $this->full($basket, $ok);
}
public function clearAction(): ?array
{
$basket = $this->loadBasket();
if ($basket === null) {
return null;
}
$ok = Cart::clear($basket);
$basket = $this->loadBasket();
return $basket === null ? null : $this->full($basket, $ok);
}
public function couponAction(string $code): ?array
{
$code = trim($code);
if ($code === "" || mb_strlen($code) > self::COUPON_MAX_LENGTH) {
$this->addError(new Error("Wrong coupon", "coupon"));
return null;
}
$basket = $this->loadBasket();
if ($basket === null) {
return null;
}
if (!Cart::addCoupon($code)) {
Cart::removeCoupon($code);
$this->addError(new Error("Coupon is not applicable", "coupon"));
return null;
}
$result = $this->full($basket, true);
foreach ($result["cart"]["coupons"] as $coupon) {
if (mb_strtolower($coupon["code"]) === mb_strtolower($code) && $coupon["applied"]) {
return $result;
}
}
Cart::removeCoupon($code);
$this->addError(new Error("Coupon is not applicable", "coupon"));
return null;
}
public function couponRemoveAction(string $code): ?array
{
$basket = $this->loadBasket();
if ($basket === null) {
return null;
}
Cart::removeCoupon(trim($code));
return $this->full($basket, true);
}
private function full(BasketBase $basket, bool $ok, bool $refresh = false): array
{
return ["ok" => $ok, "cart" => Cart::view($basket, $refresh), "state" => Cart::state($basket)];
}
private function loadBasket(): ?BasketBase
{
$basket = Cart::load();
if ($basket === null) {
$this->addError(new Error("Modules sale and catalog are required"));
}
return $basket;
}
private function validId(int $id): bool
{
if ($id > 0) {
return true;
}
$this->addError(new Error("Wrong product id"));
return false;
}
}
@@ -0,0 +1,94 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca\Controller;
use Bitrix\Main\Engine\ActionFilter\HttpMethod;
use Bitrix\Main\Engine\Controller;
use Bitrix\Main\Engine\Response\Component;
use Bitrix\Main\Error;
use Jinove\Vinoteca\Catalog\Listing;
class Catalog extends Controller
{
public function configureActions(): array
{
return [
"listing" => [
"prefilters" => [new HttpMethod([HttpMethod::METHOD_GET])],
],
"filter" => [
"prefilters" => [new HttpMethod([HttpMethod::METHOD_GET])],
],
];
}
public function listingAction(string $path): ?Component
{
$route = Listing::parsePath($path);
if ($route === null) {
$this->addError(new Error("Wrong path"));
return null;
}
if (!Listing::filterPathIsValid($route["SECTION_CODE"], $route["FILTER_PATH"])) {
$this->addError(new Error("Wrong filter"));
return null;
}
return new Component(
"jinove:catalog.listing",
"",
[
"SECTION_CODE" => $route["SECTION_CODE"],
"FILTER_PATH" => $route["FILTER_PATH"],
"AJAX" => "Y",
],
[],
static function (): array {
global $APPLICATION;
return ["title" => (string)($APPLICATION->GetPageProperty("title") ?: $APPLICATION->GetTitle())];
}
);
}
public function filterAction(string $section): ?array
{
$route = Listing::parsePath(Listing::sectionPath($section));
if ($route === null) {
$this->addError(new Error("Wrong section"));
return null;
}
global $APPLICATION;
ob_start();
$result = $APPLICATION->IncludeComponent(
"bitrix:catalog.smart.filter",
"",
Listing::filterParams($route["SECTION_CODE"], ""),
null,
[],
true
);
ob_end_clean();
$disabled = [];
foreach ((array)($result["ITEMS"] ?? []) as $item) {
if (!empty($item["PRICE"])) {
continue;
}
foreach ((array)($item["VALUES"] ?? []) as $value) {
$disabled[$value["CONTROL_NAME"]] = !empty($value["DISABLED"]);
}
}
return [
"url" => (string)($result["JS_FILTER_PARAMS"]["SEF_SET_FILTER_URL"] ?? Listing::sectionPath($route["SECTION_CODE"])),
"disabled" => $disabled,
];
}
}
@@ -0,0 +1,118 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca\Controller;
use Bitrix\Iblock\ElementTable;
use Bitrix\Iblock\SectionElementTable;
use Bitrix\Main\Engine\ActionFilter\Csrf;
use Bitrix\Main\Engine\ActionFilter\HttpMethod;
use Bitrix\Main\Engine\Controller;
use Bitrix\Main\Error;
use Bitrix\Main\Loader;
use Jinove\Vinoteca\Catalog\Comparison;
use Jinove\Vinoteca\Config;
class Compare extends Controller
{
public function configureActions(): array
{
return [
"state" => [
"prefilters" => [new HttpMethod([HttpMethod::METHOD_GET])],
],
"set" => [
"prefilters" => [new HttpMethod([HttpMethod::METHOD_POST]), new Csrf()],
],
"clear" => [
"prefilters" => [new HttpMethod([HttpMethod::METHOD_POST]), new Csrf()],
],
];
}
public function stateAction(): array
{
return $this->describe(Comparison::prune(), false);
}
public function clearAction(): array
{
Comparison::write([]);
return $this->describe([], false);
}
public function setAction(int $id, string $on): ?array
{
$items = Comparison::read();
if ($on !== "Y") {
unset($items[$id]);
Comparison::write($items);
return $this->describe($items, false);
}
if (isset($items[$id])) {
return $this->describe($items, false);
}
if (count($items) >= Comparison::MAX) {
return $this->describe($items, true);
}
$item = $this->loadItem($id);
if ($item === null) {
$this->addError(new Error("Wrong product id"));
return null;
}
$items[$id] = $item;
Comparison::write($items);
return $this->describe($items, false);
}
private function describe(array $items, bool $full): array
{
return ["items" => array_map("intval", array_keys($items)), "full" => $full];
}
private function loadItem(int $id): ?array
{
if ($id <= 0 || !Loader::includeModule("iblock")) {
return null;
}
$element = ElementTable::getRow([
"select" => ["ID", "IBLOCK_ID", "IBLOCK_SECTION_ID", "NAME", "CODE", "SECTION_CODE" => "IBLOCK_SECTION.CODE", "DETAIL_PAGE_URL" => "IBLOCK.DETAIL_PAGE_URL"],
"filter" => ["=ID" => $id, "=IBLOCK_ID" => Config::iblockId("catalog"), "=ACTIVE" => "Y"],
]);
if ($element === null) {
return null;
}
$url = \CIBlock::ReplaceDetailUrl((string)$element["DETAIL_PAGE_URL"], [
"ID" => $element["ID"],
"CODE" => $element["CODE"],
"IBLOCK_ID" => $element["IBLOCK_ID"],
"IBLOCK_SECTION_ID" => $element["IBLOCK_SECTION_ID"],
"SECTION_CODE" => $element["SECTION_CODE"],
], false, "E");
$sections = array_map("intval", array_column(SectionElementTable::getList([
"select" => ["IBLOCK_SECTION_ID"],
"filter" => ["=IBLOCK_ELEMENT_ID" => $id, "=ADDITIONAL_PROPERTY_ID" => null],
])->fetchAll(), "IBLOCK_SECTION_ID"));
return [
"ID" => (int)$element["ID"],
"~ID" => (int)$element["ID"],
"IBLOCK_ID" => (int)$element["IBLOCK_ID"],
"~IBLOCK_ID" => (int)$element["IBLOCK_ID"],
"IBLOCK_SECTION_ID" => (int)$element["IBLOCK_SECTION_ID"],
"~IBLOCK_SECTION_ID" => (int)$element["IBLOCK_SECTION_ID"],
"NAME" => htmlspecialcharsbx($element["NAME"]),
"~NAME" => $element["NAME"],
"DETAIL_PAGE_URL" => htmlspecialcharsbx($url),
"~DETAIL_PAGE_URL" => $url,
"SECTIONS_LIST" => array_combine($sections, $sections),
"PARENT_ID" => (int)$element["ID"],
];
}
}
@@ -0,0 +1,94 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca\Controller;
use Bitrix\Iblock\ElementTable;
use Bitrix\Main\Engine\ActionFilter\Csrf;
use Bitrix\Main\Engine\ActionFilter\HttpMethod;
use Bitrix\Main\Engine\Controller;
use Bitrix\Main\Error;
use Bitrix\Main\DB\SqlQueryException;
use Bitrix\Main\Loader;
use Bitrix\Sale\Fuser;
use Jinove\Vinoteca\Catalog\FavoriteTable;
class Favorite extends Controller
{
public function configureActions(): array
{
return [
"state" => [
"prefilters" => [new HttpMethod([HttpMethod::METHOD_GET])],
],
"set" => [
"prefilters" => [new HttpMethod([HttpMethod::METHOD_POST]), new Csrf()],
],
];
}
public function stateAction(): ?array
{
if (!$this->loadModules()) {
return null;
}
return ["items" => FavoriteTable::productIds((int)Fuser::getId(true))];
}
public function setAction(int $id, string $on): ?array
{
if (!$this->loadModules()) {
return null;
}
if ($on === "Y" && !$this->isProduct($id)) {
$this->addError(new Error("Wrong product id"));
return null;
}
$fuserId = (int)Fuser::getId();
$row = FavoriteTable::getRow([
"select" => ["ID"],
"filter" => ["=FUSER_ID" => $fuserId, "=PRODUCT_ID" => $id],
]);
$result = null;
if ($on === "Y" && !$row) {
try {
$result = FavoriteTable::add(["FUSER_ID" => $fuserId, "PRODUCT_ID" => $id]);
} catch (SqlQueryException $exception) {
$result = null;
}
} elseif ($on !== "Y" && $row) {
$result = FavoriteTable::delete($row["ID"]);
}
if ($result !== null && !$result->isSuccess()) {
$this->addErrors($result->getErrors());
return null;
}
return ["items" => FavoriteTable::productIds($fuserId)];
}
private function loadModules(): bool
{
if (!Loader::includeModule("sale") || !Loader::includeModule("iblock")) {
$this->addError(new Error("Modules sale and iblock are required"));
return false;
}
return true;
}
private function isProduct(int $id): bool
{
return $id > 0 && ElementTable::getCount([
"=ID" => $id,
"=IBLOCK_ID" => VINO_CATALOG_IBLOCK,
"=ACTIVE" => "Y",
]) > 0;
}
}
@@ -0,0 +1,66 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca\Controller\Filter;
use Bitrix\Main\Engine\ActionFilter\Base;
use Bitrix\Main\Error;
use Bitrix\Main\Event;
use Bitrix\Main\EventResult;
use Jinove\Vinoteca\Altcha;
use Jinove\Vinoteca\Origin;
final class FormGuard extends Base
{
public const TIMING_NONE = "";
public const TIMING_ELAPSED = "elapsed";
public const TIMING_STARTED = "started";
public const MIN_FILL_MS = 1500;
public function __construct(
private readonly string $timing = self::TIMING_NONE,
private readonly int $minFillMs = self::MIN_FILL_MS,
private readonly bool $altcha = true
) {
parent::__construct();
}
public static function startedTooEarly(int $startedMs, int $minFillMs): bool
{
return $startedMs <= 0 || (int)(microtime(true) * 1000) - $startedMs < $minFillMs;
}
public function onBeforeAction(Event $event)
{
try {
$arguments = $this->getAction()->getArguments();
} catch (\Throwable) {
return null;
}
if ((string)($arguments["website"] ?? "") !== "") {
return null;
}
if ($this->timing === self::TIMING_STARTED && self::startedTooEarly((int)($arguments["started"] ?? 0), $this->minFillMs)) {
return null;
}
if ($this->timing === self::TIMING_ELAPSED && (int)($arguments["elapsed"] ?? 0) < $this->minFillMs) {
return $this->reject("Too fast", "retry");
}
if (!Origin::allowed($this->getAction()->getController()->getRequest())) {
return $this->reject("Wrong origin", "origin");
}
if ($this->altcha && !Altcha::verify((string)($arguments["altcha"] ?? ""))) {
return $this->reject("Verification failed", "altcha");
}
return null;
}
private function reject(string $message, string $code): EventResult
{
$this->addError(new Error($message, $code));
return new EventResult(EventResult::ERROR, null, null, $this);
}
}
@@ -0,0 +1,208 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca\Controller;
use Bitrix\Main\Application;
use Bitrix\Main\Engine\ActionFilter\Csrf;
use Bitrix\Main\Engine\ActionFilter\HttpMethod;
use Bitrix\Main\Engine\Controller;
use Bitrix\Main\Engine\Response\Json;
use Bitrix\Main\Error;
use Bitrix\Main\Loader;
use Bitrix\Main\Mail\Event;
use Bitrix\Main\Type\DateTime;
use Jinove\Vinoteca\Altcha;
use Jinove\Vinoteca\Config;
use Jinove\Vinoteca\Consent;
use Jinove\Vinoteca\Controller\Filter\FormGuard;
use Jinove\Vinoteca\Phone;
class Lead extends Controller
{
private const QUESTIONS_CODE = "sommelier_questions";
private const SUBSCRIBERS_CODE = "newsletter_subscribers";
private const SUBSCRIBE_RETRY_SECONDS = 60;
public function configureActions(): array
{
return [
"challenge" => [
"prefilters" => [new HttpMethod([HttpMethod::METHOD_GET])],
],
"question" => [
"prefilters" => [new HttpMethod([HttpMethod::METHOD_POST]), new Csrf(), new FormGuard()],
],
"subscribe" => [
"prefilters" => [new HttpMethod([HttpMethod::METHOD_POST]), new Csrf(), new FormGuard()],
],
];
}
public function challengeAction(): ?Json
{
$challenge = Altcha::challenge();
if ($challenge === null) {
$this->addError(new Error("Challenge is not available", "altcha"));
return null;
}
$response = new Json($challenge);
$response->addHeader("Cache-Control", "no-store");
return $response;
}
public function questionAction(string $name, string $phone, string $message, string $consent = "", string $website = "", string $altcha = "", string $page = ""): ?array
{
if ($website !== "") {
return ["ok" => true];
}
$name = trim((string)preg_replace('/\s+/u', " ", $name));
$message = trim($message);
$phone = Phone::format($phone);
if ($consent === "" || $name === "" || $message === "" || $phone === "" || mb_strlen($name) > 100 || mb_strlen($message) > 2000) {
$this->addError(new Error("Invalid fields", "fields"));
return null;
}
$pageUrl = $this->pageUrl($page);
$consentUrl = $this->siteUrl() . "consent/";
$sentAt = (string)new DateTime();
$leadId = $this->save(self::QUESTIONS_CODE, $name . ", " . $phone, $message, [
"PERSON_NAME" => $name,
"PHONE" => $phone,
"LANG" => LANGUAGE_ID,
"PAGE" => $pageUrl,
"CONSENT" => "Y",
"CONSENT_VERSION" => Consent::VERSION,
"CONSENT_URL" => $consentUrl,
"SENT_AT" => $sentAt,
], $sentAt);
if ($leadId <= 0) {
$this->addError(new Error("Save failed", "save"));
return null;
}
Event::send([
"EVENT_NAME" => "VINO_SOMMELIER_QUESTION",
"LID" => SITE_ID,
"C_FIELDS" => [
"LEAD_ID" => $leadId,
"NAME" => $name,
"PHONE" => $phone,
"MESSAGE" => $message,
"PAGE" => $pageUrl,
"SENT_AT" => $sentAt,
"CONSENT_VERSION" => Consent::VERSION,
"CONSENT_URL" => $consentUrl,
],
]);
return ["ok" => true];
}
public function subscribeAction(string $email, string $consent = "", string $website = "", string $altcha = "", string $page = ""): ?array
{
if ($website !== "") {
return ["ok" => true];
}
$email = mb_strtolower(trim($email));
if (!check_email($email) || mb_strlen($email) > 254) {
$this->addError(new Error("Invalid e-mail", "email"));
return null;
}
if ($consent === "") {
$this->addError(new Error("Consent is required", "consent"));
return null;
}
$session = Application::getInstance()->getSession();
if (time() - (int)$session->get("vino_subscribe_last") < self::SUBSCRIBE_RETRY_SECONDS) {
return ["ok" => true];
}
$session->set("vino_subscribe_last", time());
if ($this->exists(self::SUBSCRIBERS_CODE, $email)) {
return ["ok" => true];
}
$sentAt = (string)new DateTime();
$consentUrl = $this->siteUrl() . "consent/";
$id = $this->save(self::SUBSCRIBERS_CODE, $email, "", [
"LANG" => LANGUAGE_ID,
"PAGE" => $this->pageUrl($page),
"CONSENT" => "Y",
"CONSENT_VERSION" => Consent::VERSION,
"CONSENT_URL" => $consentUrl,
"SENT_AT" => $sentAt,
], $sentAt);
if ($id <= 0) {
$this->addError(new Error("Save failed", "save"));
return null;
}
Event::send([
"EVENT_NAME" => "VINO_SUBSCRIBE",
"LID" => SITE_ID,
"C_FIELDS" => [
"EMAIL" => $email,
"CONSENT_VERSION" => Consent::VERSION,
"CONSENT_URL" => $consentUrl,
],
]);
return ["ok" => true];
}
private function iblockId(string $code): int
{
if (!Loader::includeModule("iblock")) {
return 0;
}
$iblock = \CIBlock::GetList([], ["CODE" => $code, "CHECK_PERMISSIONS" => "N"])->Fetch();
return $iblock ? (int)$iblock["ID"] : 0;
}
private function exists(string $code, string $name): bool
{
$iblockId = $this->iblockId($code);
if ($iblockId <= 0) {
return false;
}
return (bool)\CIBlockElement::GetList([], ["IBLOCK_ID" => $iblockId, "=NAME" => $name], false, ["nTopCount" => 1], ["ID"])->Fetch();
}
private function save(string $code, string $name, string $text, array $properties, string $sentAt): int
{
$iblockId = $this->iblockId($code);
if ($iblockId <= 0) {
return 0;
}
$element = new \CIBlockElement();
return (int)$element->Add([
"IBLOCK_ID" => $iblockId,
"NAME" => $name,
"ACTIVE" => "Y",
"DATE_ACTIVE_FROM" => $sentAt,
"DETAIL_TEXT" => $text,
"DETAIL_TEXT_TYPE" => "text",
"PROPERTY_VALUES" => $properties,
], false, false, false);
}
private function siteUrl(): string
{
return Config::host() . SITE_DIR;
}
private function pageUrl(string $page): string
{
$path = (string)parse_url($page, PHP_URL_PATH);
return Config::host() . ($path !== "" && str_starts_with($path, "/") ? $path : SITE_DIR);
}
}
@@ -0,0 +1,42 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca\Controller;
use Bitrix\Main\Engine\ActionFilter\HttpMethod;
use Bitrix\Main\Engine\Controller;
use Bitrix\Main\Engine\Response\Component;
use Bitrix\Main\Error;
use Jinove\Vinoteca\News as NewsList;
class News extends Controller
{
public function configureActions(): array
{
return [
"page" => [
"prefilters" => [new HttpMethod([HttpMethod::METHOD_GET])],
],
];
}
public function pageAction(): ?Component
{
$page = (string)$this->getRequest()->getQuery("PAGEN_1");
if (!ctype_digit($page) || (int)$page < 1 || (int)$page > NewsList::pageCount()) {
$this->addError(new Error("Wrong page"));
return null;
}
$meta = NewsList::pageMeta((int)$page);
return new Component(
"bitrix:news.list",
NewsList::LIST_TEMPLATE,
NewsList::listParams(true),
[],
static fn(): array => ["title" => $meta["title"]]
);
}
}
@@ -0,0 +1,97 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca\Controller;
use Bitrix\Main\Application;
use Bitrix\Main\Engine\ActionFilter\Csrf;
use Bitrix\Main\Engine\ActionFilter\HttpMethod;
use Bitrix\Main\Engine\Controller;
use Bitrix\Main\Error;
use Bitrix\Sale\DiscountCouponsManager;
use Jinove\Vinoteca\Cart;
use Jinove\Vinoteca\Checkout;
use Jinove\Vinoteca\Controller\Filter\FormGuard;
use Jinove\Vinoteca\Phone;
class Order extends Controller
{
private const RETRY_SECONDS = 20;
public function configureActions(): array
{
return [
"create" => ["prefilters" => [new HttpMethod([HttpMethod::METHOD_POST]), new Csrf(), new FormGuard()]],
"pay" => ["prefilters" => [new HttpMethod([HttpMethod::METHOD_POST]), new Csrf(), new FormGuard(FormGuard::TIMING_NONE, FormGuard::MIN_FILL_MS, false)]],
];
}
public function createAction(string $name, string $phone, string $email, string $pay, string $consent = "", string $comment = "", string $website = "", string $altcha = "", string $page = "", string $base = "/"): ?array
{
if ($website !== "") {
return ["ok" => true, "redirect" => ""];
}
$name = trim((string)preg_replace('/\s+/u', " ", $name));
$email = mb_strtolower(trim($email));
$comment = trim($comment);
$phone = Phone::format($phone);
if ($consent !== "Y" || preg_match('/^\/[\w\-\/]{0,198}$/', $page) !== 1 || mb_strlen($name) < 2 || mb_strlen($name) > 100 || $phone === "" || !check_email($email) || mb_strlen($email) > 254 || mb_strlen($comment) > 500 || (int)$pay <= 0) {
return $this->fail("Invalid fields", "fields");
}
$session = Application::getInstance()->getSession();
if (time() - (int)$session->get("vino_order_last") < self::RETRY_SECONDS) {
return $this->fail("Too many orders", "rate");
}
$session->set("vino_order_last", time());
$basket = Cart::load();
if ($basket === null) {
$session->set("vino_order_last", 0);
return $this->fail("Cart is unavailable", "cart");
}
DiscountCouponsManager::init();
$created = Checkout::create($basket, ["name" => $name, "phone" => $phone, "email" => $email, "comment" => $comment], (int)$pay, Checkout::consentProof($page));
if (isset($created["error"])) {
$session->set("vino_order_last", 0);
return $this->fail("Order was not created", (string)$created["error"]);
}
$dir = Checkout::dir($base);
$order = $created["order"];
$redirect = Checkout::doneUrl($order, $dir);
if ($created["method"]["code"] === "halyk") {
$redirect = Checkout::doneUrl($order, $dir, ["autopay" => "Y"]);
} elseif ($created["method"]["code"] !== "cash") {
$started = Checkout::startPayment($order, $dir);
$redirect = $started["url"] !== "" ? $started["url"] : Checkout::doneUrl($order, $dir, ["pay" => "failed"]);
}
return ["ok" => true, "redirect" => $redirect];
}
public function payAction(int $id, string $hash, string $base = "/"): ?array
{
$order = Checkout::find($id, $hash);
if ($order === null || $order->isCanceled()) {
return $this->fail("Order not found", "order");
}
$dir = Checkout::dir($base);
$started = Checkout::startPayment($order, $dir);
if (is_array($started["widget"] ?? null)) {
return ["ok" => true, "widget" => $started["widget"]];
}
if ($started["url"] === "") {
return $this->fail("Payment is unavailable", "pay");
}
return ["ok" => true, "redirect" => $started["url"]];
}
private function fail(string $message, string $code): ?array
{
$this->addError(new Error($message, $code));
return null;
}
}
@@ -0,0 +1,125 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca\Controller;
use Bitrix\Main\Application;
use Bitrix\Main\Data\Cache;
use Bitrix\Main\Engine\ActionFilter\Csrf;
use Bitrix\Main\Engine\ActionFilter\HttpMethod;
use Bitrix\Main\Engine\Controller;
use Bitrix\Main\Error;
use Bitrix\Main\UserTable;
use Jinove\Vinoteca\Controller\Filter\FormGuard;
class Password extends Controller
{
private const MAX_PER_WINDOW = 6;
private const WINDOW_SECONDS = 600;
private const MAIL_PAUSE_SECONDS = 60;
private const PASSWORD_MIN = 8;
private const PASSWORD_MAX = 200;
private const RESPONSE_MS = 600;
private const EVENT = "USER_PASS_REQUEST";
public function configureActions(): array
{
$filters = ["prefilters" => [new HttpMethod([HttpMethod::METHOD_POST]), new Csrf(), new FormGuard(FormGuard::TIMING_ELAPSED)]];
return ["request" => $filters, "reset" => $filters];
}
public function requestAction(string $email, string $website = "", int $elapsed = 0, string $altcha = ""): ?array
{
$started = microtime(true);
if ($website !== "") {
return ["ok" => true];
}
if (!$this->limit("vino_password_request_log")) {
return null;
}
$email = mb_strtolower(trim($email));
if (!check_email($email) || mb_strlen($email) > 254) {
$this->addError(new Error("Invalid e-mail", "email"));
return null;
}
$row = UserTable::getRow([
"select" => ["ID"],
"filter" => ["=EMAIL" => $email, "=ACTIVE" => "Y"],
]);
if ($row !== null && $this->mayMail((int)$row["ID"])) {
\CUser::SendUserInfo((int)$row["ID"], SITE_ID, "", false, self::EVENT);
}
$left = self::RESPONSE_MS * 1000 - (int)((microtime(true) - $started) * 1000000);
if ($left > 0) {
usleep($left);
}
return ["ok" => true];
}
public function resetAction(string $login, string $checkword, string $password, string $website = "", int $elapsed = 0, string $altcha = ""): ?array
{
if ($website !== "") {
$this->addError(new Error("Reset failed", "failed"));
return null;
}
if (!$this->limit("vino_password_reset_log")) {
return null;
}
$length = mb_strlen($password);
if (
$login === ""
|| mb_strlen($login) > 254
|| !preg_match('/^[A-Za-z0-9]{32}$/', $checkword)
) {
$this->addError(new Error("Invalid link", "link"));
return null;
}
if ($length < self::PASSWORD_MIN || $length > self::PASSWORD_MAX || mb_strtolower($password) === mb_strtolower($login)) {
$this->addError(new Error("Weak password", "password"));
return null;
}
$result = (new \CUser())->ChangePassword($login, $checkword, $password, $password, SITE_ID, "", 0, false);
if (($result["TYPE"] ?? "") !== "OK") {
$this->addError(new Error("Reset failed", (string)($result["FIELD"] ?? "") === "PASSWORD" ? "password" : "link"));
return null;
}
return ["ok" => true];
}
private function limit(string $sessionKey): bool
{
$session = Application::getInstance()->getSession();
$now = time();
$log = array_values(array_filter((array)($session->get($sessionKey) ?? []), static fn($at): bool => (int)$at > $now - self::WINDOW_SECONDS));
if (count($log) >= self::MAX_PER_WINDOW) {
$this->addError(new Error("Too many attempts", "too_often"));
return false;
}
$log[] = $now;
$session->set($sessionKey, $log);
return true;
}
private function mayMail(int $userId): bool
{
$cache = Cache::createInstance();
if ($cache->initCache(self::MAIL_PAUSE_SECONDS, "vino_pass_mail_" . $userId, "/vino/password")) {
return false;
}
$cache->startDataCache();
$cache->endDataCache(["sent" => true]);
return true;
}
}
@@ -0,0 +1,152 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca\Controller;
use Bitrix\Main\Application;
use Bitrix\Main\Data\Cache;
use Bitrix\Main\Engine\ActionFilter\Csrf;
use Bitrix\Main\Engine\ActionFilter\HttpMethod;
use Bitrix\Main\Engine\Controller;
use Bitrix\Main\Engine\CurrentUser;
use Bitrix\Main\Error;
use Bitrix\Main\Security\Password;
use Bitrix\Main\UserTable;
use Jinove\Vinoteca\Redirect;
class Profile extends Controller
{
private const MAX_PER_WINDOW = 5;
private const WINDOW_SECONDS = 600;
private const NAME_MAX = 50;
private const PASSWORD_MIN = 8;
private const PASSWORD_MAX = 200;
public function configureActions(): array
{
$filters = ["prefilters" => [new HttpMethod([HttpMethod::METHOD_POST]), new Csrf()]];
return ["save" => $filters, "password" => $filters, "logout" => $filters];
}
public function saveAction(string $name, string $phone = ""): ?array
{
$userId = $this->userId();
if ($userId <= 0) {
$this->addError(new Error("Not authorized", "auth"));
return null;
}
$name = trim((string)preg_replace('/\s+/u', " ", $name));
if ($name === "" || mb_strlen($name) > self::NAME_MAX) {
$this->addError(new Error("Invalid name", "name"));
return null;
}
if (!mb_check_encoding($name, "UTF-8") || preg_match('/[<>\x00-\x1f\x7f]/', $name)) {
$this->addError(new Error("Invalid name characters", "name_chars"));
return null;
}
$phone = trim($phone);
if ($phone !== "" && !preg_match('/^\+\d{8,15}$/', $phone)) {
$this->addError(new Error("Invalid phone", "phone"));
return null;
}
$user = new \CUser();
if (!$user->Update($userId, ["NAME" => $name, "PERSONAL_PHONE" => $phone])) {
$this->addError(new Error("Save failed", "failed"));
return null;
}
return ["ok" => true];
}
public function passwordAction(string $current, string $password): ?array
{
$userId = $this->userId();
if ($userId <= 0) {
$this->addError(new Error("Not authorized", "auth"));
return null;
}
$session = Application::getInstance()->getSession();
$now = time();
$log = array_values(array_filter((array)($session->get("vino_profile_password_log") ?? []), static fn($at): bool => (int)$at > $now - self::WINDOW_SECONDS));
if (count($log) >= self::MAX_PER_WINDOW) {
$this->addError(new Error("Too many attempts", "too_often"));
return null;
}
$log[] = $now;
$session->set("vino_profile_password_log", $log);
if (!$this->mayTryPassword($userId)) {
$this->addError(new Error("Too many attempts", "too_often"));
return null;
}
$row = UserTable::query()->setSelect(["PASSWORD", "EMAIL"])->setFilter(["=ID" => $userId])->enablePrivateFields()->fetch() ?: null;
if ($row === null || $current === "" || !Password::equals((string)$row["PASSWORD"], $current)) {
$this->addError(new Error("Wrong current password", "current"));
return null;
}
$length = mb_strlen($password);
if ($length < self::PASSWORD_MIN || $length > self::PASSWORD_MAX || mb_strtolower($password) === mb_strtolower((string)$row["EMAIL"])) {
$this->addError(new Error("Weak password", "password"));
return null;
}
if ($password === $current) {
$this->addError(new Error("Same password", "same"));
return null;
}
$user = new \CUser();
if (!$user->Update($userId, ["PASSWORD" => $password, "CONFIRM_PASSWORD" => $password])) {
$this->addError(new Error("Password rejected", "policy"));
return null;
}
return ["ok" => true];
}
public function logoutAction(string $lang = "en"): array
{
global $USER;
$USER->Logout();
return ["ok" => true, "redirect" => Redirect::home($lang)];
}
private function mayTryPassword(int $userId): bool
{
$cache = Cache::createInstance();
$key = "vino_profile_password_" . $userId;
$attempts = [];
if ($cache->initCache(self::WINDOW_SECONDS, $key, "/vino/profile")) {
$attempts = (array)($cache->getVars()["attempts"] ?? []);
}
$now = time();
$attempts = array_values(array_filter($attempts, static fn($at): bool => (int)$at > $now - self::WINDOW_SECONDS));
if (count($attempts) >= self::MAX_PER_WINDOW) {
return false;
}
$attempts[] = $now;
$cache->clean($key, "/vino/profile");
$cache->startDataCache(self::WINDOW_SECONDS, $key, "/vino/profile");
$cache->endDataCache(["attempts" => $attempts]);
return true;
}
private function userId(): int
{
return (int)CurrentUser::get()->getId();
}
}
@@ -0,0 +1,124 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca\Controller;
use Bitrix\Main\Application;
use Bitrix\Main\Config\Option;
use Bitrix\Main\Engine\ActionFilter\Csrf;
use Bitrix\Main\Engine\ActionFilter\HttpMethod;
use Bitrix\Main\Engine\Controller;
use Bitrix\Main\Error;
use Bitrix\Main\Type\DateTime;
use Bitrix\Main\UserTable;
use Jinove\Vinoteca\Config;
use Jinove\Vinoteca\Controller\Filter\FormGuard;
use Jinove\Vinoteca\Consent;
use Jinove\Vinoteca\Redirect;
class Register extends Controller
{
private const MAX_PER_WINDOW = 5;
private const WINDOW_SECONDS = 600;
private const PASSWORD_MIN = 8;
private const PASSWORD_MAX = 200;
private const NAME_MAX = 50;
public function configureActions(): array
{
return [
"create" => [
"prefilters" => [new HttpMethod([HttpMethod::METHOD_POST]), new Csrf(), new FormGuard(FormGuard::TIMING_ELAPSED)],
],
];
}
public function createAction(
string $name,
string $email,
string $password,
string $consent = "",
string $back = "",
string $lang = "en",
string $website = "",
int $elapsed = 0,
string $altcha = ""
): ?array {
$lang = Redirect::language($lang);
if ($website !== "") {
return ["ok" => true, "redirect" => Redirect::home($lang)];
}
$session = Application::getInstance()->getSession();
$now = time();
$log = array_values(array_filter((array)($session->get("vino_register_log") ?? []), static fn($at): bool => (int)$at > $now - self::WINDOW_SECONDS));
if (count($log) >= self::MAX_PER_WINDOW) {
$this->addError(new Error("Too many attempts", "too_often"));
return null;
}
$log[] = $now;
$session->set("vino_register_log", $log);
$name = trim((string)preg_replace('/\s+/u', " ", $name));
$email = mb_strtolower(trim($email));
$length = mb_strlen($password);
if (
$consent !== "1"
|| $name === ""
|| mb_strlen($name) > self::NAME_MAX
|| !mb_check_encoding($name, "UTF-8")
|| preg_match('/[<>\x00-\x1f\x7f]/', $name)
|| !check_email($email)
|| mb_strlen($email) > 254
|| $length < self::PASSWORD_MIN
|| $length > self::PASSWORD_MAX
|| mb_strtolower($password) === $email
) {
$this->addError(new Error("Registration failed", "failed"));
return null;
}
$exists = UserTable::getRow([
"select" => ["ID"],
"filter" => ["LOGIC" => "OR", "=EMAIL" => $email, "=LOGIN" => $email],
]);
if ($exists !== null) {
$this->addError(new Error("Registration failed", "failed"));
return null;
}
$groups = array_values(array_filter(array_map("intval", explode(",", (string)Option::get("main", "new_user_registration_def_group", "")))));
$user = new \CUser();
$id = (int)$user->Add([
"LOGIN" => $email,
"EMAIL" => $email,
"NAME" => $name,
"PASSWORD" => $password,
"CONFIRM_PASSWORD" => $password,
"ACTIVE" => "Y",
"LID" => SITE_ID,
"GROUP_ID" => $groups,
"UF_CONSENT_TIME" => (string)new DateTime(),
"UF_CONSENT_VERSION" => Consent::VERSION,
"UF_CONSENT_PAGE" => $this->consentPage(),
"UF_CONSENT_URL" => Config::host() . SITE_DIR . "consent/",
]);
if ($id <= 0) {
$this->addError(new Error("Registration failed", "failed"));
return null;
}
global $USER;
$USER->Authorize($id);
return ["ok" => true, "redirect" => Redirect::back($back, $lang)];
}
private function consentPage(): string
{
$path = (string)parse_url((string)($this->getRequest()->getHeader("Referer") ?? ""), PHP_URL_PATH);
return mb_check_encoding($path, "UTF-8") && !preg_match('/[\x00-\x1f\x7f]/', $path) ? mb_substr($path, 0, 200) : "";
}
}
@@ -0,0 +1,130 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca\Controller;
use Bitrix\Iblock\ElementTable;
use Bitrix\Main\Application;
use Bitrix\Main\Engine\ActionFilter\Authentication;
use Bitrix\Main\Engine\ActionFilter\Csrf;
use Bitrix\Main\Engine\ActionFilter\HttpMethod;
use Bitrix\Main\Engine\Controller;
use Bitrix\Main\Engine\CurrentUser;
use Bitrix\Main\Error;
use Bitrix\Main\Loader;
use Jinove\Vinoteca\Catalog\ReviewStats;
use Jinove\Vinoteca\Config;
use Jinove\Vinoteca\Consent;
use Jinove\Vinoteca\Controller\Filter\FormGuard;
class Review extends Controller
{
private const SITE_URL = "https://vinoteca.jimagie.com";
private const MIN_FILL_MS = 2500;
private const RETRY_SECONDS = 60;
private const LANGS = ["en" => "", "ru" => "/ru", "pl" => "/pl"];
public function configureActions(): array
{
return [
"add" => [
"prefilters" => [new Authentication(), new HttpMethod([HttpMethod::METHOD_POST]), new Csrf(), new FormGuard(FormGuard::TIMING_STARTED, self::MIN_FILL_MS)],
],
];
}
public function addAction(
int $productId,
int $rating,
string $text,
string $consent = "",
string $website = "",
int $started = 0,
string $altcha = "",
string $lang = "en",
string $page = ""
): ?array {
if ($website !== "" || FormGuard::startedTooEarly($started, self::MIN_FILL_MS)) {
return ["ok" => true];
}
$user = CurrentUser::get();
$author = trim((string)$user->getFullName());
if ($author === "") {
$author = trim((string)$user->getLogin());
}
$author = mb_substr($author, 0, 60);
if (!mb_check_encoding($author, "UTF-8") || !mb_check_encoding($text, "UTF-8")) {
$this->addError(new Error("Wrong encoding", "text"));
return null;
}
$author = trim((string)preg_replace('/\s+/u', " ", $author));
$text = trim($text);
$lang = isset(self::LANGS[$lang]) ? $lang : "en";
if ($rating < 1 || $rating > 5) {
$this->addError(new Error("Rating is required", "rating"));
}
if (mb_strlen($text) < 10 || mb_strlen($text) > 2000) {
$this->addError(new Error("Text is required", "text"));
}
if ($consent !== "1") {
$this->addError(new Error("Consent is required", "consent"));
}
if ($this->getErrors()) {
return null;
}
$session = Application::getInstance()->getSession();
if (time() - (int)($session->get("vino_review_last") ?? 0) < self::RETRY_SECONDS) {
$this->addError(new Error("Too often", "too_often"));
return null;
}
if (!Loader::includeModule("iblock")) {
$this->addError(new Error("Iblock module is required", "internal"));
return null;
}
$product = ElementTable::getRow([
"select" => ["ID", "NAME"],
"filter" => ["=ID" => $productId, "=IBLOCK_ID" => Config::iblockId("catalog"), "=ACTIVE" => "Y"],
]);
if ($product === null) {
$this->addError(new Error("Wine not found", "not_found"));
return null;
}
$pagePath = (string)parse_url($page, PHP_URL_PATH);
$element = new \CIBlockElement();
$id = $element->Add([
"IBLOCK_ID" => ReviewStats::iblockId(ReviewStats::REVIEWS_CODE),
"ACTIVE" => "N",
"NAME" => mb_substr($author . ": " . $product["NAME"], 0, 255),
"ACTIVE_FROM" => ConvertTimeStamp(time(), "FULL"),
"PREVIEW_TEXT" => $text,
"PREVIEW_TEXT_TYPE" => "text",
"PROPERTY_VALUES" => [
"PRODUCT" => (int)$product["ID"],
"RATING" => $rating,
"AUTHOR" => $author,
"USER_ID" => (int)$user->getId(),
"LANG" => $lang,
"PAGE" => self::SITE_URL . ($pagePath !== "" ? $pagePath : "/"),
"CONSENT" => "Y",
"CONSENT_VERSION" => Consent::VERSION,
"CONSENT_URL" => self::SITE_URL . self::LANGS[$lang] . "/consent/",
],
]);
if (!$id) {
$this->addError(new Error("Review was not saved", "internal"));
return null;
}
$session->set("vino_review_last", time());
return ["ok" => true];
}
}
@@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca\Controller;
use Bitrix\Main\Engine\ActionFilter\HttpMethod;
use Bitrix\Main\Engine\Controller;
class State extends Controller
{
public function configureActions(): array
{
return [
"all" => [
"prefilters" => [new HttpMethod([HttpMethod::METHOD_GET])],
],
];
}
public function allAction(): array
{
return [
"favorite" => (new Favorite())->stateAction(),
"basket" => (new Basket())->stateAction(),
"compare" => (new Compare())->stateAction(),
];
}
}
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca;
use Bitrix\Main\Localization\Loc;
final class DateFormat
{
public static function long(int $timestamp, string $languageId): string
{
return (string)Loc::getMessage("JINOVE_VINOTECA_DATE_LONG", [
"#DAY#" => date("j", $timestamp),
"#MONTH#" => Loc::getMessage("JINOVE_VINOTECA_MONTH_" . date("n", $timestamp), null, $languageId),
"#YEAR#" => date("Y", $timestamp),
], $languageId);
}
}
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca;
class Language
{
public static function url(string $language): string
{
global $APPLICATION;
$languages = Config::languages();
$path = (string)$APPLICATION->GetCurPage(false);
if (SITE_DIR !== "/" && str_starts_with($path, SITE_DIR)) {
$path = "/" . substr($path, strlen(SITE_DIR));
}
return Config::host() . rtrim((string)($languages[$language]["dir"] ?? "/"), "/") . $path;
}
}
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca;
use Bitrix\Main\Loader;
final class Money
{
public static function format(float $amount, string $currency): string
{
if (!Loader::includeModule("currency")) {
return (string)$amount;
}
return trim(html_entity_decode(strip_tags((string)\CCurrencyLang::CurrencyFormat($amount, $currency)), ENT_QUOTES | ENT_HTML5, "UTF-8"));
}
}
@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca;
use Bitrix\Main\Application;
final class Navigation
{
public static function isActive(string $path, bool $exact = false): bool
{
if (defined("ERROR_404")) {
return false;
}
$current = self::current();
return $exact ? $current === $path : str_starts_with($current, $path);
}
private static function current(): string
{
$uri = (string)Application::getInstance()->getContext()->getRequest()->getRequestUri();
$path = (string)parse_url($uri, PHP_URL_PATH);
if (SITE_DIR !== "/" && str_starts_with($path, SITE_DIR)) {
$path = "/" . substr($path, strlen(SITE_DIR));
}
if (str_ends_with($path, "index.php")) {
$path = substr($path, 0, -9);
}
return $path === "" ? "/" : $path;
}
}
+162
View File
@@ -0,0 +1,162 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca;
use Bitrix\Iblock\ElementTable;
use Bitrix\Main\Localization\Loc;
use Bitrix\Main\Type\DateTime;
use Jinove\Vinoteca\Catalog\LocalizedText;
Loc::loadMessages(__FILE__);
final class News
{
public const PAGE_SIZE = 8;
public const LIST_TEMPLATE = "vinoteca-news-list";
public const FILTER_OTHER = "vinoNewsOther";
private const LIST_FIELDS = ["PREVIEW_PICTURE", "PREVIEW_TEXT", "ACTIVE_FROM"];
private const LIST_PROPERTIES = ["NAME_EN", "NAME_PL", "PREVIEW_TEXT_EN", "PREVIEW_TEXT_PL"];
public static function folder(): string
{
return SITE_DIR . "articles/";
}
public static function iblockId(): int
{
return Config::iblockId("news");
}
public static function listParams(bool $ajax = false): array
{
return array_merge(self::baseParams(self::PAGE_SIZE), [
"DISPLAY_BOTTOM_PAGER" => "Y",
"PAGER_TEMPLATE" => "vinoteca",
"PAGER_TITLE" => (string)Loc::getMessage("VINO_NEWS_PAGER_TITLE"),
"PAGER_SHOW_ALWAYS" => "N",
"PAGER_SHOW_ALL" => "N",
"PAGER_DESC_NUMBERING" => "N",
"PAGER_BASE_LINK_ENABLE" => "Y",
"PAGER_BASE_LINK" => self::folder(),
"VINO_AJAX" => $ajax ? "Y" : "N",
]);
}
public static function homeParams(): array
{
return self::baseParams(3);
}
public static function otherParams(int $excludeId): array
{
$GLOBALS[self::FILTER_OTHER] = ["!ID" => $excludeId];
return array_merge(self::baseParams(3), [
"FILTER_NAME" => self::FILTER_OTHER,
"CACHE_FILTER" => "Y",
]);
}
public static function pageCount(): int
{
$iblockId = self::iblockId();
if ($iblockId <= 0) {
return 1;
}
return (int)Cached::remember("/jinove/vinoteca/news", "pages_" . $iblockId, 3600, ["iblock_id_" . $iblockId], static function () use ($iblockId): int {
$now = new DateTime();
$count = ElementTable::getCount([
"=IBLOCK_ID" => $iblockId,
"=ACTIVE" => "Y",
["LOGIC" => "OR", ["=ACTIVE_FROM" => false], ["<=ACTIVE_FROM" => $now]],
["LOGIC" => "OR", ["=ACTIVE_TO" => false], [">=ACTIVE_TO" => $now]],
]);
return max(1, (int)ceil($count / self::PAGE_SIZE));
});
}
public static function pageMeta(int $page): array
{
if ($page > 1) {
return [
"title" => (string)Loc::getMessage("VINO_NEWS_PAGE_TITLE_N", ["#PAGE#" => $page]),
"description" => (string)Loc::getMessage("VINO_NEWS_DESCRIPTION_N", ["#PAGE#" => $page]),
"canonical" => self::folder() . "?PAGEN_1=" . $page,
];
}
return [
"title" => (string)Loc::getMessage("VINO_NEWS_PAGE_TITLE"),
"description" => (string)Loc::getMessage("VINO_NEWS_DESCRIPTION"),
"canonical" => self::folder(),
];
}
public static function card(array $item, array $widths = [480, 800]): array
{
$item = LocalizedText::localizeItem($item, ["NAME", "PREVIEW_TEXT", "DETAIL_TEXT"], []);
$picture = $item["DETAIL_PICTURE"] ?? null;
$picture = $item["PREVIEW_PICTURE"] ?: $picture;
$item["VINO_PICTURE"] = [];
if (!empty($picture["ID"])) {
$srcset = [];
foreach ($widths as $width) {
if ((int)$picture["WIDTH"] > $width) {
$resized = \CFile::ResizeImageGet((int)$picture["ID"], ["width" => $width, "height" => 9999], BX_RESIZE_IMAGE_PROPORTIONAL, false);
if (!empty($resized["src"])) {
$srcset[] = $resized["src"] . " " . $width . "w";
}
}
}
$srcset[] = $picture["SRC"] . " " . (int)$picture["WIDTH"] . "w";
$item["VINO_PICTURE"] = [
"ID" => (int)$picture["ID"],
"SRC" => (string)$picture["SRC"],
"SRCSET" => implode(", ", $srcset),
"WIDTH" => (int)$picture["WIDTH"],
"HEIGHT" => (int)$picture["HEIGHT"],
"ALT" => (string)$item["~NAME"],
];
}
$published = $item["ACTIVE_FROM"] ? DateTime::createFromUserTime((string)$item["ACTIVE_FROM"])->getTimestamp() : 0;
$item["VINO_TIMESTAMP"] = $published;
$item["VINO_DATE"] = $published ? ["ISO" => date("Y-m-d", $published), "TEXT" => DateFormat::long($published, LANGUAGE_ID)] : [];
return $item;
}
private static function baseParams(int $count): array
{
return [
"IBLOCK_TYPE" => "news",
"IBLOCK_ID" => self::iblockId(),
"NEWS_COUNT" => (string)$count,
"SORT_BY1" => "ACTIVE_FROM",
"SORT_ORDER1" => "DESC",
"SORT_BY2" => "ID",
"SORT_ORDER2" => "DESC",
"FIELD_CODE" => self::LIST_FIELDS,
"PROPERTY_CODE" => self::LIST_PROPERTIES,
"DETAIL_URL" => self::folder() . "#ELEMENT_CODE#/",
"CHECK_DATES" => "Y",
"CACHE_TYPE" => "A",
"CACHE_TIME" => "36000000",
"CACHE_GROUPS" => "N",
"CACHE_FILTER" => "N",
"SET_TITLE" => "N",
"SET_BROWSER_TITLE" => "N",
"SET_META_KEYWORDS" => "N",
"SET_META_DESCRIPTION" => "N",
"SET_LAST_MODIFIED" => "N",
"SET_STATUS_404" => "N",
"SHOW_404" => "N",
"INCLUDE_IBLOCK_INTO_CHAIN" => "N",
"ADD_SECTIONS_CHAIN" => "N",
"DISPLAY_TOP_PAGER" => "N",
"DISPLAY_BOTTOM_PAGER" => "N",
];
}
}
@@ -0,0 +1,339 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca;
use Bitrix\Iblock\Iblock;
use Bitrix\Main\Application;
use Bitrix\Main\Data\Cache;
use Bitrix\Main\Loader;
use Bitrix\Main\Localization\Loc;
use Bitrix\Main\Type\DateTime;
use Bitrix\Sale\Internals\DiscountCouponTable;
use Bitrix\Sale\Internals\DiscountGroupTable;
use Bitrix\Sale\Internals\DiscountTable;
use Jinove\Vinoteca\Catalog\Listing;
Loc::loadMessages(__FILE__);
final class Offers
{
public const FILTER = "vinoOffersFilter";
public const CACHE_TAG = "jinove_offers_discounts";
private const CACHE_DIR = "/jinove/vinoteca/offers";
public static function folder(): string
{
return SITE_DIR . "offers/";
}
public static function iblockId(): int
{
return Config::iblockId("offers");
}
public static function discounts(): array
{
if (!Loader::includeModule("sale")) {
return [];
}
$cache = Cache::createInstance();
$cacheId = "discounts_" . Config::basketSiteId();
if ($cache->initCache(3600, $cacheId, self::CACHE_DIR)) {
$vars = (array)$cache->getVars();
if ((int)($vars["expires"] ?? 0) === 0 || (int)$vars["expires"] > time()) {
return (array)($vars["rules"] ?? []);
}
$cache->clean($cacheId, self::CACHE_DIR);
}
self::clearCache();
$cache->startDataCache();
$taggedCache = Application::getInstance()->getTaggedCache();
$taggedCache->startTagCache(self::CACHE_DIR);
try {
$taggedCache->registerTag(self::CACHE_TAG);
$vars = self::loadDiscounts();
} catch (\Throwable $exception) {
$taggedCache->abortTagCache();
$cache->abortDataCache();
throw $exception;
}
$taggedCache->endTagCache();
$cache->endDataCache($vars);
return $vars["rules"];
}
private static function loadDiscounts(): array
{
$time = time();
$expires = 0;
$boundary = static function ($date) use ($time, &$expires): void {
if ($date instanceof DateTime && $date->getTimestamp() > $time) {
$expires = $expires === 0 ? $date->getTimestamp() : min($expires, $date->getTimestamp());
}
};
$current = static function ($from, $to) use ($time): bool {
return !($from instanceof DateTime && $from->getTimestamp() > $time) && !($to instanceof DateTime && $to->getTimestamp() < $time);
};
$public = [];
$groups = DiscountGroupTable::getList([
"select" => ["DISCOUNT_ID"],
"filter" => ["=GROUP_ID" => 2, "=ACTIVE" => "Y"],
]);
while ($group = $groups->fetch()) {
$public[(int)$group["DISCOUNT_ID"]] = true;
}
$rules = [];
$rows = DiscountTable::getList([
"select" => ["ID", "USE_COUPONS", "ACTIVE_FROM", "ACTIVE_TO", "CONDITIONS_LIST", "ACTIONS_LIST"],
"filter" => ["=ACTIVE" => "Y", "=LID" => Config::basketSiteId()],
]);
while ($row = $rows->fetch()) {
$boundary($row["ACTIVE_FROM"]);
$boundary($row["ACTIVE_TO"]);
if (!$current($row["ACTIVE_FROM"], $row["ACTIVE_TO"]) || !isset($public[(int)$row["ID"]]) || !empty($row["CONDITIONS_LIST"]["CHILDREN"])) {
continue;
}
$rule = self::parseActions((array)$row["ACTIONS_LIST"]);
if ($rule === null) {
continue;
}
if ($row["USE_COUPONS"] === "Y") {
$coupons = DiscountCouponTable::getList([
"select" => ["COUPON", "ACTIVE_FROM", "ACTIVE_TO"],
"filter" => [
"=DISCOUNT_ID" => (int)$row["ID"],
"=ACTIVE" => "Y",
"=TYPE" => DiscountCouponTable::TYPE_MULTI_ORDER,
"=MAX_USE" => 0,
],
]);
while ($coupon = $coupons->fetch()) {
$boundary($coupon["ACTIVE_FROM"]);
$boundary($coupon["ACTIVE_TO"]);
if ($current($coupon["ACTIVE_FROM"], $coupon["ACTIVE_TO"])) {
$rule["coupons"][] = (string)$coupon["COUPON"];
}
}
if (!$rule["coupons"]) {
continue;
}
}
$rules[(int)$row["ID"]] = $rule;
}
return ["rules" => $rules, "expires" => $expires];
}
private static function parseActions(array $actions): ?array
{
$rule = ["percent" => 0, "products" => [], "sections" => [], "coupons" => []];
foreach ((array)($actions["CHILDREN"] ?? []) as $action) {
$data = (array)($action["DATA"] ?? []);
if (($action["CLASS_ID"] ?? "") !== "ActSaleBsktGrp" || ($data["Type"] ?? "") !== "Discount" || ($data["Unit"] ?? "") !== "Perc" || ($data["True"] ?? "True") !== "True") {
return null;
}
$conditions = (array)($action["CHILDREN"] ?? []);
if (!$conditions || (count($conditions) > 1 && ($data["All"] ?? "") !== "OR")) {
return null;
}
foreach ($conditions as $condition) {
$class = (string)($condition["CLASS_ID"] ?? "");
if (!in_array($class, ["CondIBElement", "CondIBSection"], true) || ($condition["DATA"]["logic"] ?? "") !== "Equal" || !empty($condition["CHILDREN"])) {
return null;
}
$key = $class === "CondIBElement" ? "products" : "sections";
$rule[$key] = array_merge($rule[$key], array_map("intval", (array)($condition["DATA"]["value"] ?? [])));
}
$rule["percent"] = max($rule["percent"], (int)$data["Value"]);
}
return $rule["percent"] > 0 && ($rule["products"] || $rule["sections"]) ? $rule : null;
}
public static function summary(array $discountIds): array
{
$rules = array_intersect_key(self::discounts(), array_flip(array_map("intval", $discountIds)));
$percents = array_column($rules, "percent");
$coupons = array_merge([], ...array_column($rules, "coupons"));
$products = array_values(array_unique(array_merge([], ...array_column($rules, "products"))));
$sections = array_values(array_unique(array_merge([], ...array_column($rules, "sections"))));
$badge = "";
if ($percents) {
$max = max($percents);
$badge = (string)Loc::getMessage(count(array_unique($percents)) > 1 ? "VINO_OFFERS_BADGE_UPTO" : "VINO_OFFERS_BADGE", ["#PERCENT#" => $max]);
}
return [
"active" => (bool)$rules,
"badge" => $badge,
"coupons" => array_values(array_unique($coupons)),
"products" => $products,
"sections" => $sections,
];
}
public static function automatic(): array
{
$products = [];
$sections = [];
foreach (self::discounts() as $rule) {
if (!$rule["coupons"]) {
$products = array_merge($products, $rule["products"]);
$sections = array_merge($sections, $rule["sections"]);
}
}
return ["products" => array_values(array_unique($products)), "sections" => array_values(array_unique($sections))];
}
public static function wineParams(array $products, array $sections, string $baseLink, string $listId): array
{
$filter = [];
if ($products && $sections) {
$filter[] = ["LOGIC" => "OR", ["ID" => $products], ["SECTION_ID" => $sections, "INCLUDE_SUBSECTIONS" => "Y"]];
} elseif ($products) {
$filter["ID"] = $products;
} elseif ($sections) {
$filter["SECTION_ID"] = $sections;
$filter["INCLUDE_SUBSECTIONS"] = "Y";
} else {
$filter["ID"] = [0];
}
$GLOBALS[self::FILTER] = $filter;
$catalog = Listing::catalogParams();
return [
"IBLOCK_TYPE" => $catalog["IBLOCK_TYPE"],
"IBLOCK_ID" => $catalog["IBLOCK_ID"],
"SECTION_ID" => 0,
"SHOW_ALL_WO_SECTION" => "Y",
"FILTER_NAME" => self::FILTER,
"PRICE_CODE" => $catalog["PRICE_CODE"],
"BASKET_URL" => $catalog["BASKET_URL"],
"PAGE_ELEMENT_COUNT" => "12",
"LINE_ELEMENT_COUNT" => "3",
"INCLUDE_SUBSECTIONS" => "Y",
"ELEMENT_SORT_FIELD" => "SORT",
"ELEMENT_SORT_ORDER" => "ASC",
"ELEMENT_SORT_FIELD2" => "ID",
"ELEMENT_SORT_ORDER2" => "DESC",
"PROPERTY_CODE" => $catalog["LIST_PROPERTY_CODE"],
"CACHE_TYPE" => $catalog["CACHE_TYPE"],
"CACHE_TIME" => $catalog["CACHE_TIME"],
"CACHE_GROUPS" => $catalog["CACHE_GROUPS"],
"CACHE_FILTER" => "Y",
"SET_TITLE" => "N",
"SET_BROWSER_TITLE" => "N",
"SET_META_KEYWORDS" => "N",
"SET_META_DESCRIPTION" => "N",
"SET_STATUS_404" => "N",
"SHOW_404" => "N",
"ADD_SECTIONS_CHAIN" => "N",
"ACTION_VARIABLE" => $catalog["ACTION_VARIABLE"],
"PRODUCT_ID_VARIABLE" => $catalog["PRODUCT_ID_VARIABLE"],
"USE_PRODUCT_QUANTITY" => "Y",
"ADD_TO_BASKET_ACTION" => "ADD",
"SHOW_OLD_PRICE" => "Y",
"SHOW_DISCOUNT_PERCENT" => "Y",
"DISPLAY_TOP_PAGER" => "N",
"DISPLAY_BOTTOM_PAGER" => "Y",
"PAGER_TEMPLATE" => "vinoteca",
"PAGER_SHOW_ALWAYS" => "N",
"PAGER_TITLE" => (string)Loc::getMessage("VINO_OFFERS_PAGER_TITLE"),
"PAGER_BASE_LINK_ENABLE" => "Y",
"PAGER_BASE_LINK" => $baseLink,
"SECTION_URL" => $catalog["SEF_FOLDER"] . $catalog["SEF_URL_TEMPLATES"]["section"],
"DETAIL_URL" => $catalog["SEF_FOLDER"] . $catalog["SEF_URL_TEMPLATES"]["element"],
"HIDE_NOT_AVAILABLE" => "N",
"VINO_TITLE_TAG" => "h3",
"VINO_GRID_FULL" => "Y",
"VINO_LIST_ID" => VINO_HOST . $listId . "#items",
];
}
public static function card(array $item): array
{
$item = News::card($item, [480, 800, 1200]);
$ids = array_map("intval", (array)($item["PROPERTIES"]["DISCOUNT_ID"]["VALUE"] ?? []));
$item["VINO_OFFER"] = self::summary($ids);
Application::getInstance()->getTaggedCache()->registerTag(self::CACHE_TAG);
$until = (string)($item["DATE_ACTIVE_TO"] ?? $item["ACTIVE_TO"] ?? "");
$item["VINO_UNTIL"] = $until !== "" ? (string)Loc::getMessage("VINO_OFFERS_UNTIL", ["#DATE#" => DateFormat::long(DateTime::createFromUserTime($until)->getTimestamp(), LANGUAGE_ID)]) : (string)Loc::getMessage("VINO_OFFERS_ALWAYS");
return $item;
}
public static function listParams(): array
{
return [
"IBLOCK_TYPE" => "content",
"IBLOCK_ID" => self::iblockId(),
"NEWS_COUNT" => "20",
"SORT_BY1" => "SORT",
"SORT_ORDER1" => "ASC",
"SORT_BY2" => "ACTIVE_FROM",
"SORT_ORDER2" => "DESC",
"FIELD_CODE" => ["PREVIEW_PICTURE", "PREVIEW_TEXT", "ACTIVE_FROM", "DATE_ACTIVE_TO"],
"PROPERTY_CODE" => ["DISCOUNT_ID", "NAME_EN", "NAME_PL", "PREVIEW_TEXT_EN", "PREVIEW_TEXT_PL"],
"DETAIL_URL" => self::folder() . "#ELEMENT_CODE#/",
"CHECK_DATES" => "Y",
"CACHE_TYPE" => "A",
"CACHE_TIME" => "3600",
"CACHE_GROUPS" => "N",
"SET_TITLE" => "N",
"SET_BROWSER_TITLE" => "N",
"SET_META_KEYWORDS" => "N",
"SET_META_DESCRIPTION" => "N",
"SET_LAST_MODIFIED" => "N",
"SET_STATUS_404" => "N",
"SHOW_404" => "N",
"INCLUDE_IBLOCK_INTO_CHAIN" => "N",
"ADD_SECTIONS_CHAIN" => "N",
"DISPLAY_TOP_PAGER" => "N",
"DISPLAY_BOTTOM_PAGER" => "N",
];
}
public static function discountIdsOf(int $elementId): array
{
$iblockId = self::iblockId();
if ($elementId <= 0 || $iblockId <= 0 || !Loader::includeModule("iblock")) {
return [];
}
return (array)Cached::remember(self::CACHE_DIR, "discount_ids_" . $elementId, 86400, ["iblock_id_" . $iblockId], static function () use ($iblockId, $elementId): array {
$ids = [];
$element = Iblock::wakeUp($iblockId)->getEntityDataClass()::getByPrimary($elementId, ["select" => ["ID", "DISCOUNT_ID"]])->fetchObject();
if ($element) {
foreach ($element->getDiscountId()->getAll() as $value) {
if ((int)$value->getValue() > 0) {
$ids[] = (int)$value->getValue();
}
}
}
return $ids;
});
}
public static function refresh(): void
{
self::discounts();
}
public static function canonical(string $path): void
{
$navNum = (int)($GLOBALS["NavNum"] ?? 0);
$page = $navNum > 0 ? Application::getInstance()->getContext()->getRequest()->getQuery("PAGEN_" . $navNum) : null;
if ($page !== null && (int)$page > 1) {
$GLOBALS["APPLICATION"]->SetPageProperty("vino_canonical", $path . "?PAGEN_" . $navNum . "=" . (int)$page);
}
}
public static function clearCache(): void
{
Application::getInstance()->getTaggedCache()->clearByTag(self::CACHE_TAG);
}
}
@@ -0,0 +1,89 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca;
use Bitrix\Main\Type\DateTime;
final class OfferSchema
{
private const CONTEXT = "https://schema.org";
public static function list(array $items, string $path, string $name, string $description): array
{
$url = Config::host() . $path;
$list = [];
foreach (array_values($items) as $index => $item) {
$list[] = ["@type" => "ListItem", "position" => $index + 1, "url" => $item["url"], "name" => $item["name"]];
}
return [
"@context" => self::CONTEXT,
"@graph" => [
[
"@type" => "CollectionPage",
"@id" => $url . "#webpage",
"url" => $url,
"name" => $name,
"description" => $description,
"inLanguage" => LANGUAGE_ID,
"about" => ["@id" => Config::host() . "/#store"],
"mainEntity" => ["@id" => $url . "#offers"],
"workTranslation" => PageSchema::translations($path, "CollectionPage"),
],
[
"@type" => "ItemList",
"@id" => $url . "#offers",
"url" => $url,
"numberOfItems" => count($list),
"itemListElement" => $list,
],
],
];
}
public static function detail(array $offer): array
{
$url = Config::host() . $offer["path"];
$store = ["@id" => Config::host() . "/#store"];
$event = [
"@type" => "SaleEvent",
"@id" => $url . "#event",
"url" => $url,
"name" => $offer["name"],
"description" => $offer["description"],
"inLanguage" => LANGUAGE_ID,
"eventStatus" => "https://schema.org/EventScheduled",
"eventAttendanceMode" => "https://schema.org/MixedEventAttendanceMode",
"location" => $store,
"organizer" => $store,
];
foreach (["startDate" => "start", "endDate" => "end"] as $property => $key) {
if ($offer[$key] !== "") {
$event[$property] = $offer[$key];
}
}
$page = [
"@type" => "WebPage",
"@id" => $url . "#webpage",
"url" => $url,
"name" => $offer["name"],
"description" => $offer["description"],
"inLanguage" => LANGUAGE_ID,
"mainEntity" => ["@id" => $url . "#event"],
"workTranslation" => PageSchema::translations($offer["path"], "WebPage"),
];
if ($offer["image"]) {
$event["image"] = PageSchema::image($url . "#image", $offer["image"]["url"], $offer["image"]["width"], $offer["image"]["height"]);
$page["primaryImageOfPage"] = ["@id" => $url . "#image"];
}
return ["@context" => self::CONTEXT, "@graph" => [$page, $event]];
}
public static function date(string $value): string
{
return $value !== "" ? date(DATE_ATOM, DateTime::createFromUserTime($value)->getTimestamp()) : "";
}
}
@@ -0,0 +1,17 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca;
use Bitrix\Main\HttpRequest;
class Origin
{
public static function allowed(HttpRequest $request): bool
{
$origin = (string)($request->getHeader("Origin") ?? "");
return $origin === "" || $origin === Config::host();
}
}
@@ -0,0 +1,70 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca;
class PageSchema
{
public static function translations(string $path, string $pageType): array
{
$relative = SITE_DIR !== "/" && str_starts_with($path, SITE_DIR) ? "/" . substr($path, strlen(SITE_DIR)) : $path;
$nodes = [];
foreach (Config::languages() as $language => $settings) {
if ($language === LANGUAGE_ID) {
continue;
}
$url = Config::host() . rtrim((string)$settings["dir"], "/") . $relative;
$nodes[] = ["@type" => $pageType, "@id" => $url . "#webpage", "url" => $url, "inLanguage" => $language];
}
return $nodes;
}
public static function legalPage(string $path, string $name, string $description, string $modified): array
{
$url = Config::host() . $path;
return [
"@context" => "https://schema.org",
"@type" => "WebPage",
"@id" => $url . "#webpage",
"url" => $url,
"name" => $name,
"description" => $description,
"inLanguage" => LANGUAGE_ID,
"dateModified" => $modified,
"workTranslation" => self::translations($path, "WebPage"),
];
}
public static function aboutPage(string $path, string $name, string $description, array $image): array
{
$url = Config::host() . $path;
return [
"@context" => "https://schema.org",
"@type" => "AboutPage",
"@id" => $url . "#webpage",
"url" => $url,
"name" => $name,
"description" => $description,
"inLanguage" => LANGUAGE_ID,
"mainEntity" => ["@id" => Config::host() . "/#store"],
"primaryImageOfPage" => $image,
"workTranslation" => self::translations($path, "AboutPage"),
];
}
public static function image(string $id, string $url, int $width, int $height): array
{
return [
"@type" => "ImageObject",
"@id" => $id,
"url" => $url,
"contentUrl" => $url,
"width" => ["@type" => "QuantitativeValue", "value" => $width, "unitCode" => "E37"],
"height" => ["@type" => "QuantitativeValue", "value" => $height, "unitCode" => "E37"],
];
}
}
@@ -0,0 +1,73 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca\Personal;
use Bitrix\Main\Loader;
use Bitrix\Sale\Internals\BasketTable;
use Bitrix\Sale\Order;
use Bitrix\Sale\OrderStatus;
use Jinove\Vinoteca\Catalog\Media;
use Jinove\Vinoteca\Catalog\Related;
use Jinove\Vinoteca\Money;
class Orders
{
private const FINAL_STATUS = "F";
private const PER_PAGE = 20;
public static function forUser(int $userId, bool $completed, int $page = 1): array
{
if ($userId <= 0 || !Loader::includeModule("sale") || !Loader::includeModule("currency")) {
return ["orders" => [], "more" => false];
}
$statuses = OrderStatus::getAllStatusesNames(LANGUAGE_ID);
$filter = $completed
? ["=USER_ID" => $userId, ["LOGIC" => "OR", ["=STATUS_ID" => self::FINAL_STATUS], ["=CANCELED" => "Y"]]]
: ["=USER_ID" => $userId, "!=STATUS_ID" => self::FINAL_STATUS, "=CANCELED" => "N"];
$orders = [];
$rows = Order::getList([
"select" => ["ID", "ACCOUNT_NUMBER", "DATE_INSERT", "STATUS_ID", "PRICE", "CURRENCY", "CANCELED"],
"filter" => $filter,
"order" => ["ID" => "DESC"],
"limit" => self::PER_PAGE + 1,
"offset" => (max(1, $page) - 1) * self::PER_PAGE,
]);
while ($row = $rows->fetch()) {
$orders[(int)$row["ID"]] = [
"number" => (string)$row["ACCOUNT_NUMBER"],
"date" => $row["DATE_INSERT"]->getTimestamp(),
"statusId" => (string)$row["STATUS_ID"],
"status" => $row["CANCELED"] === "Y" ? "" : (string)($statuses[$row["STATUS_ID"]] ?? ""),
"canceled" => $row["CANCELED"] === "Y",
"total" => Money::format((float)$row["PRICE"], (string)$row["CURRENCY"]),
"items" => [],
];
}
$more = count($orders) > self::PER_PAGE;
$orders = array_slice($orders, 0, self::PER_PAGE, true);
if (!$orders) {
return ["orders" => [], "more" => false];
}
$lines = BasketTable::getList([
"select" => ["ORDER_ID", "PRODUCT_ID", "NAME", "QUANTITY", "PRICE", "CURRENCY"],
"filter" => ["@ORDER_ID" => array_keys($orders)],
"order" => ["ID" => "ASC"],
])->fetchAll();
$productIds = array_map(static fn(array $line): int => (int)$line["PRODUCT_ID"], $lines);
$images = Media::thumbs($productIds, 120, 120);
$products = Related::summariesById($productIds);
foreach ($lines as $line) {
$orders[(int)$line["ORDER_ID"]]["items"][] = [
"name" => (string)$line["NAME"],
"url" => (string)($products[(int)$line["PRODUCT_ID"]]["url"] ?? ""),
"quantity" => (float)$line["QUANTITY"],
"price" => Money::format((float)$line["PRICE"], (string)$line["CURRENCY"]),
"image" => $images[(int)$line["PRODUCT_ID"]] ?? "",
];
}
return ["orders" => array_values($orders), "more" => $more];
}
}
@@ -0,0 +1,51 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca\Personal;
use Bitrix\Iblock\Iblock;
use Bitrix\Main\Loader;
use Jinove\Vinoteca\Catalog\Related;
use Jinove\Vinoteca\Catalog\ReviewStats;
class Reviews
{
private const LIMIT = 100;
public static function forUser(int $userId): array
{
$reviewsId = ReviewStats::iblockId(ReviewStats::REVIEWS_CODE);
if ($userId <= 0 || $reviewsId <= 0 || !Loader::includeModule("iblock")) {
return [];
}
$table = Iblock::wakeUp($reviewsId)->getEntityDataClass();
if ($table === null) {
return [];
}
$rows = $table::getList([
"select" => ["ID", "ACTIVE", "PREVIEW_TEXT", "ACTIVE_FROM", "DATE_CREATE", "PRODUCT_" => "PRODUCT", "RATING_" => "RATING"],
"filter" => ["=USER_ID.VALUE" => $userId],
"order" => ["ACTIVE_FROM" => "DESC", "ID" => "DESC"],
"limit" => self::LIMIT,
])->fetchAll();
$items = [];
foreach ($rows as $row) {
$date = $row["ACTIVE_FROM"] ?: $row["DATE_CREATE"];
$items[] = [
"product" => (int)$row["PRODUCT_VALUE"],
"rating" => max(0, min(5, (int)$row["RATING_VALUE"])),
"text" => trim((string)preg_replace('/\s+/u', " ", strip_tags((string)$row["PREVIEW_TEXT"]))),
"date" => $date instanceof \Bitrix\Main\Type\DateTime ? $date->getTimestamp() : 0,
"published" => $row["ACTIVE"] === "Y",
];
}
$products = Related::summariesById(array_column($items, "product"));
foreach ($items as $key => $item) {
$items[$key]["name"] = $products[$item["product"]]["name"] ?? "";
$items[$key]["url"] = $products[$item["product"]]["url"] ?? "";
}
return $items;
}
}
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca;
class Phone
{
public static function format(mixed $raw): string
{
$digits = preg_replace("~\\D~", "", (string)$raw);
if (strlen($digits) === 11 && ($digits[0] === "8" || $digits[0] === "7")) {
$digits = substr($digits, 1);
}
if (strlen($digits) !== 10) {
return "";
}
return "+7 (" . substr($digits, 0, 3) . ") " . substr($digits, 3, 3) . "-" . substr($digits, 6, 2) . "-" . substr($digits, 8, 2);
}
}
@@ -0,0 +1,46 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca;
class Redirect
{
private const HOMES = ["en" => "/", "ru" => "/ru/", "pl" => "/pl/"];
public static function safe(string $back): string
{
$path = (string)parse_url($back, PHP_URL_PATH);
if (
$path === ""
|| preg_match('/[\x00-\x1f\x7f\\\\]/', $back)
|| strlen($back) > 300
|| $path[0] !== "/"
|| str_starts_with($path, "//")
|| preg_match('#(^|/)\.\.?(/|$)#', $path)
|| preg_match('#^(/(ru|pl))?/(bitrix|upload|local|login|register|forgot-password|reset-password)(/|$)#', $path)
) {
return "";
}
$query = (string)parse_url($back, PHP_URL_QUERY);
return $path . ($query !== "" ? "?" . $query : "");
}
public static function language(string $language): string
{
return isset(self::HOMES[$language]) ? $language : "en";
}
public static function home(string $language): string
{
return self::HOMES[self::language($language)];
}
public static function back(string $back, string $language): string
{
$safe = self::safe($back);
return $safe !== "" ? $safe : self::home($language);
}
}
@@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca;
use Bitrix\Iblock\ElementTable;
use Bitrix\Iblock\IblockTable;
use Bitrix\Main\Loader;
use Bitrix\Main\Type\DateTime;
final class Retention
{
private const QUESTIONS_CODE = "sommelier_questions";
private const MONTHS = 12;
private const BATCH = 200;
public static function purge(): string
{
if (Loader::includeModule("iblock")) {
$iblock = IblockTable::getRow(["select" => ["ID"], "filter" => ["=CODE" => self::QUESTIONS_CODE]]);
if ($iblock !== null) {
$before = new DateTime();
$before->add("-" . self::MONTHS . " months");
$rows = ElementTable::getList([
"select" => ["ID"],
"filter" => ["=IBLOCK_ID" => (int)$iblock["ID"], "<DATE_CREATE" => $before],
"limit" => self::BATCH,
]);
while ($row = $rows->fetch()) {
\CIBlockElement::Delete((int)$row["ID"]);
}
}
}
return __METHOD__ . "();";
}
}
@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca;
class Routing
{
private const MOVED = ["news" => "articles"];
public static function onPageStart(): void
{
if (defined("ADMIN_SECTION") || PHP_SAPI === "cli" || !in_array($_SERVER["REQUEST_METHOD"] ?? "", ["GET", "HEAD"], true)) {
return;
}
$uri = (string)($_SERVER["REQUEST_URI"] ?? "");
$path = (string)parse_url($uri, PHP_URL_PATH);
$query = (string)parse_url($uri, PHP_URL_QUERY);
if ($path === "" || preg_match('#^/(bitrix|upload|local|include)/#', $path)) {
return;
}
if (str_contains(basename($path), ".")) {
return;
}
$target = str_contains($path, "%") ? $path : mb_strtolower($path);
if (preg_match('#^(/(?:ru|pl))?/(' . implode("|", array_keys(self::MOVED)) . ')(/.*)?$#', $target, $match)) {
$target = $match[1] . "/" . self::MOVED[$match[2]] . ($match[3] ?? "/");
}
if (!str_ends_with($target, "/")) {
$target .= "/";
}
if ($target !== $path) {
LocalRedirect(Config::host() . $target . ($query !== "" ? "?" . $query : ""), true, "301 Moved permanently");
}
}
}
@@ -0,0 +1,320 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca;
use Bitrix\Main\Context;
use Bitrix\Main\Loader;
use Bitrix\Main\Localization\Loc;
use Jinove\Vinoteca\Catalog\EnumNames;
use Jinove\Vinoteca\Catalog\LocalizedText;
use Jinove\Vinoteca\Catalog\Prices;
use Jinove\Vinoteca\Catalog\Related;
use Jinove\Vinoteca\Catalog\SearchMeta;
use Jinove\Vinoteca\Catalog\Sections;
Loc::loadMessages(__FILE__);
class Search
{
public const INPUT_ID = "vino-search-input";
private const LANGUAGES = ["en", "pl"];
private const ENUMS = ["COUNTRY", "REGION", "GRAPE", "WINE_COLOR", "SUGAR"];
private const TITLE_ENUMS = ["COUNTRY", "REGION", "GRAPE"];
private const SNIPPET_LENGTH = 200;
private const THUMB_WIDTH = 144;
private const THUMB_HEIGHT = 180;
private const CACHE_DIR = "/jinove/vinoteca/search";
public static function beforeIndex(array $fields): array
{
if (($fields["MODULE_ID"] ?? "") !== "iblock" || !ctype_digit((string)($fields["ITEM_ID"] ?? "")) || !Loader::includeModule("iblock")) {
return $fields;
}
$iblockId = (int)($fields["PARAM2"] ?? 0);
if (!in_array($iblockId, array_values(self::kinds()), true)) {
return $fields;
}
$words = [];
$titles = [];
$rows = \CIBlockElement::GetProperty($iblockId, (int)$fields["ITEM_ID"], "sort", "asc", []);
while ($property = $rows->Fetch()) {
$code = (string)$property["CODE"];
if (preg_match('/_(EN|PL)$/', $code)) {
$value = is_array($property["VALUE"]) ? (string)($property["VALUE"]["TEXT"] ?? "") : (string)$property["VALUE"];
$words[] = strip_tags($value);
if (str_starts_with($code, "NAME_")) {
$titles[] = $value;
}
} elseif (in_array($code, self::ENUMS, true) && (string)$property["VALUE_XML_ID"] !== "") {
$names = [];
foreach (self::LANGUAGES as $language) {
$names[] = EnumNames::name($code, (string)$property["VALUE_XML_ID"], "", $language);
}
$words = array_merge($words, $names);
if (in_array($code, self::TITLE_ENUMS, true)) {
$titles = array_merge($titles, $names, [(string)$property["VALUE_ENUM"]]);
}
}
}
$words = array_filter(array_map("trim", $words));
if ($words) {
$fields["BODY"] = trim((string)($fields["BODY"] ?? "") . " " . implode(" ", array_unique($words)));
}
$titles = array_diff(array_unique(array_filter(array_map("trim", $titles))), [trim((string)($fields["TITLE"] ?? ""))]);
if ($titles) {
$fields["TITLE"] = trim((string)($fields["TITLE"] ?? "") . " " . implode(" ", $titles));
}
return $fields;
}
public static function folder(): string
{
return SITE_DIR . "search/";
}
public static function preparePage(): void
{
global $APPLICATION;
$query = trim((string)Context::getCurrent()->getRequest()->getQuery("q"));
$APPLICATION->SetTitle((string)Loc::getMessage("VINO_SEARCH_PAGE_H1"));
$APPLICATION->SetPageProperty("title", $query !== "" ? (string)Loc::getMessage("VINO_SEARCH_PAGE_TITLE_QUERY", ["#QUERY#" => htmlspecialcharsbx(mb_substr($query, 0, 60))]) : (string)Loc::getMessage("VINO_SEARCH_PAGE_H1"));
$APPLICATION->SetPageProperty("robots", "noindex, follow");
$APPLICATION->SetPageProperty("vino_alternates", "N");
}
public static function titleParams(): array
{
$kinds = self::kinds();
$params = [
"NUM_CATEGORIES" => "3",
"TOP_COUNT" => "6",
"ORDER" => "rank",
"USE_LANGUAGE_GUESS" => "N",
"CHECK_DATES" => "Y",
"SHOW_OTHERS" => "N",
"SHOW_INPUT" => "Y",
"PAGE" => "#SITE_DIR#search/",
"INPUT_ID" => self::INPUT_ID,
"CONTAINER_ID" => "vino-search-field",
];
$groups = [["wine"], ["brand"], ["article", "offer"]];
foreach ($groups as $index => $group) {
$types = [];
foreach ($group as $kind) {
$types[self::iblockType($kind)][] = (string)$kinds[$kind];
}
$params["CATEGORY_" . $index] = array_map(static fn(string $type): string => "iblock_" . $type, array_keys($types));
foreach ($types as $type => $ids) {
$params["CATEGORY_" . $index . "_iblock_" . $type] = $ids;
}
}
return $params;
}
public static function pageParams(): array
{
$params = [
"RESTART" => "Y",
"NO_WORD_LOGIC" => "N",
"CHECK_DATES" => "Y",
"USE_TITLE_RANK" => "Y",
"DEFAULT_SORT" => "rank",
"FILTER_NAME" => "",
"SHOW_WHERE" => "N",
"SHOW_WHEN" => "N",
"PAGE_RESULT_COUNT" => "12",
"AJAX_MODE" => "N",
"CACHE_TYPE" => "A",
"CACHE_TIME" => "3600",
"DISPLAY_TOP_PAGER" => "N",
"DISPLAY_BOTTOM_PAGER" => "Y",
"PAGER_TITLE" => (string)Loc::getMessage("VINO_SEARCH_PAGER_TITLE"),
"PAGER_SHOW_ALWAYS" => "N",
"PAGER_TEMPLATE" => "vinoteca",
"USE_LANGUAGE_GUESS" => "N",
"USE_SUGGEST" => "N",
"arrFILTER" => ["main"],
"arrFILTER_main" => [SITE_DIR . "about/", SITE_DIR . "privacy/", SITE_DIR . "consent/"],
];
foreach (self::kinds() as $kind => $iblockId) {
$type = self::iblockType($kind);
if (!in_array("iblock_" . $type, $params["arrFILTER"], true)) {
$params["arrFILTER"][] = "iblock_" . $type;
}
$params["arrFILTER_iblock_" . $type][] = (string)$iblockId;
}
return $params;
}
public static function suggest(array $categories): array
{
$hits = [];
foreach ($categories as $code => $category) {
if ($code === "all") {
continue;
}
foreach ((array)($category["ITEMS"] ?? []) as $item) {
if (($item["MODULE_ID"] ?? "") !== "") {
$hits[] = $item;
}
}
}
return self::describe($hits);
}
public static function describe(array $hits): array
{
$keys = [];
foreach ($hits as $index => $hit) {
$hits[$index]["URL"] = rtrim((string)preg_replace('/([?&])sphrase_id=[^&]*&?/', '$1', (string)($hit["URL"] ?? "")), "?&");
$keys[] = [$hit["MODULE_ID"] ?? "", $hit["PARAM2"] ?? "", $hit["ITEM_ID"] ?? "", $hits[$index]["URL"], $hit["TITLE"] ?? "", $hit["BODY"] ?? ""];
}
return (array)Cached::remember(self::CACHE_DIR, "describe_" . SITE_ID . "_" . md5(serialize($keys)), 3600, array_merge(array_map(static fn(int $iblockId): string => "iblock_id_" . $iblockId, self::kinds()), [Offers::CACHE_TAG]), static fn(): array => self::build($hits));
}
private static function build(array $hits): array
{
$kindsById = array_flip(self::kinds());
$elementIds = [];
$sectionIds = [];
foreach ($hits as $hit) {
if (($hit["MODULE_ID"] ?? "") !== "iblock") {
continue;
}
$itemId = (string)($hit["ITEM_ID"] ?? "");
if (ctype_digit($itemId) && isset($kindsById[(int)($hit["PARAM2"] ?? 0)])) {
$elementIds[] = (int)$itemId;
} elseif (preg_match('/^S(\d+)$/', $itemId, $match)) {
$sectionIds[] = (int)$match[1];
}
}
$elements = self::elements($elementIds);
$wineIds = array_keys(array_filter($elements, static fn(array $element): bool => $element["kind"] === "wine"));
$wines = Related::summariesById($wineIds);
$meta = SearchMeta::get($wineIds);
$prices = Prices::optimal($wineIds);
$sections = [];
if ($sectionIds) {
foreach (Sections::all() as $code => $section) {
if (in_array($section["ID"], $sectionIds, true)) {
$sections[$section["ID"]] = ["name" => (string)$section["NAME"], "url" => SITE_DIR . "catalog/" . $code . "/", "text" => (string)$section["DESCRIPTION"]];
}
}
}
$items = [];
foreach ($hits as $hit) {
$itemId = (string)($hit["ITEM_ID"] ?? "");
if (($hit["MODULE_ID"] ?? "") === "main") {
$items[] = self::item("page", (string)$hit["TITLE"], (string)$hit["URL"], self::snippet((string)($hit["BODY"] ?? "")));
continue;
}
if (preg_match('/^S(\d+)$/', $itemId, $match)) {
$section = $sections[(int)$match[1]] ?? null;
if ($section) {
$items[] = self::item("section", $section["name"], $section["url"], self::snippet($section["text"]));
}
continue;
}
$element = $elements[(int)$itemId] ?? null;
if ($element === null) {
continue;
}
if ($element["kind"] === "wine") {
$wine = $wines[(int)$itemId] ?? null;
if ($wine === null) {
continue;
}
$item = self::item("wine", (string)$wine["name"], (string)$wine["url"], (string)($meta[(int)$itemId]["META"] ?? ""));
$price = $prices[(int)$itemId] ?? null;
$item["price"] = $price ? Money::format((float)$price["price"], (string)$price["currency"]) : "";
} else {
$item = self::item($element["kind"], $element["name"], (string)$hit["URL"], self::snippet($element["text"]));
}
$item["image"] = $element["image"];
$items[] = $item;
}
return $items;
}
private static function item(string $kind, string $name, string $url, string $text): array
{
return [
"kind" => $kind,
"label" => (string)Loc::getMessage("VINO_SEARCH_KIND_" . strtoupper($kind)),
"name" => $name,
"url" => $url,
"meta" => $text,
"image" => "",
"price" => "",
];
}
private static function elements(array $ids): array
{
if (!$ids || !Loader::includeModule("iblock")) {
return [];
}
$kindsById = array_flip(self::kinds());
$found = [];
$rows = \CIBlockElement::GetList([], ["ID" => array_values(array_unique($ids))], false, false, ["ID", "IBLOCK_ID", "NAME", "PREVIEW_TEXT", "PREVIEW_PICTURE", "DETAIL_PICTURE"]);
while ($row = $rows->GetNextElement()) {
$element = $row->GetFields();
$element["PROPERTIES"] = $row->GetProperties();
$kind = $kindsById[(int)$element["IBLOCK_ID"]] ?? "";
$found[(int)$element["ID"]] = [
"kind" => $kind,
"name" => LocalizedText::field($element, "NAME"),
"text" => LocalizedText::field($element, "PREVIEW_TEXT"),
"image" => self::thumb((int)($element["PREVIEW_PICTURE"] ?: $element["DETAIL_PICTURE"])),
];
}
return $found;
}
private static function thumb(int $fileId): string
{
if ($fileId <= 0) {
return "";
}
$file = \CFile::ResizeImageGet($fileId, ["width" => self::THUMB_WIDTH, "height" => self::THUMB_HEIGHT], BX_RESIZE_IMAGE_EXACT, false);
return (string)($file["src"] ?? "");
}
private static function snippet(string $text): string
{
$text = trim((string)preg_replace('/\s+/u', " ", strip_tags(str_replace(["</p>", "<br>", "<br />"], " ", $text))));
if (mb_strlen($text) <= self::SNIPPET_LENGTH) {
return $text;
}
$cut = mb_substr($text, 0, self::SNIPPET_LENGTH);
$space = mb_strrpos($cut, " ");
return rtrim(mb_substr($cut, 0, $space ?: self::SNIPPET_LENGTH), " ,.;:") . "…";
}
private static function kinds(): array
{
return [
"wine" => Config::iblockId("catalog"),
"brand" => Config::iblockId("brands"),
"article" => Config::iblockId("news"),
"offer" => Config::iblockId("offers"),
];
}
private static function iblockType(string $kind): string
{
$iblock = Loader::includeModule("iblock") ? \CIBlock::GetArrayByID(self::kinds()[$kind]) : false;
return is_array($iblock) ? (string)$iblock["IBLOCK_TYPE_ID"] : "";
}
}
+122
View File
@@ -0,0 +1,122 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca;
final class Seo
{
public static function currentPath(): string
{
global $APPLICATION;
$path = (string)$APPLICATION->GetCurPage(false);
if (substr($path, -9) === "index.php") {
$path = substr($path, 0, -9);
}
return $path === "" ? "/" : $path;
}
public static function description(string $text, int $limit = 155): string
{
$text = trim((string)preg_replace('/\s+/u', " ", $text));
if (mb_strlen($text) <= $limit) {
return $text;
}
$cut = mb_substr($text, 0, $limit + 1);
$sentence = max((int)mb_strrpos($cut, ". "), (int)mb_strrpos($cut, "! "), (int)mb_strrpos($cut, "? "));
if ($sentence >= 60) {
return mb_substr($cut, 0, $sentence + 1);
}
$space = (int)mb_strrpos($cut, " ");
return rtrim(mb_substr($cut, 0, $space > 0 ? $space : $limit), " ,;:-");
}
public static function fitTitle(array $candidates, int $limit = 60): string
{
foreach ($candidates as $candidate) {
if (mb_strlen($candidate) <= $limit) {
return $candidate;
}
}
return (string)end($candidates);
}
public static function fitDescription(string $base, array $tails, int $min = 120, int $max = 160): string
{
$base = trim($base);
if (mb_strlen($base) >= $min) {
return $base;
}
foreach ($tails as $tail) {
$candidate = $base . " " . $tail;
if (mb_strlen($candidate) >= $min && mb_strlen($candidate) <= $max) {
return $candidate;
}
}
return $base;
}
public static function openGraph(string $canonical): string
{
global $APPLICATION;
if ((string)$APPLICATION->GetPageProperty("vino_alternates") === "N") {
return "";
}
$tag = static fn(string $attribute, string $name, string $value): string => ' <meta ' . $attribute . '="' . $name . '" content="' . htmlspecialcharsbx($value) . '">' . "\n";
$languages = Config::languages();
$html = $tag("property", "og:site_name", "Vinoteca") . $tag("property", "og:locale", (string)$languages[LANGUAGE_ID]["locale"]);
foreach ($languages as $code => $language) {
if ($code !== LANGUAGE_ID) {
$html .= $tag("property", "og:locale:alternate", (string)$language["locale"]);
}
}
$image = (string)$APPLICATION->GetProperty("og_image");
return $html
. $tag("property", "og:type", (string)$APPLICATION->GetProperty("og_type") ?: "website")
. $tag("property", "og:url", Config::host() . self::canonicalPath($canonical))
. $tag("property", "og:title", (string)$APPLICATION->GetTitle(false))
. $tag("property", "og:description", (string)$APPLICATION->GetProperty("description"))
. $tag("property", "og:image", $image !== "" ? $image : Config::host() . SITE_TEMPLATE_PATH . "/assets/media/og-home.jpg")
. $tag("name", "twitter:card", "summary_large_image");
}
public static function canonicalPath(string $default): string
{
global $APPLICATION;
$path = (string)$APPLICATION->GetPageProperty("vino_canonical");
return $path !== "" ? $path : $default;
}
public static function headLinks(string $default, string $host, array $languages, string $defaultLanguage): string
{
if (defined("ERROR_404") && ERROR_404 === "Y") {
return "";
}
$path = self::canonicalPath($default);
$relative = $path;
if (SITE_DIR !== "/" && strpos($path, SITE_DIR) === 0) {
$relative = "/" . substr($path, strlen(SITE_DIR));
}
$ready = array_values(array_filter(array_map("trim", explode(",", (string)$GLOBALS["APPLICATION"]->GetPageProperty("vino_langs")))));
if ($ready) {
$languages = array_intersect_key($languages, array_flip($ready));
$defaultLanguage = isset($languages[$defaultLanguage]) ? $defaultLanguage : (string)array_key_first($languages);
}
$html = '<link rel="canonical" href="' . htmlspecialcharsbx($host . $path) . '">' . "\n";
if ((string)$GLOBALS["APPLICATION"]->GetPageProperty("vino_alternates") === "N") {
return $html;
}
foreach ($languages as $language => $settings) {
$html .= ' <link rel="alternate" hreflang="' . $language . '" href="' . htmlspecialcharsbx($host . rtrim($settings["dir"], "/") . $relative) . '">' . "\n";
}
$html .= ' <link rel="alternate" hreflang="x-default" href="' . htmlspecialcharsbx($host . rtrim($languages[$defaultLanguage]["dir"], "/") . $relative) . '">' . "\n";
return $html;
}
}
@@ -0,0 +1,107 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca;
use Bitrix\Main\Localization\Loc;
use Bitrix\Main\Page\Asset;
Loc::loadMessages(__FILE__);
final class Showcase
{
private const PAGES = [
["HOME", "", true],
["SECTION", "catalog/red/", true],
["WINE", "catalog/red/altovesca-signature-sangiovese-2022/", true],
["BRANDS", "brands/", true],
["BRAND", "brands/bodega-cerrovento/", true],
["OFFERS", "offers/", true],
["OFFER", "offers/promo-vino10/", true],
["ARTICLES", "articles/", true],
["ARTICLE", "articles/wine-glass-guide/", true],
["ABOUT", "about/", true],
["SEARCH", "search/?q=merlot", false],
["COMPARE", "compare/", false],
["FAVORITES", "personal/favorites/", false],
["CART", "personal/cart/", false],
["LOGIN", "login/", false],
["PRIVACY", "privacy/", true],
["NOT_FOUND", "page-not-found/", false],
];
private const SHOTS = [
["01", "WINES", 383],
["02", "WINE_PROPS", 383],
["03", "WINE_TEXT", 383],
["04", "WINE_SEO", 383],
["05", "BRAND", 383],
["06", "OFFER", 383],
["07", "DISCOUNT", 383],
["08", "ORDERS", 383],
["09", "ORDER", 383],
["10", "ORDER_ITEMS", 383],
["11", "ARTICLE", 383],
["12", "BANNER", 383],
["13", "SITES", 172],
];
public static function preparePage(): void
{
global $APPLICATION;
$APPLICATION->SetTitle((string)Loc::getMessage("VINO_SHOWCASE_H1"));
$APPLICATION->SetPageProperty("title", (string)Loc::getMessage("VINO_SHOWCASE_TITLE"));
$APPLICATION->SetPageProperty("description", (string)Loc::getMessage("VINO_SHOWCASE_DESCRIPTION"));
$APPLICATION->SetPageProperty("vino_alternates", "N");
$asset = Asset::getInstance();
$asset->addCss(SITE_TEMPLATE_PATH . "/assets/vendor/photoswipe/photoswipe.css?v=5.4.4");
$asset->addJs(SITE_TEMPLATE_PATH . "/assets/vendor/photoswipe/photoswipe.umd.min.js?v=5.4.4");
$asset->addJs(SITE_TEMPLATE_PATH . "/assets/js/vino-shots.js?v=3");
}
public static function pages(): array
{
$pages = [];
foreach (self::PAGES as [$code, $path, $checks]) {
$url = Config::host() . SITE_DIR . $path;
$pages[] = [
"NAME" => (string)Loc::getMessage("VINO_SHOWCASE_PAGE_" . $code),
"URL" => SITE_DIR . $path,
"SCHEMA" => $checks ? "https://validator.schema.org/#url=" . rawurlencode($url) : "",
"SPEED" => $checks ? "https://pagespeed.web.dev/analysis?url=" . rawurlencode($url) : "",
];
}
return $pages;
}
public static function viewer(): array
{
return [
"closeTitle" => (string)Loc::getMessage("VINO_SHOWCASE_VIEWER_CLOSE"),
"zoomTitle" => (string)Loc::getMessage("VINO_SHOWCASE_VIEWER_ZOOM"),
"arrowPrevTitle" => (string)Loc::getMessage("VINO_SHOWCASE_VIEWER_PREV"),
"arrowNextTitle" => (string)Loc::getMessage("VINO_SHOWCASE_VIEWER_NEXT"),
"errorMsg" => (string)Loc::getMessage("VINO_SHOWCASE_VIEWER_ERROR"),
];
}
public static function shots(): array
{
$dir = SITE_TEMPLATE_PATH . "/assets/media/admin/admin-" . (LANGUAGE_ID === "ru" ? "" : "en-");
$shots = [];
foreach (self::SHOTS as [$number, $code, $height]) {
$shots[] = [
"NAME" => (string)Loc::getMessage("VINO_SHOWCASE_SHOT_" . $code),
"ALT" => (string)Loc::getMessage("VINO_SHOWCASE_SHOT_ALT", ["#NAME#" => (string)Loc::getMessage("VINO_SHOWCASE_SHOT_" . $code)]),
"SRC" => $dir . $number . "-800.webp?v=4",
"FULL" => $dir . $number . "-1920.webp?v=4",
"HEIGHT" => $height,
"FULL_HEIGHT" => (int)round($height * 1920 / 800),
];
}
return $shots;
}
}
@@ -0,0 +1,164 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca;
use Bitrix\Iblock\ElementTable;
use Bitrix\Main\Application;
use Bitrix\Main\Loader;
use Bitrix\Main\Type\DateTime;
use Jinove\Vinoteca\Catalog\MegaMenu;
use Jinove\Vinoteca\Catalog\Sections;
final class Sitemap
{
private const FILE = "/sitemap.xml";
private const LIMIT = 50000;
public static function refresh(): string
{
self::write(self::build());
return __METHOD__ . "();";
}
public static function build(): string
{
$pages = self::pages();
$languages = Config::languages();
$host = Config::host();
$xml = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">' . "\n";
$count = 0;
foreach ($pages as $page) {
$alternates = "";
foreach ($languages as $code => $language) {
$alternates .= ' <xhtml:link rel="alternate" hreflang="' . $code . '" href="' . self::escape($host . self::url($language["dir"], $page["path"])) . '"/>' . "\n";
}
$alternates .= ' <xhtml:link rel="alternate" hreflang="x-default" href="' . self::escape($host . self::url($languages["en"]["dir"], $page["path"])) . '"/>' . "\n";
foreach ($languages as $language) {
if (++$count > self::LIMIT) {
break 2;
}
$xml .= " <url>\n <loc>" . self::escape($host . self::url($language["dir"], $page["path"])) . "</loc>\n";
if ($page["lastmod"] !== "") {
$xml .= " <lastmod>" . $page["lastmod"] . "</lastmod>\n";
}
$xml .= $alternates . " </url>\n";
}
}
return $xml . "</urlset>\n";
}
private static function pages(): array
{
$catalogId = Config::iblockId("catalog");
$pages = [];
if ($catalogId <= 0 || !Loader::includeModule("iblock")) {
return $pages;
}
$sectionCodes = [];
foreach (Sections::all() as $code => $section) {
$sectionCodes[$section["ID"]] = $code;
}
$now = new DateTime();
$wines = [];
$latest = 0;
$rows = ElementTable::getList([
"select" => ["CODE", "IBLOCK_SECTION_ID", "TIMESTAMP_X"],
"filter" => [
"=IBLOCK_ID" => $catalogId,
"=ACTIVE" => "Y",
["LOGIC" => "OR", ["=ACTIVE_FROM" => false], ["<=ACTIVE_FROM" => $now]],
["LOGIC" => "OR", ["=ACTIVE_TO" => false], [">=ACTIVE_TO" => $now]],
],
"order" => ["ID" => "ASC"],
]);
while ($row = $rows->fetch()) {
$section = $sectionCodes[(int)$row["IBLOCK_SECTION_ID"]] ?? "";
if ($section === "" || (string)$row["CODE"] === "") {
continue;
}
$time = $row["TIMESTAMP_X"] instanceof DateTime ? $row["TIMESTAMP_X"]->getTimestamp() : 0;
$latest = max($latest, $time);
$wines[] = ["path" => "catalog/" . $section . "/" . rawurlencode((string)$row["CODE"]) . "/", "lastmod" => self::date($time)];
}
$menu = MegaMenu::collect($catalogId, 1000);
$lastmod = self::date($latest);
$pages[] = ["path" => "", "lastmod" => $lastmod];
$pages[] = ["path" => "catalog/", "lastmod" => $lastmod];
foreach (["TYPES", "COUNTRIES", "BRANDS"] as $group) {
foreach ($menu[$group] as $item) {
$pages[] = ["path" => ltrim(self::relative((string)$item["URL"]), "/"), "lastmod" => $lastmod];
}
}
$pages[] = ["path" => "brands/", "lastmod" => $lastmod];
$pages[] = ["path" => "about/", "lastmod" => $lastmod];
$pages = array_merge($pages, self::section("news", "articles/", $now));
$pages = array_merge($pages, self::section("offers", "offers/", $now, static fn(int $id): bool => Offers::summary(Offers::discountIdsOf($id))["active"]));
$pages = array_merge($pages, $wines);
$pages[] = ["path" => "privacy/", "lastmod" => self::date(Consent::timestamp(Consent::POLICY_VERSION))];
$pages[] = ["path" => "consent/", "lastmod" => self::date(Consent::timestamp(Consent::VERSION))];
return $pages;
}
private static function section(string $iblock, string $folder, DateTime $now, ?callable $keep = null): array
{
$iblockId = Config::iblockId($iblock);
if ($iblockId <= 0) {
return [];
}
$items = [];
$latest = 0;
$rows = ElementTable::getList([
"select" => ["ID", "CODE", "TIMESTAMP_X"],
"filter" => [
"=IBLOCK_ID" => $iblockId,
"=ACTIVE" => "Y",
["LOGIC" => "OR", ["=ACTIVE_FROM" => false], ["<=ACTIVE_FROM" => $now]],
["LOGIC" => "OR", ["=ACTIVE_TO" => false], [">=ACTIVE_TO" => $now]],
],
"order" => ["ACTIVE_FROM" => "DESC", "ID" => "DESC"],
]);
while ($row = $rows->fetch()) {
if ((string)$row["CODE"] === "" || ($keep !== null && !$keep((int)$row["ID"]))) {
continue;
}
$time = $row["TIMESTAMP_X"] instanceof DateTime ? $row["TIMESTAMP_X"]->getTimestamp() : 0;
$latest = max($latest, $time);
$items[] = ["path" => $folder . rawurlencode((string)$row["CODE"]) . "/", "lastmod" => self::date($time)];
}
return array_merge([["path" => $folder, "lastmod" => self::date($latest)]], $items);
}
private static function write(string $xml): void
{
$file = Application::getDocumentRoot() . self::FILE;
$temporary = $file . ".tmp";
if (file_put_contents($temporary, $xml, LOCK_EX) !== false) {
rename($temporary, $file);
}
}
private static function relative(string $url): string
{
return SITE_DIR !== "/" && str_starts_with($url, SITE_DIR) ? "/" . substr($url, strlen(SITE_DIR)) : $url;
}
private static function url(string $directory, string $path): string
{
return rtrim($directory, "/") . "/" . $path;
}
private static function date(int $timestamp): string
{
return $timestamp > 0 ? date("Y-m-d", $timestamp) : "";
}
private static function escape(string $value): string
{
return htmlspecialchars($value, ENT_XML1 | ENT_QUOTES, "UTF-8");
}
}
@@ -0,0 +1,61 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca;
use Jinove\Vinoteca\Catalog\PriceRange;
final class StoreSchema
{
private const OPENS = "10:00";
private const CLOSES = "21:00";
private const COUNTRY = "RU";
private const CURRENCY = "RUB";
private const DAYS = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
public static function graph(array $contacts, string $description, string $street, string $city): array
{
$host = Config::host();
$store = $host . "/#store";
return [
"@context" => "https://schema.org",
"@graph" => [
[
"@type" => "LiquorStore",
"@id" => $store,
"name" => "Vinoteca",
"description" => $description,
"url" => $host . SITE_DIR,
"logo" => $host . SITE_TEMPLATE_PATH . "/assets/brand/vinoteca-icon-512.png",
"image" => $host . SITE_TEMPLATE_PATH . "/assets/media/og-home.jpg",
"telephone" => $contacts["phone"],
"email" => $contacts["email"],
"address" => [
"@type" => "PostalAddress",
"streetAddress" => $street,
"addressLocality" => $city,
"addressCountry" => self::COUNTRY,
],
"openingHoursSpecification" => [[
"@type" => "OpeningHoursSpecification",
"dayOfWeek" => array_map(static fn(string $day): string => "https://schema.org/" . $day, self::DAYS),
"opens" => self::OPENS,
"closes" => self::CLOSES,
]],
"currenciesAccepted" => self::CURRENCY,
"priceRange" => PriceRange::get(),
"sameAs" => [$contacts["telegram"]],
],
[
"@type" => "WebSite",
"@id" => $host . SITE_DIR . "#website",
"url" => $host . SITE_DIR,
"name" => "Vinoteca",
"inLanguage" => LANGUAGE_ID,
],
],
];
}
}