Vinoteca: wine shop on 1C-Bitrix (module, template, components, pages)

This commit is contained in:
jimagie committed 2026-10-22 23:22:27 +05:00
commit 52795535ae
586 files changed
+27619

No files matched your search

@@ -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(),
];
}
}