|
Ok!
|
|
|
Ok!
|
---|---|---|---|---|
319 | # Удаляем index.php из адреса RewriteCond %{THE_REQUEST} ^GET.*index.php [NC] # Не применяем к админке, иначе перестает работать страница Highload-блоки RewriteCond %{REQUEST_URI} !/bitrix/admin/.* [NC] RewriteCond %{REQUEST_URI} !^/bitrix/tools/ [NC] RewriteRule (.*?)index.php/*(.*) https://%{HTTP_HOST}/$1$2 [R=301,NE,L] | htaccess, rewrite, bitrix | 395 | Удалить index.php из УРЛ редиректом, кроме админки Битрикс |
316 | 'cache' => array( 'value' => array ( 'type' => 'memcache', 'memcache' => array( 'host' => 'localhost', 'port' => '11211' ), 'sid' => $_SERVER["DOCUMENT_ROOT"]."#01" ), ), | memcached, bitrix | 300 | настройка memcached в bitrix в файле .settings.php |
314 | $ipropValues = new BitrixIblockInheritedPropertyElementValues( $arParams['IBLOCK_ID'], $arResult["ID"] ); $arResult["IPROPERTY_VALUES"] = $ipropValues->getValues(); | meta values, bitrix | 28005 | Получить в Битрикс метаданные элемента |
313 | // определим константу LOG_FILENAME, в которой зададим путь к лог-файлу define("LOG_FILENAME", $_SERVER["DOCUMENT_ROOT"]."/mylog-6665444.txt"); //дебаг почты function custom_mail($to, $subject, $message, $additional_headers='', $additional_parameters='') { AddMessage2Log( 'To: '.$to.PHP_EOL. 'Subject: '.$subject.PHP_EOL. 'Message: '.$message.PHP_EOL. 'Headers: '.$additional_headers.PHP_EOL. 'Params: '.$additional_parameters.PHP_EOL ); if ($additional_parameters!='') { return @mail($to, $subject, $message, $additional_headers, $additional_parameters); } else { return @mail($to, $subject, $message, $additional_headers); } } | mail, php, log, bitrix | 19005 | mail log bitrix |
310 | CFile::ShowImage($img, $width, $height); | bitrix, img, image, битрикс, изображение | 460 | Как вывести в Битрикс картинку по размерам. $img - ID картинки или путь к файлу |
308 | system('tail -n 100 /home/bitrix/.msmtprc') | почта, bitrixvm, log mail | 300 | Посмотреть в php строке Битрикс лог почты |
306 | <div><?=(new CBXSanitizer)->sanitizeHtml($foo);?></div> $login = $DB->ForSql($_REQUEST['login']); $res = $DB->Query("SELECT * FROM b_user WHERE LOGIN='$login'"); $arInsert = $DB->PrepareInsert("b_user", ["LOGIN" => $_REQUEST["login"]]); $sql = "INSERT INTO b_user (".$arInsert[0].") VALUES (".$arInsert[1].")"; $res = $DB->Query($sql); | sanitize, bitrix | 100 | Обработать переменную в Битрикс |
304 | $assetManager->addJs( "https://cdn.ampproject.org/v0.js"); | amp, bitrix | 30090 | Скрипт загрузки АМП |
283 | CJSCore::Init(['masked_input']); | maskedinput, bitrix, Битрикс, маска | 1290 | Аналог maskedinput в Битрикс |
274 | if (!defined('B_PROLOG_INCLUDED') || B_PROLOG_INCLUDED !== true) die(); use BitrixMainDataCache; $elems = []; $cash_key = md5("hdgbchdch383787lkokcodcjj8773asas_"); $cache = Cache::createInstance(); // получаем экземпляр класса if ($cache->initCache(360000, $cash_key)) { // проверяем кеш и задаём настройки $elems = $cache->getVars(); // достаем переменные из кеша } elseif ($cache->startDataCache()) { ...вычисления $cache->endDataCache($elems); // записываем в кеш } | cache, bitrix, кеширование | 23600 | Кеширование блоков в битрикс |
273 | function webpImage($source, $quality = 100, $removeOld = false) { if(strpos('http', $source) !== false) { //define scheme $scheme = CMain::IsHTTPS() ? "https" : "http"; // http //replace http://server with nothing $source = str_replace([$scheme . '://'. $_SERVER['HTTP_HOST']], [""], $source); } if(strpos('http', $source) === false) { $source = '/home/bitrix/www' . $source; } $dir = pathinfo($source, PATHINFO_DIRNAME); $name = pathinfo($source, PATHINFO_FILENAME); $destination = $dir . DIRECTORY_SEPARATOR . $name . '.webp'; $info = getimagesize($source); $isAlpha = false; echo $info['mime']; if ($info['mime'] == 'image/jpeg'){ $image = imagecreatefromjpeg($source); echo $source; var_dump($image); } elseif ($isAlpha = $info['mime'] == 'image/gif') { $image = imagecreatefromgif($source); } elseif ($isAlpha = $info['mime'] == 'image/png') { $image = imagecreatefrompng($source); } else { return $source; } if ($isAlpha) { imagepalettetotruecolor($image); imagealphablending($image, true); imagesavealpha($image, true); } imagewebp($image, $destination, $quality); imagedestroy($image); if ($removeOld) unlink($source); return $destination; } | webp, convert image, bitrix | 10900 | Функция для Битрикс конвертации картинок в webp |
268 | $pdf = new CSalePdf('P', 'pt', 'A4'); print_r( $pdf ); | pdf, bitrix | 170 | В Битрикс сделать ПДФ pdf |
253 | $iterator = CIBlockElement::GetList( array("ID"=>"DESC"), array('IBLOCK_ID' => 26, '=ACTIVE' => 'Y', 'IBLOCK_SECTION_ID', ['LOGIC' => 'OR', 'PREVIEW_TEXT' => false, 'DETAIL_TEXT' => false]), false, false, array('ID', 'NAME', 'CODE', 'IBLOCK_SECTION_ID') ); while($item = $iterator->Fetch()) { $was_id = 0; $nav = CIBlockSection::GetNavChain(false, $item['IBLOCK_SECTION_ID'], array(), false); $url = ""; while($nav->Fetch()){ if($was_id != $item['ID']){ $url_length = count($nav->arResult); $url .= $nav->arResult[$url_length - 1]['CODE'] . "/"; echo $item['ID'] . ';"' . $item['NAME'] . '";"https://lamaree.ru/catalog/' . $url . $item['CODE'] . '/"' . " "; $was_id = $item['ID']; } } } | url, bitrix, catalog | 980 | Выбрать из каталога Битрикс товары без описаний с URL |
238 | "SECTION_URL" => $arResult["FOLDER"].$arResult["URL_TEMPLATES"]["section"], | bitrix, catalog.section.list | 500 | Путь секции для catalog.section.list |
236 | //ADD SECTION CANONICAL URL $canonicalScheme = CMain::IsHTTPS() ? "https" : "http"; $APPLICATION->AddHeadString('<link rel="canonical" href="' . $canonicalScheme . '://' . SITE_SERVER_NAME . $arCurSection["PATH"][$arCurSection["ID"]]["SECTION_PAGE_URL"] . '" />', true); | bitrix, section | 9008 | ADD SECTION CANONICAL URL |
232 | if(preg_match('/[A-Z]/', $_SERVER['REQUEST_URI'])){ LocalRedirect(strtolower($_SERVER['REQUEST_URI']), 0, "301 Moved permanently"); } | bitrix, редирект, localredirect | 9000 | Битрикс редирект в обход htaccess с заглавных букв в УРЛ на маленькие |
231 | $scheme = CMain::IsHTTPS() ? "https" : "http"; | https, bitrix | 9090 | Определить https в Битрикс |
223 | public function convertImage(&$content) { if (defined('ADMIN_SECTION') || defined('WIZARD_SITE_ID')) { return; } preg_match_all('/"(/upload/[^"]*.(jpg|jpeg|png))"/i', $content, $matches1); self::convertImageToWebp($content, $matches1); preg_match_all("/'(/upload/[^']*.(jpg|jpeg|png))'/i", $content, $matches2); self::convertImageToWebp($content, $matches2); } private static function convertImageToWebp(&$content, $matches) { if (!empty($matches[1])) { foreach ($matches[1] as $i => $imageUrl) { $root = $_SERVER['DOCUMENT_ROOT']; $type = $matches[2][$i]; $newName = str_replace($type, 'webp', $imageUrl); if (file_exists($root . $newName)) { $content = str_replace($imageUrl, $newName, $content); continue; } if (!file_exists($root . $imageUrl)) { continue; } $type = strtolower($type); switch ($type) { case 'jpeg': case 'jpg': $img = imagecreatefromjpeg($root . $imageUrl); break; case 'png': $img = imagecreatefrompng($root . $imageUrl); imagepalettetotruecolor($img); imagealphablending($img, true); imagesavealpha($img, true); break; } if (isset($img)) { $result = imagewebp($img, $root . $newName, 75); if (!$result) { continue; } $content = str_replace($imageUrl, $newName, $content); imagedestroy($img); unset($img); } } } } | bitrix, webp, convert | 20030 | convert image to webp bitrix |
200 | "CUSTOM_FILTER" => "{"CLASS_ID":"CondGroup","DATA":{"All":"AND","True":"True"},"CHILDREN":[{"CLASS_ID":"CondIBSection","DATA":{"logic":"Equal","value":995}}]}", | custom filter, bitrix | 100 | Пример заполнения custom_filter в Битрикс |
149 | <?$APPLICATION->IncludeFile(SITE_DIR."catalog/sidebar_".$arResult['ID'].".php",Array(),Array("MODE"=>"php"));?> | include, bitrix, включаемая область | 120 | Включаемая область |
148 | $arFilter = Array("IBLOCK_ID"=>GOODS, "ACTIVE_DATE"=>"Y", "ACTIVE"=>"Y", "=PROPERTY_CML2_ARTIKUL_VALUE"=>$p_title); | bitrix filter value, filter bx, value | 1290 | Свойство элемента в Битрикс фильтре |
144 | $iterator = CIBlockElement::GetList( array(), array('IBLOCK_ID' => 2, '=AVAILABLE' => 'Y', '=TYPE' => 1, '>=PRICE' => 100, '<=PRICE' => 200, 'CURRENCY_FOR_SCALE' => 'USD'), false, false, array('ID', 'NAME', 'IBLOCK_ID') ); | итератор, iterator bitrix, iterator | 140 | Выборка элементов Битрикс из каталога или другого инфоблока. Итерация. |
142 | array("LOGIC"=>"OR","NAME"=>$q,"PREVIEW_TEXT"=>$q, "PROPERTY_CML2_ARTIKUL"=>$q), | фильтр с логикой, логика, битрикс, bitrix, logic | 500 | Фильтр с логикой в Битрикс |
131 | <? $APPLICATION->IncludeFile( SITE_TEMPLATE_PATH . "/bespl_kons.php", Array(), Array( "MODE" => "html" ) ); ?> | include, bitrix, включаемая область | 90 | Вставка включаемой области из html файла в Битрикс |
122 | $component = new CBitrixComponent(); $component->InitComponent('redesign:menu', 'mobile'); $component->initComponentTemplate(); $path = $component->__template->GetFolder(); | путь к компоненту, битрикс, bitrix | 120 | Путь к шаблону компонента в папке components |
105 | <a id="ajaxaction=add&ajaxaddid=<?=$ar_fields['ID'];?>" rel="nofollow" class="catalog-item-buy input-basket-submit" href="?action=ADD2BASKET&id=<?=$ar_fields['ID'];?>">В корзину</a> | bitrix, в корзину | 560 | Код кнопки добавления в корзину итрикс |
101 | /bitrix/modules/main/include.php replace OLDSITEEXPIREDATE by (exmpl) time() + 86400 * 3 | bitrix | 100 | replace old site expire date |
79 | <?if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true)die(); $widthPreview = 300; $heightPreview = 200; $widthPreviewBig = 300*2; $heightPreviewBig = 200*2; foreach($arResult['ITEMS'] as $i => $arItem) { $file = CFile::ResizeImageGet($arItem['FIELDS']["DETAIL_PICTURE"]['ID'], array('width' => $widthPreviewBig, 'height' => $heightPreviewBig), BX_RESIZE_IMAGE_EXACT, true); $arResult['ITEMS'][$i]["FIELDS"]["DETAIL_PICTURE"]["SRC"] = $file["src"]; $arResult['ITEMS'][$i]["FIELDS"]["DETAIL_PICTURE"]["WIDTH"] = $file["width"]; $arResult['ITEMS'][$i]["FIELDS"]["DETAIL_PICTURE"]["HEIGHT"] = $file["height"]; $file = CFile::ResizeImageGet($arItem["PREVIEW_PICTURE"]['ID'], array('width' => $widthPreview, 'height' => $heightPreview), BX_RESIZE_IMAGE_EXACT, true); $arResult['ITEMS'][$i]["PREVIEW_PICTURE"]["SRC"] = $file["src"]; $arResult['ITEMS'][$i]["PREVIEW_PICTURE"]["WIDTH"] = $file["width"]; $arResult['ITEMS'][$i]["PREVIEW_PICTURE"]["HEIGHT"] = $file["height"]; } | resizeImageGet, resize, bitrix | 2300 | Ресайз |
76 | <?if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true)die(); use BitrixIblock; $sectionsID = array(); foreach ($arResult["ITEMS"] as $arItem) { if ($arItem["IBLOCK_SECTION_ID"]) { $sectionsID[] = $arItem["IBLOCK_SECTION_ID"]; } } $sectionsID = array_unique($sectionsID); $result = IblockSectionTable::getList(array( "select" => array( "ID", "NAME", ), "filter" => array( "ID" => $sectionsID, "IBLOCK_ID" => $arResult["IBLOCK_ID"], ), )); $arResult["SECTIONS"] = array(); while ($row = $result->fetch()) { $arResult["SECTIONS"][$row["ID"]] = $row; } | sections, bitrix, sections by id | 120 | Выбор секций каталога Битрикс по ID элемента |
75 | $widthPreview = 200; $heightPreview = 200; if ($arResult["DETAIL_PICTURE"]) { $file = CFile::ResizeImageGet($arResult["DETAIL_PICTURE"], array('width'=> $widthPreview, 'height'=> $heightPreview), BX_RESIZE_IMAGE_EXACT, true); $arResult["PREVIEW_PICTURE"]["SRC"] = $file["src"]; $arResult["PREVIEW_PICTURE"]["WIDTH"] = $file["width"]; $arResult["PREVIEW_PICTURE"]["HEIGHT"] = $file["height"]; } elseif($arResult["PREVIEW_PICTURE"]) { $file = CFile::ResizeImageGet($arItem["PREVIEW_PICTURE"], array('width'=> $widthPreview, 'height'=> $heightPreview), BX_RESIZE_IMAGE_EXACT, true); $arResult["PREVIEW_PICTURE"]["SRC"] = $file["src"]; $arResult["PREVIEW_PICTURE"]["WIDTH"] = $file["width"]; $arResult["PREVIEW_PICTURE"]["HEIGHT"] = $file["height"]; } | resizeImageGet, resize, bitrix | 250 | result_modifier для кеширования и ресайза картинок |
45 | <? $str = "1234567890"; echo TruncateText($str, 7); // результатом будет строка "1234567..." ?> | bitrix, truncate, text, truncate text | 3100 | Обрезка текста в Битрикс |
17 | if($arParams["PREVIEW_TRUNCATE_LEN"] > 0 && strlen($arItem["PREVIEW_TEXT"])>5) $arItem["PREVIEW_TEXT"] = $obParser->html_cut($arItem["PREVIEW_TEXT"], $arParams["PREVIEW_TRUNCATE_LEN"]); | truncate, bitrix, prewiew text | 400 | Функция Битрикс для обрезки превью текста, если обрезка автоматически не работает |
12 | $items_sel = (new CIBlockElement())->GetList([], $filter, 0, 0, ['ID']); $arResult['ITEMS_SELECTED'] = $items_sel->SelectedRowsCount(); if(!$arResult['ITEMS_SELECTED']) $ids = []; else while($item = $items_sel->Fetch()) $ids[] = $item['ID']; | select, iblock, bitrix | 100 | Выбор айблоков в Битрикс |