Семь, полсотни три

Заметки о дизайне, вёрстке, программировании и администрировании сайтов и линукса.

Текущие свойства заказа (отфильтрованные по типу пользователя, доставке и оплате)

<?php
/**
 * @param {int} $personType
 * @param {int} $deliveryId
 * @param {int} $paymentId
 * 
 * @var {array} $orderPropList
 */
$sqlIsOk = <<<SQL
IF (
    ISNULL(GROUP_CONCAT(DISTINCT %s SEPARATOR '|'))
    ,1-- all entities
    ,IF (
        INSTR(
            CONCAT('|', GROUP_CONCAT(DISTINCT %s SEPARATOR '|'), '|')
            ,'|{{entityId}}|'
        )
        ,1-- entity: ok
        ,0-- entity: fail
    )
)
SQL;
$orderPropList = \Bitrix\Sale\Internals\OrderPropsTable::getList([
    'select' => [
        'ID', 'NAME'
        ,new \Bitrix\Main\ORM\Fields\ExpressionField(
            'dr:ok'
            ,str_replace('{{entityId}}', $deliveryId, $sqlIsOk)
            ,['DR.ENTITY_ID', 'DR.ENTITY_ID']
        )
        ,new \Bitrix\Main\ORM\Fields\ExpressionField(
            'pr:ok'
            ,str_replace('{{entityId}}', $paymentId, $sqlIsOk)
            ,['PR.ENTITY_ID', 'PR.ENTITY_ID']
        )
    ],
    'filter' => [
        'PERSON_TYPE_ID' => $personType,
        'ACTIVE' => 'Y',
        'dr:ok' => true,
        'pr:ok' => true,
    ],
    'group' => ['ID'],
    'runtime' => [
        'DR' => [
            'data_type' => '\Bitrix\Sale\Internals\OrderPropsRelationTable',
            'reference' => [
                '=ref.ENTITY_TYPE' => new \Bitrix\Main\Db\SqlExpression('?s' , 'D'),
                '=ref.PROPERTY_ID' => 'this.ID',
            ],
        ],
        'PR' => [
            'data_type' => '\Bitrix\Sale\Internals\OrderPropsRelationTable',
            'reference' => [
                '=ref.ENTITY_TYPE' => new \Bitrix\Main\Db\SqlExpression('?s' , 'P'),
                '=ref.PROPERTY_ID' => 'this.ID',
            ],
        ],
    ],
])->fetchAll();
$orderPropList = array_column($orderPropList, 'ID');

Маска телефона (`BX.maskedInput`) в оформлении заказа (`bitrix:sale.order.ajax`)

Для добавления маски телефона в оформление заказа (`bitrix:sale.order.ajax`) необходимо: собственно, добавить маску; и настроить валидацию.
 
Для этого необходимо отредактировать файл со скриптами в шаблоне оформления заказа `order_ajax.js` (1, 2) и языковой файл`lang/ru/template.php`.

1. инициализация `BX.maskedInput` поля

В методе `alterProperty` код:

if (settings.IS_PHONE == 'Y') {
	textNode.setAttribute('autocomplete', 'tel');
}

… заменить на:

if (settings.IS_PHONE == 'Y') {
	textNode.setAttribute('autocomplete', 'tel');
	/*--- phone (w/ BX.maskedInput) initialization ---begin-*/
	let value = textNode.value.substring(1);
	let result = new BX.MaskedInput({
		mask: '+7 (999) 999 99 99',
		input: textNode,
		placeholder: '_'
	}).setValue(value);
	textNode._masked = {prefix: '7', length: 10};// used in validation
	//- 'change' event for `BX.maskedInput`
	textNode.addEventListener('focus', function(evnt){ this._value = this.value; });
	textNode.addEventListener('blur', function(evnt)
	{ 
		if (this._value !== this.value) {
			this.dispatchEvent(new Event('change'));
		}
		delete this._value;
	});
	/*--- phone (w/ BX.maskedInput) initialization ---end-*/
}

2. валидация `BX.maskedInput` поля

В методе `validateString`…
(1) код:

if (arProperty.REQUIRED == 'Y' && value.length == 0)

… заменить на:

/*--- phone (w/ BX.maskedInput) validation, p.1 ---begin-*/
if ('Y' === arProperty.IS_PHONE && !!input._masked) {
	value = value.replace(/\D/g, '').replace(new RegExp('^'+input._masked.prefix), '');
}
/*--- phone (w/ BX.maskedInput) validation, p.1 ---end-*/

if (arProperty.REQUIRED == 'Y' && value.length == 0)

(2) код:

if (value.length > 0 && arProperty.IS_EMAIL == 'Y')

…заменить на:

/*--- phone (w/ BX.maskedInput) validation, p.2 ---begin-*/
if (
	'Y' === arProperty.IS_PHONE && !!input._masked
	&& value.length !== input._masked.length
) {
	errors.push(BX.message('SOA_INVALID_PHONE'));
}
/*--- phone (w/ BX.maskedInput) validation, p.2 ---end-*/

if (value.length > 0 && arProperty.IS_EMAIL == 'Y')

3. текст сообщения об ошибке

В языковом файле код:

$MESS["SOA_INVALID_EMAIL"] = "Введен неверный e-mail";

…заменить на:

$MESS["SOA_INVALID_PHONE"] = "Введен неверный номер телефона";
$MESS["SOA_INVALID_EMAIL"] = "Введен неверный e-mail";

Битрикс: случайные числа

RandomSequence
Класс для генерации псевдослучайных последовательностей. Не использовать для любых криптографических или защитных целей.
использовать для генерации id-шников
RandomSequence
примеры использования:

<?php
$randSeq = new \Bitrix\Main\Type\RandomSequence(microtime());
foreach ($list as $item) {
	$indx = sprintf('%04d', $randSeq->rand($min=0, $max=9999));
	// <…>
}
<?php
$randSeq = new \Bitrix\Main\Type\RandomSequence(microtime());
foreach ($list as $item) {
	$id = 'id-'.$randSeq->randString($strLen=4);
	// <…>
}

Random
генератор случайных чисел
криптобезопасный, использовать для паролей и всего, что относится к безопасности
Random

<?php
$codeCheck = sprintf('%06d', \Bitrix\Main\Security\Random::getInt($min=0, $max=999999));

Percent resource usage for critical and almost critical

Atop man-page

For the resource consumption on system level, atop uses colors to indicate that a critical occupation percentage has been (almost) reached. A critical occupation percentage means that is likely that this load causes a noticeable negative performance influence for applications using this resource. The critical percentage depends on the type of resource: e. g. the performance influence of a disk with a busy percentage of 80% might be more noticeable for applications/user than a CPU with a busy percentage of 90%. Currently atop uses the following default values to calculate a weighted percentage per resource:

Processor
A busy percentage of 90% or higher is considered ‘critical’.
Disk
A busy percentage of 70% or higher is considered ‘critical’.
Network
A busy percentage of 90% or higher for the load of an interface is considered ‘critical’.
Memory
An occupation percentage of 90% is considered ‘critical’. Notice that this occupation percentage is the accumulated memory consumption of the kernel (including slab) and all processes; the memory for the page cache (‘cache’ and ‘buff’ in the MEM-line) and the reclaimable part of the slab (‘slrec‘) is not implied!
If the number of pages swapped out (‘swout’ in the PAG-line) is larger than 10 per second, the memory resource is considered ‘critical’. A value of at least 1 per second is considered ‘almost critical’. If the committed virtual memory exceeds the limit (‘vmcom’ and ‘vmlim’ in the SWP-line), the SWP-line is colored due to overcommitting the system.
Swap
An occupation percentage of 80% is considered ‘critical’ because swap space might be completely exhausted in the near future; it is not critical from a performance point-of-view. These default values can be modified in the configuration file (see separate man-page of atoprc). When a resource exceeds its critical occupation percentage, the concerning values in the screen line are colored red by default.

When a resource exceeded (default) 80% of its critical percentage (so it is almost critical), the concerning values in the screen line are colored cyan by default. This ‘almost critical percentage’ (one value for all resources) can be modified in the configuration file (see separate man-page of atoprc). The default colors red and cyan can be modified in the configuration file as well (see separate man-page of atoprc).

With the key ’x’ (or flag −x), the use of colors can be suppressed.

Переменные шаблона

component.php

<?php
/**
 * @var {array} $arParams
 * @var {array} $arResult
 * @var {string} $componentPath
 * @var {string} $componentName
 * @var {string} $componentTemplate
 * @var {CBitrixComponent} $this
 * @global {CMain} $APPLICATION
 * @global {CUser} $USER
 * @global {CDatabase} $DB
 **/

if (!defined('B_PROLOG_INCLUDED') || B_PROLOG_INCLUDED !== true) die();

template.php

https://dev.1c-bitrix.ru/learning/course/index.php?COURSE_ID=43&LESSON_ID=2829&LESSON_PATH=3913.4565.2829

<?php
/**
 * @var {array} $arParams – массив входящих параметров компонента
 * @var {array} $arResult – массив результатов работы компонента
 * @var {array} $templateData — массив данных (передача данных из template.php в файл component_epilog.php)
 * @var {array} $arLangMessages – массив языковых сообщений шаблона
 * @var {string} $templateFile – путь к шаблону относительно корня сайта
 * @var {string} $templateFolder – путь к папке с шаблоном от DOCUMENT_ROOT
 * @var {string} $parentTemplateFolder – путь относительно корня сайта к папке шаблона комплексного
 *                                     компонента, в составе которого подключается данный компонент
 * @var {string} $templateName — имя шаблона компонента
 * @var {string} $componentPath — путь к папке с компонентом от DOCUMENT_ROOT
 * @var {CBitrixComponent} $component — ссылка на текущий вызванный компонент
 * @var {CBitrixComponentTemplate} $this — ссылка на текущий шаблон
 * @global {CMain} $APPLICATION
 * @global {CUser} $USER
 * @global {CDatabase} $DB
 */

if (!defined('B_PROLOG_INCLUDED') || B_PROLOG_INCLUDED !== true) die();

use \Bitrix\Main\Localization\Loc;

$this->setFrameMode(true);
?>

component_epilog.php

https://dev.1c-bitrix.ru/learning/course/index.php?COURSE_ID=43&LESSON_ID=2975

<?php
/**
 * @var {array} $arParams — массив входящих параметров компонента
 * @var {array} $arResult — массив результатов работы компонента
 * @var {array} $templateData — массив данных (передача данных из template.php в файл component_epilog.php)
 * @var {string} $componentPath — путь к папке с компонентом от DOCUMENT_ROOT
 * @var {string} $epilogFile — путь к файлу component_epilog.php относительно DOCUMENT_ROOT
 * @var {string} $templateName - имя шаблона компонента
 * @var {string} $templateFile — путь к файлу шаблона от DOCUMENT_ROOT
 * @var {string} $templateFolder — путь к папке с шаблоном от DOCUMENT_ROOT
 * @var {CBitrixComponent} $component — ссылка на $this
 * @var {CBitrixComponent} $this — ссылка на текущий вызванный компонент
 * @global {CMain} $APPLICATION
 * @global {CUser} $USER
 * @global {CDatabase} $DB
 */

if (!defined('B_PROLOG_INCLUDED') || B_PROLOG_INCLUDED !== true) die();

use \Bitrix\Main\Localization\Loc;
?>

result_modifier.php

https://dev.1c-bitrix.ru/learning/course/index.php?COURSE_ID=43&LESSON_ID=2829&LESSON_PATH=3913.4565.2829#variables

<?php
/**
 * @var {array} $arParams — массив входящих параметров (НЕ затрагивает компонент)
 * @var {array} $arResult — массив результатов работы компонента (затрагивает компонент)
 * @var {CBitrixComponentTemplate} $this — ссылка на текущий вызванный компонент
 * @global {CMain} $APPLICATION
 * @global {CUser} $USER
 * @global {CDatabase} $DB
 */

if (!defined('B_PROLOG_INCLUDED') || B_PROLOG_INCLUDED !== true) die();

use \Bitrix\Main\Localization\Loc;
?>

element.php, detail.php, news.php…

<?php
/**
 * @var {array} $arParams – массив входящих параметров компонента
 * @var {array} $arResult – массив результатов работы компонента
 * @var {string} $templateFile – путь к шаблону относительно корня сайта
 * @var {string} $templateFolder – путь к папке с шаблоном от DOCUMENT_ROOT
 * @var {string} $templateName — имя шаблона компонента
 * @var {string} $componentPath — путь к папке с компонентом от DOCUMENT_ROOT
 * @var {CBitrixComponent} $component — ссылка на текущий вызванный компонент
 * @var {CBitrixComponentTemplate} $this — ссылка на текущий шаблон
 * @global {CMain} $APPLICATION
 * @global {CUser} $USER
 * @global {CDatabase} $DB
 */

if (!defined('B_PROLOG_INCLUDED') || B_PROLOG_INCLUDED !== true) die();

use \Bitrix\Main\Localization\Loc;

$this->setFrameMode(true);
?>

functions.php… (included in template.php)

<?php
namespace MA\Custom;
/**
 * include in template.php
 * @var {array} $arParams – массив входящих параметров компонента
 * @var {array} $arResult – массив результатов работы компонента
 * @var {array} $templateData — массив данных (передача данных из template.php в файл component_epilog.php)
 * @var {array} $arLangMessages – массив языковых сообщений шаблона
 * @var {string} $templateFile – путь к шаблону относительно корня сайта
 * @var {string} $templateFolder – путь к папке с шаблоном от DOCUMENT_ROOT
 * @var {string} $parentTemplateFolder – путь относительно корня сайта к папке шаблона комплексного
 *                                     компонента, в составе которого подключается данный компонент
 * @var {string} $templateName — имя шаблона компонента
 * @var {string} $componentPath — путь к папке с компонентом от DOCUMENT_ROOT
 * @var {CBitrixComponent} $component — ссылка на текущий вызванный компонент
 * @var {CBitrixComponentTemplate} $this — ссылка на текущий шаблон
 * @global {CMain} $APPLICATION
 * @global {CUser} $USER
 * @global {CDatabase} $DB
 */

// if (!defined('B_PROLOG_INCLUDED') || B_PROLOG_INCLUDED !== true) die();

use \Bitrix\Main\Localization\Loc;

.{{menuType}}.menu_ext.php

<?php
/**
 * @global {CMain} $APPLICATION
 * @global {CUser} $USER
 * @global {CDatabase} $DB
 */

if (!defined('B_PROLOG_INCLUDED') || B_PROLOG_INCLUDED !== true) die();

Управление версиями snap программ

Получение всех установленных в системе версия приложения

snap list opera --all

где вместо opera надо указать название приложения
получится результат:


Name   Version        Rev  Tracking       Publisher        Notes
opera  73.0.3856.344  106  latest/stable  opera-software✓  disabled
opera  74.0.3911.75   107  latest/stable  opera-software✓  -

где в колонке Rev будут номера версий (ревизии)

выбрать нужную версию приложения (ревизию) можно командой:

sudo snap revert opera --revision 106

где вместо

opera

надо указать название приложения,
а вместо 106 — номер ревизии

чтобы откатится до предыдущей версии необходимо выполнить команду:

sudo snap revert opera

где вместо opera надо указать название приложения,

Ранее Ctrl + ↓