Bitrix получить кол-во элементов в инфоблоке с фильтрами
1 2 3 4 5 6 |
$count = intval(CIBlockElement::GetList(false, [ "IBLOCK_ID" => 5, "PROPERTY_NAME" => 'VALUE', ], ['IBLOCK_ID'])->Fetch()['CNT']); echo $count; |
1 2 3 4 5 6 |
$count = intval(CIBlockElement::GetList(false, [ "IBLOCK_ID" => 5, "PROPERTY_NAME" => 'VALUE', ], ['IBLOCK_ID'])->Fetch()['CNT']); echo $count; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
<?php require $_SERVER["DOCUMENT_ROOT"] . '/bitrix/modules/main/include/prolog_before.php'; if(!CModule::IncludeModule('highloadblock')) die(); global $USER; if(!$USER->IsAdmin()) die(); use Bitrix\Highloadblock as HL; use Bitrix\Main\Entity; $hlblock = HL\HighloadBlockTable::getById(1)->fetch(); $hlEntity = HL\HighloadBlockTable::compileEntity($hlblock); $entDataClass = $hlEntity->getDataClass(); $sTableID = 'tbl_'.$hlblock['TABLE_NAME']; $arFilter = array("!UF_USER_ID" => NULL, "UF_GIFT" => 4, "!UF_DATET" => NULL); //задаете фильтр по вашим полям $rsData = $entDataClass::getList(array( "select" => array('*'), //выбираем все поля "filter" => $arFilter, "limit" => 5000000, "order" => array("UF_DATET"=>"DESC") // сортировка по полю UF_SORT, будет работать только, если вы завели такое поле в hl'блоке )); $rsData = new CDBResult($rsData, $sTableID); while ($arRes = $rsData->Fetch()) { echo $arRes['UF_DATET'] . "<br/>"; } |
Материалы https://dev.1c-bitrix.ru/learning/course/index.php?COURSE_ID=43&CHAPTER_ID=05745&LESSON_PATH=3913.5062.5745 https://thisis-blog.ru/elementi-highload-bloka/ http://julliet.ru/articles/highload-api.html
Хотим сменить фразу
1 |
Контрольная строка, а также ваши регистрационные данные были высланы по E-Mail. Пожалуйста, дождитесь письма, так как контрольная строка изменяется при каждом запросе. |
на
1 |
Ссылка для смены пароля, а также ваши регистрационные данные были высланы по E-Mail. Пожалуйста, дождитесь письма. |
Находится фраза здесь
1 |
/bitrix/modules/main/lang/ru/classes/general/user.php |
Создадим файл
1 |
bitrix/php_interface/user_lang/ru/lang.php |
С переменной
1 |
$MESS["/bitrix/modules/main/lang/ru/classes/general/user.php"]['ACCOUNT_INFO_SENT'] = "Ссылка для смены пароля, а также ваши регистрационные данные были высланы по E-Mail. Пожалуйста, дождитесь письма."; |
Источник: https://dev.1c-bitrix.ru/community/blogs/vad/1560.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 |
<?php /* TODO: Получаем список email активных юзеров и засылаем их в sendpulse */ require($_SERVER["DOCUMENT_ROOT"] . '/bitrix/modules/main/include/prolog_before.php'); // Получаем список email всех активных юзеров global $USER; $filter = Array( "ACTIVE" => "Y", ); $email = Array(); $rsUsers = CUser::GetList(($by = "NAME"), ($order = "desc"), $filter); while ($arUser = $rsUsers->Fetch()) { $phone = $arUser['PERSONAL_PHONE']; $phone = !is_null($phone) ? trim($phone) : null; $fields = [ "email" => $arUser['EMAIL'], "name" => $arUser['NAME'], "phone" => $phone ]; array_push($email, $fields); } $apiKey = 'КЛЮЧ API'; // Массив с исключениями $array = Array( "retailcrm.com", "retailcrm.ru", "sberbank.ru", "matveevs.ru", ); /** * Ищем если совпадение * * @param string $value Искомое значение * @param Array $array Массив исключений * * @return Boolean Результат */ function strposArray($value, $array) { $res = false; foreach ($array as $key) { $res = strpos($value, $key) ? true : $res; } return $res; } // удаляем с исключением покупателей foreach ($email as $key => $value) { if (strposArray($value['email'], $array)) { unset($email[$key]); } } // чистим поля покупателей для подписчиков)) unset($rsUsers, $arUser, $value, $key, $phone, $fields); $emailSub = Array(); // Subscribe CModule::IncludeModule('subscribe'); $rsUsers = CSubscription::GetList(Array(), $filter, false); while ($arUser = $rsUsers->Fetch()) { $fields = [ "email" => $arUser['EMAIL'], ]; array_push($emailSub, $fields); } // удаляем с исключением подписчиков foreach ($emailSub as $key => $value) { if (strposArray($value['email'], $array)) { unset($emailSub[$key]); } } unset($value, $key); function addSubscribe($bookID, $array, $mode = false) { global $apiKey; $query = [ 'list_ids' => $bookID, 'fields[email]' => $array['email'], 'api_key' => $apiKey, 'double_optin' => 3, 'tags' => urlencode("Added using API by positron-it.ru") ]; if ($mode) { $query['fields[Name]'] = $array['name']; $query['fields[phone]'] = $array['phone']; } $ch = curl_init(); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $query); curl_setopt($ch, CURLOPT_TIMEOUT, 10); curl_setopt($ch, CURLOPT_URL, 'https://api.unisender.com/ru/api/subscribe?format=json'); $result = curl_exec($ch); } foreach ($email as $key => $value) { addSubscribe('id книги с покупателями', $value, true); } unset($key, $value); foreach ($emailSub as $key => $value) { addSubscribe('id книги с подписчиками', $value); } |
Парсим элементы
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 |
<?php die('Все спарсили'); require($_SERVER["DOCUMENT_ROOT"] . '/bitrix/modules/main/include/prolog_before.php'); CModule::IncludeModule("iblock"); // инфоблоки function getItems($sql) { $DB = new CDatabase; $DBHost = "localhost"; $DBLogin = "LOGIN к БД MODX"; $DBPassword = "Пароль к БД modx"; $DBName = "имя базы modX"; $DB->Connect($DBHost, $DBName, $DBLogin, $DBPassword); $query = $DB->Query($sql); if ($query->SelectedRowsCount() > 0) { $res = []; while($data = $query->Fetch()) { array_push($res, $data); } return $res; } else if ($query->SelectedRowsCount() == 0) { return false; } $DB->Disconnect(); } function translit($string) { $arTransParams = array( "max_len" => 100, "change_case" => false, "replace_space" => '_', "replace_other" => '-', "delete_repeat_replace" => true, ); $transName = CUtil::translit($string, "ru", $arTransParams); return $transName; } $items = getItems("SELECT * FROM `modx_site_content` where parent = 28"); $el = new CIBlockElement; foreach ($items as $item) { $id = $item['id']; $title = $item['pagetitle']; $desc = $item['description']; $previewText = $item['introtext']; $detailText = $item['content']; $prop = [2 => $id]; $fields = [ "IBLOCK_SECTION_ID" => false, "IBLOCK_ID" => 6, "NAME" => $title, "CODE" => translit($title), "ACTIVE" => "Y", "PROPERTY_VALUES" => $prop, "PREVIEW_TEXT" => $previewText, "DETAIL_TEXT" => $detailText, "IPROPERTY_TEMPLATES" => [ "ELEMENT_META_DESCRIPTION" => $desc ] ]; if ($element = $el->Add($fields)) { echo "New ID: ".$element; } else { echo "Error: ".$el->LAST_ERROR; } echo "<hr/>"; } |
Парсим картинки (Галерею)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
<?php require($_SERVER["DOCUMENT_ROOT"] . '/bitrix/modules/main/include/prolog_before.php'); CModule::IncludeModule("iblock"); // инфоблоки function getItems($sql) { $DB = new CDatabase; $DBHost = "localhost"; $DBLogin = "логин modx"; $DBPassword = "пароль modx"; $DBName = "база modx"; $DB->Connect($DBHost, $DBName, $DBLogin, $DBPassword); $query = $DB->Query($sql); if ($query->SelectedRowsCount() > 0) { $res = []; while($data = $query->Fetch()) { array_push($res, $data); } return $res; } else if ($query->SelectedRowsCount() == 0) { return false; } $DB->Disconnect(); } function galleryImage ($id) { $sql = 'SELECT items.id, items.item, item.filename FROM `modx_gallery_albums` as album LEFT JOIN `modx_gallery_album_items` as items ON items.album = album.id LEFT JOIN `modx_gallery_items` as item ON item.id = items.item where album.name = "album'.$id.'"'; $items = getItems($sql); $arr = []; foreach ($items as $key) { $file = ["VALUE" => CFile::MakeFileArray("/var/www/user/data/www/siteMODX.ru/assets/gallery/" . $key['filename'])]; array_push($arr, $file); } return $arr; } $arSelect = Array("ID", "NAME", "DATE_ACTIVE_FROM", "PROPERTY_ID_GALLERY"); $arFilter = Array("IBLOCK_ID" => 6, "ACTIVE_DATE"=>"Y", "ACTIVE"=>"Y", "PROPERTY_GALLERY" => false); $res = CIBlockElement::GetList(Array(), $arFilter, false, Array("nPageSize" => 500), $arSelect); $el = new CIBlockElement; while($ob = $res->GetNext()) { $elementID = $ob['ID']; $galleryID = $ob['PROPERTY_ID_GALLERY_VALUE']; $images = galleryImage($galleryID); $prop = [ 1 => $images, 2 => $galleryID ]; $fields = [ "PROPERTY_VALUES" => $prop ]; $el->Update($elementID, $fields); } |
#45 строка Можно указать абсолютный путь или внешний url расположение картинки в текущем примере рассмотрен вариант абсолютный путь до изображения (сайт bitrix и modx) находятся на одном сервере
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
/** * Возвращаем секцию элемента, имя и т.д. * * @param integer $id ИД элемента * @param integer $level Уровень раздела * * @return array */ function getSectionElement($id, $level = 2) { CModule::IncludeModule("catalog"); $section = CIBlockSection::GetList( Array(), Array( "DEPTH_LEVEL" => $level, "HAS_ELEMENT" => $id ), false, Array(), Array("nTopCount" => 1) ); $result = Array(); while ($res = $section->GetNext()) { $result = $res; } return $result; } |
bitrix, section, element, section element
Получаем email адрес администратора сайта bitrix
1 2 |
require($_SERVER["DOCUMENT_ROOT"] . '/bitrix/modules/main/include/prolog_before.php'); echo COption::GetOptionString("main", "email_from"); |
У нас есть форма
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<div class="services_form_right"> <form class="services_form" id="paving_and_laying"> <input type="text" name="name" placeholder="Имя"> <input type="email" name="email" placeholder="E-mail"> <input type="tel" name="phone" placeholder="Телефон"> <textarea name="message" placeholder="Комментарий к заказу"></textarea> <div class="box_agree"> <input type="checkbox" name="agree" id="agree" class="checkbox"> <label for="agree" class="check">Даю согласие на обработку персональных данных</label> </div> <div class="services_btn"> <button type="submit" class="btn">Расчитать заказ</button> </div> </form> </div> |
js’ка
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
$("form#paving_and_laying").on('submit', function(event){ event.preventDefault(); form = $(this); $.ajax({ type: "POST", url: "/make.php", data: $(this).serializeArray(), success: function(msg) { json = $.parseJSON(msg); form.find('.requiredInputError').removeClass('requiredInputError'); if (json.result) { form.parent('.services_form_right').addClass('success').html(json.msg); form.remove(); } else { if (json.errors) { json.errors.forEach(function(item) { if (item == 'agree') { form.children('div').children('label').addClass('requiredInputError'); } else if (item == 'message') { form.children('textarea[name="message"]').addClass('requiredInputError'); } else { form.children('input[name="' + item + '"]').addClass('requiredInputError'); } }); } else { alert(json.msg); } } } }); }); |
Файл make.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
<?php $name = $_REQUEST['name']; $email = $_REQUEST['email']; $phone = $_REQUEST['phone']; $message = $_REQUEST['message']; $agree = isset($_REQUEST['agree']); $errors = false; $requiredFields = ['name', 'email', 'phone', 'agree', 'message']; $errorFields = []; // проверяем обязательные поля foreach($requiredFields as $field){ if (!$_REQUEST[$field]){ array_push($errorFields, $field); $errors = true; } } if (!$errors) : $subjectuser = "Сообщение"; $headersuser = "From: Сообщение\r\n"; $headersuser .= "Reply-To: ". strip_tags($name) . "\r\n"; $headersuser .= "MIME-Version: 1.0\r\n"; $headersuser .= "Content-Type: text/html;charset=utf-8 \r\n"; $my_message = "<h1>ТЕМА</h1><br/>"; $my_message .= "Имя: {$name}<br/>"; if ($phone){ $my_message .= "Телефон: {$phone}<br />"; } if ($email){ $my_message .= "E-mail: {$email}<br />"; } if ($message){ $my_message .= "Комментарий: <br>" . $message . "<hr/>"; } $my_message .= "Время заказа: " . date('H:i:s d.m.Y'); require_once($_SERVER['DOCUMENT_ROOT'] . '/include/libs/PHPMailer/class.phpmailer.php'); //Подключаем PHPMailer $mail = new PHPMailer(true); //New instance, with exceptions enabled $mail->CharSet = "UTF-8"; $mail->IsSMTP(); // telling the class to use SMTP $mail->Host = "smtp.yandex.ru"; // SMTP server $mail->SMTPDebug = 0; // enables SMTP debug information (for testing) $mail->SMTPAuth = true; // enable SMTP authentication $mail->Port = 465; // set the SMTP port for the GMAIL server $mail->SMTPSecure = 'ssl'; // Secure SMTP $mail->Username = 'from@matveevs,ru'; // SMTP account username $mail->Password = "fromPassword"; // SMTP account password $mail->SetFrom('from@matveevs,ru', 'site.ru'); $mail->AddReplyTo('from@matveevs,ru','site.ru'); $mail->Subject = "Сообщение с сайта site.ru"; $mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test $mail->MsgHTML($my_message); $address = 'to@matveevs.ru'; $mail->AddAddress($address, "User"); $mail->CharSet="UTF-8"; $mail->IsHTML(true); // send as HTML if(!$mail->Send()) : $res = Array( "result" => false, "msg" => "Ошибка отправления" ); else: $res = Array( "result" => true, "msg" => "Спасибо! Ваша заявка отправлена" ); require $_SERVER["DOCUMENT_ROOT"] . '/addToBitrix.php'; endif; else: $res = Array( "result" => false, "msg" => "Ошибка: заполните все поля формы", "errors" => $errorFields ); endif; echo json_encode($res, JSON_UNESCAPED_UNICODE); |
addToBitrix.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<?php require $_SERVER["DOCUMENT_ROOT"] . '/bitrix/modules/main/include/prolog_before.php'; CModule::IncludeModule("catalog"); $el = new CIBlockElement; $PROP = array( "NAME" => $name, "PHONE" => $phone, "EMAIL" => $email, "MESSAGE" => $message ); $arFields = array( "IBLOCK_ID" => 10, "IBLOCK_SECTION_ID" => false, "NAME" => $name, "PROPERTY_VALUES" => $PROP, "ACTIVE" => "Y", ); $el->Add($arFields); |
1 2 3 4 5 6 7 8 |
<? $APPLICATION->IncludeComponent("bitrix:main.include","",Array( "AREA_FILE_SHOW" => "file", "PATH" => SITE_TEMPLATE_PATH."/include/header.php", "EDIT_TEMPLATE" => "standard.php" ) ); ?> |
Документация
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
<?$APPLICATION->IncludeComponent( "bitrix:news.list", "slider-main", array( "ACTIVE_DATE_FORMAT" => "d.m.Y", "ADD_SECTIONS_CHAIN" => "Y", "AJAX_MODE" => "N", "AJAX_OPTION_ADDITIONAL" => "", "AJAX_OPTION_HISTORY" => "N", "AJAX_OPTION_JUMP" => "N", "AJAX_OPTION_STYLE" => "Y", "CACHE_FILTER" => "N", "CACHE_GROUPS" => "Y", "CACHE_TIME" => "36000000", "CACHE_TYPE" => "A", "CHECK_DATES" => "Y", "DETAIL_URL" => "", "DISPLAY_BOTTOM_PAGER" => "Y", "DISPLAY_DATE" => "Y", "DISPLAY_NAME" => "Y", "DISPLAY_PICTURE" => "Y", "DISPLAY_PREVIEW_TEXT" => "Y", "DISPLAY_TOP_PAGER" => "N", "FIELD_CODE" => array( 0 => "DETAIL_TEXT", 1 => "", ), "FILTER_NAME" => "", "HIDE_LINK_WHEN_NO_DETAIL" => "N", "IBLOCK_ID" => "4", "IBLOCK_TYPE" => "banner", "INCLUDE_IBLOCK_INTO_CHAIN" => "Y", "INCLUDE_SUBSECTIONS" => "Y", "MESSAGE_404" => "", "NEWS_COUNT" => "5", "PAGER_BASE_LINK_ENABLE" => "N", "PAGER_DESC_NUMBERING" => "N", "PAGER_DESC_NUMBERING_CACHE_TIME" => "36000", "PAGER_SHOW_ALL" => "N", "PAGER_SHOW_ALWAYS" => "N", "PAGER_TEMPLATE" => ".default", "PAGER_TITLE" => "Новости", "PARENT_SECTION" => "", "PARENT_SECTION_CODE" => "", "PREVIEW_TRUNCATE_LEN" => "", "PROPERTY_CODE" => array( 0 => "LINK", 1 => "ICON", 2 => "", ), "SET_BROWSER_TITLE" => "N", "SET_LAST_MODIFIED" => "N", "SET_META_DESCRIPTION" => "N", "SET_META_KEYWORDS" => "N", "SET_STATUS_404" => "N", "SET_TITLE" => "N", "SHOW_404" => "N", "SORT_BY1" => "SORT", "SORT_BY2" => "ACTIVE_FROM", "SORT_ORDER1" => "ASC", "SORT_ORDER2" => "DESC", "STRICT_SECTION_CHECK" => "N" ), false );?> |
Документация