box's People
box's Issues
Обрізка тексту
$tmpText = strip_tags($arItem['DETAIL_TEXT']);
$length = $arParams['TR_TEXT'];
$tmpText = substr($tmpText, 0, $length);
$arItem['TEXT'] = substr($tmpText, 0, strrpos($tmpText, ' ') ) . '...';
minprice
` public function setOffers(array $offers = [])
{
$this->offers = [
'all' => [],
'minPrice' => false
];
if(!empty($offers))
{
$offer = current($offers);
$offer = array_reduce($offers, function(Offer $offer, Offer $o)
{
if(($o->getPrice() < $offer->getPrice()))
{
$offer = $o;
}
return $offer;
}, $offer);
$this->offers['all'] = $offers;
$this->offers['minPrice'] = $offer;
}
return $this;
}`
siteURL
public static function siteURL()
{
$protocol = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') ||
$_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
$domainName = $_SERVER['SERVER_NAME'];
return $protocol.$domainName;
}
пароль для
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/classes/general/backup.php");
$backup_secret_key = CPasswordStorage::Get('dump_temporary_cache');
echo "<pre>";print_r($backup_secret_key);echo "</pre>";
Очистка
`<?php
//rename("index.php", "restore.php");
/* удалить базу*/
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/php_interface/dbconn.php");
if (!mysql_connect($DBHost, $DBLogin, $DBPassword)) {
print 'Could not connect to mysql';
exit;
}
$result = mysql_list_tables($DBName);
if (!$result) {
print "DB Error, could not list tables\n";
print 'MySQL Error: ' . mysql_error();
exit;
}
$arTable= array();
while ($row = mysql_fetch_row($result)) {
$arTable[]= $row[0];
print "Table: $row[0]\n";
}
mysql_free_result($result);
unset ($result);
if (count($arTable)>0){
$query="DROP TABLE ".implode(', ',$arTable);
if(mysql_connect($DBHost, $DBLogin, $DBPassword)){echo('good');}else{echo('bad');}
$result = mysql_query($query) or die ("Не возможно удалить таблицы");
mysql_free_result($result);
}
echo "Все Таблицы БД удалены - ".$result;
rrmdir(".");
//Another simple way to recursively delete a directory that is not empty:
function rrmdir($dir) {
if (is_dir($dir)) {
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object != "." && $object != "..") {
if ( $object=='clear.php') continue;
if (filetype($dir."/".$object) == "dir") rrmdir($dir."/".$object); else unlink($dir."/".$object);
}
}
reset($objects);
rmdir($dir);
}
}
?>`
onAdd highload
$handler = $eventManager->addEventHandler( "", "WISHOnBeforeAdd", array( "Webvision\\Promodo\\Observers\\Wishlist", "OnAdd" ) );
csv import
`if (($handle = fopen("svcar.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if($data[1] != '')
{
$arAdd = array("SITE_ID" => "s1", "RULE" => $data[0], "TARGET" => $data[1]);
add($arAdd);
}
}
fclose($handle);
}
function add($arFields)
{
global $DB;
$table = 'b_webvision_seo_redirects';
foreach ($arFields as $k => $v)
{
$arFields[$k] = '"'.$DB->ForSQL($v).'"';
}
return $DB->Insert($table, $arFields, '');
}`
next prev в component_epilog
$cp = $this->__component; if (is_object($cp)) { $arResult['COUNT'] = count($arResult['ITEMS']); $cp->SetResultCacheKeys(array("NAV_RESULT")); }
`$nav_nomer = $arResult['NAV_RESULT']->NavPageNomer;
$NavPageCount = $arResult['NAV_RESULT']->NavPageCount;
$arUrl = explode('?', $_SERVER['REQUEST_URI']);
$dir = $arUrl[0];
if(!isset($_REQUEST['sort']) || $_REQUEST['sort'] == '')
{
if(preg_match("/page=([0-9]+)/$/", $dir, $matches))
{
$paging = $matches[1];
$page = preg_replace("/page=([0-9]+)/$/",'',$dir);
}
if($nav_nomer == 1 && $NavPageCount > 1)
{
$seo_link_next_url = $dir.'page=2/';
$APPLICATION->AddHeadString('',true);
}
elseif($nav_nomer > 1 && $nav_nomer < $NavPageCount)
{
if($nav_nomer == 2)
{
//$page = 'page='.
//$prev =
$seo_link_prev_url = str_replace('/page=2/', '/',$dir);
$APPLICATION->AddHeadString('',true);
}
else
{
$seo_link_prev_url = str_replace($paging, intval($nav_nomer)-1,$dir);
$APPLICATION->AddHeadString('',true);
}
$seo_link_next_url = str_replace($paging, intval($nav_nomer)+1,$dir);
$APPLICATION->AddHeadString('',true);
}
elseif($nav_nomer > 1 && $nav_nomer == $NavPageCount)
{
if($nav_nomer == 2)
{
$seo_link_prev_url = str_replace('/page=2/', '/',$dir);
}
else $seo_link_prev_url = str_replace($paging, intval($nav_nomer)-1,$dir);
$APPLICATION->AddHeadString('<link rel="prev" href="https://wallet.ua'.$seo_link_prev_url.'">',true);
}
}`
Фильтр по даті
$objDateTime = DateTime::createFromTimestamp(time() - 90 * 86400);
$arResult = \Bitrix\Sale\Order::getList(array('filter' => array('>DATE_INSERT' => $objDateTime, 'PAYED' => 'N', 'CANCELED' => 'N', '!STATUS_ID' => 'F'))) -> fetchAll();
foreach($arResult as $order)
{
echo '<pre>'; print_r($order['ID']); echo '</pre>';
}
крон
текст між квадратними дужками
$pattern = '/([^\]]+)\[(.*)\]/';
preg_match($pattern, $arItem['INPUT_NAME'], $matches, PREG_OFFSET_CAPTURE);
між круглими
/([^\)]+)((.*))/
ajax кнопка в адмінці + проставка свойства
Ініт
AddEventHandler('main', 'OnAdminContextMenuShow', 'OrderDetailAdminContextMenuShow'); function OrderDetailAdminContextMenuShow(&$items) { if (($_SERVER['REQUEST_METHOD']=='GET' && $GLOBALS['APPLICATION']->GetCurPage()=='/bitrix/admin/cat_product_edit.php' && $_REQUEST['ID']>0 ) || ($_SERVER['REQUEST_METHOD']=='GET' && $GLOBALS['APPLICATION']->GetCurPage()=='/bitrix/admin/iblock_element_edit.php' && $_REQUEST['ID']>0 && $_REQUEST['IBLOCK_ID'] == 54 )) { $items[] = array("TEXT"=>"Прописать цветные товары", "LINK"=>"javascript:button('".$_REQUEST['ID']."', '".$_REQUEST['IBLOCK_ID']."');"); \CJSCore::RegisterExt('_button', array( 'js' => '/local/admin/admin.js' , )); \CJSCore::Init(array('jquery', '_button')); } }
js
function button(id, ib) { var maxbitDialogAddImg = new BX.CDialog({ title: 'Заполнение вариантов цвета', content_url: '/local/admin/color.php', content_post: 'ajax=yes&window=openWindow&ID=' + id + '&IB=' + ib, width:400, min_width:400, height:200, min_height:200, buttons: [ BX.CDialog.prototype.btnClose ] }); maxbitDialogAddImg.Show(); }
php
`<?
require_once($_SERVER['DOCUMENT_ROOT'].'/bitrix/modules/main/include/prolog_admin_before.php');
if (isset($_REQUEST['ID']) && intval($_REQUEST['ID'])>0 && isset($_REQUEST['IB']) && intval($_REQUEST['IB'])>0){
$iblock = $_REQUEST['IB'];
$ELEMENT_ID = (int)$_REQUEST['ID'];
$prop_org_photo_code = 'RECOMMEND';
$prop_org_photo_code_VALUE = 'PROPERTY_'.$prop_org_photo_code.'_VALUE';
if(CModule::IncludeModule("iblock"))
{
$arSelect = Array("ID", "NAME","PROPERTY_".$prop_org_photo_code);
$arFilter = Array("IBLOCK_ID"=>$iblock, "ID"=>$ELEMENT_ID );
$res = CIBlockElement::GetList(Array(), $arFilter, false, false, $arSelect);
while($ob = $res->GetNext())
{
$ar_ob =$ob[$prop_org_photo_code_VALUE];
};
if (is_array($ar_ob) && count($ar_ob)>0){
foreach($ar_ob as $key => $ph)
{
$ar_ob_elem = array();
$ar_ob_elem = $ar_ob;
$ar_ob_elem [$ELEMENT_ID]= $ELEMENT_ID;
unset($ar_ob_elem[$ph]);
if(($key = array_search($ph, $ar_ob_elem)) !== false) {
unset($ar_ob_elem[$key]);
}
$file = CIBlockElement::SetPropertyValueCode($ph, $prop_org_photo_code,$ar_ob_elem);
}
}
}
if (isset($file) && $file == 1){
echo "Цвета проставленны успешно.";
}else{
echo "При установки цветов вознилки проблемы.";
}
}
?>`
if(!is_dir($dir)) mkdir($dir) ;
if(!is_dir($dir)) mkdir($dir) ;
Форма з рекачею
стара підписка
`
Рассылка новостей Акции каждую неделю!
ПОДПИСАТЬСЯ
<script> jQuery('#subscrible_form').on('submit', function(){ var email = $('#on_mouse_playholder').val(); if(email.length <= 0) { subAlert('Введите e-mail','error'); } else if(!isEmail(email)){ subAlert('Вы указали неверный e-mail','error'); } else{ $.ajax({ url: "/local/include/ajax/subscribe.php", type : "POST", dataType: 'json', data: {'email': email, 'uid': 'IsAuthorized()? $USER->GetID():false?>'}, success: function(res){ console.log(res); subAlert(res.text, res.type); } }); } return false; });function isEmail(email) {
var regex = /^([a-zA-Z0-9_.+-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
function subAlert(text, classAdd){
$('.subNotification').text(text).addClass(classAdd);
}
function hideSubText(){
$('.subNotification').text('').removeClass('error').removeClass('good');
}
</script>
php
`<?
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
header('Content-Type: text/html; charset=utf-8');
require_once($_SERVER['DOCUMENT_ROOT'].'/bitrix/modules/main/include/prolog_before.php'); // include bitrix prolog (clasess)
define("STOP_STATISTICS", true); // disable statistic
CModule::IncludeModule("subscribe");
$email = htmlspecialchars($_POST['email']);
$subscr = CSubscription::GetList(
array("ID"=>"ASC"),
array("EMAIL"=>$email)
);
while(($subscr_arr = $subscr->Fetch()))
$aId = $subscr_arr["ID"];
if($aId > 0 ) $res = array('type' => 'error', 'text' => 'Вы уже подписаны на рассылку');
else
{
$arFields = Array(
"USER_ID" => intval($_POST['uid']),
"FORMAT" => "html",
"EMAIL" => $email,
"ACTIVE" => "Y",
"SEND_CONFIRM" => "N",
"CONFIRMED" => "Y",
"RUB_ID" => array(9)
);
$subscr = new CSubscription;
//can add without authorization
$ID = $subscr->Add($arFields);
if($ID>0)
{
$res = array('type' => 'good', 'text' => 'Спасибо за подписку!');
CSubscription::Authorize($ID);
}
else
{
$strWarning .= "Error adding subscription: ".$subscr->LAST_ERROR."<br>";
\Bitrix\Main\Diag\Debug::writeToFile($strWarning,"error",'/local/logs/subscribe.txt');
$res = array('type' => 'error', 'text' => 'Ошибка подписки на рассылку');
}
}
echo json_encode($res);`
архівувати папку з консолі
zip -r folder.zip ./
slick slider баг
`function initSlider(){
$('.slick').slick({
dots: true,
infinite: true,
speed: 300,
slidesToShow: 5,
slidesToScroll: 5,
responsive: [
{
breakpoint: 1199,
settings: {
slidesToShow: 4,
slidesToScroll: 4,
infinite: true
}
},
{
breakpoint: 680,
settings: {
slidesToShow: 2,
slidesToScroll: 2,
infinite: true,
dots: false
}
},
{
breakpoint: 480,
settings: {
slidesToShow: 1,
slidesToScroll: 1,
infinite: true,
dots: false
}
}
]
});
}
$(document).on('ready', function () {
initSlider();
});`
нова пошта
<?
namespace Webvision\Main;
class Np
{
public $api_key;
public function __construct($api_key)
{
$this->api_key = $api_key;
}
function get_city_list($filter = false)
{
$json = $this->get_json_sity();
$result_json = $this->make_request_2($json);
return json_decode($result_json);
}
function get_warehouses($filter)
{
//$xml = $this->make_xml('warehouses', $filter);
//$result_xml = $this->make_request($xml);
//return simplexml_load_string($result_xml);
$json = $this->get_json_warehouses($filter);
$result_json = $this->make_request_2($json);
return $result_json;
}
function make_request_2($json)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://testapi.novaposhta.ua/v2.0/json/AddressGeneral/getWarehouses');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type: text/xml"));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
function get_json_sity($Page=1)
{
$arr = array(
'apiKey' => $this->api_key,
'modelName' => 'Address',
'calledMethod' => 'getCities',
'methodProperties' => array('Page'=>$Page)
);
return json_encode($arr);
}
function get_json_warehouses($Ref)
{
// if(!strlen($Ref)) return false;
$arr = array(
'apiKey' => $this->api_key,
'modelName' => 'Address',
'calledMethod' => 'getWarehouses',
'methodProperties' => array('CityRef'=>$Ref)
);
return json_encode($arr);
}
function make_request($xml)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://orders.novaposhta.ua/xml.php');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type: text/xml"));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
function object_to_array($obj)
{
$data = json_decode(json_encode(simplexml_load_string($obj)), true);
return $obj;
}
function make_xml($select, $filter = false)
{
$dom = new DOMDocument("1.0", "utf-8");
$xml_root = $dom->createElement("file");
$xml_auth = $dom->createElement("auth", $this->api_key);
$xml_root->appendChild($xml_auth);
switch($select)
{
case 'city':
$xml_city = $dom->createElement("citywarehouses");
$xml_root->appendChild($xml_city);
break;
case 'warehouses':
$xml_warehouses = $dom->createElement("warenhouse");
$xml_root->appendChild($xml_warehouses);
break;
}
if($filter)
{
$xml_filter = $dom->createElement("filter", $filter);
$xml_root->appendChild($xml_filter);
}
$dom->appendChild($xml_root);
return $dom->saveXML();
}
}
$WVNovaPoshta = new Webvision\Main\Np('6ece38edc821aeddb937ec590fe86bd8');
$objWarehouseList = $WVNovaPoshta->get_warehouses();
?>
долганін адмінка
не обєднувати скрипт в бітрікс
data-skip-moving="true"
в тексті є кирилиця
$pattern = "/[а-яё]/iu";
if(preg_match($pattern,${$FILTER_NAME}['?NAME']))
{
${$FILTER_NAME}['PROPERTY']['?Brand_name_in_Russian'] = ${$FILTER_NAME}['?NAME'];
unset(${$FILTER_NAME}['?NAME']);
}
gt order
`if(!is_array($_SESSION['SHOW_GA_TRANC']) ) $_SESSION['SHOW_GA_TRANC'] =array();
if (intval($arResult['ORDER_ID'] ) && !in_array($arResult['ORDER_ID'], $_SESSION['SHOW_GA_TRANC'])){
CModule::IncludeModule('sale');
CModule::IncludeModule('iblock');
$arProducts = array();
$dbBasketItems = CSaleBasket::GetList(
array(),
array(
"ORDER_ID" => $arResult["ORDER_ID"]
),
false,
false,
array("ID", "PRODUCT_ID", "QUANTITY","PRICE")
);
while ($arItems = $dbBasketItems->Fetch())
{
$arSelect = Array("ID", "NAME", 'IBLOCK_SECTION_ID', "PROPERTY_Code_products");
$arFilter = Array("ACTIVE_DATE"=>"Y", "ACTIVE"=>"Y", "ID"=>$arItems['PRODUCT_ID']);
$res = CIBlockElement::GetList(Array(), $arFilter, false, Array(), $arSelect);
while($ob = $res->GetNextElement())
{
$arFields = $ob->GetFields();
$res_section = CIBlockSection::GetByID($arFields['IBLOCK_SECTION_ID']);
if($ar_res = $res_section->GetNext()) $sec_name = $ar_res['NAME'];
$arProdIDRemarketing[] = $arItems['PRODUCT_ID'];
$arProducts[]= array(
'sku' => $arFields['PROPERTY_CODE_PRODUCTS_VALUE'],
'name' =>$arFields['NAME'],
'category'=>$sec_name, // Product Category
'price' =>$arItems['PRICE'],
'currency'=>'UAH',
'quantity'=>intval($arItems['QUANTITY'])
);
}
}
$dataLayer = array(
'transactionId'=> $arResult['ORDER']['ID'],
'transactionAffiliation'=> 'Wallet',
'transactionTotal'=>$arResult['ORDER']['PRICE'],
'transactionTax'=>$arResult['ORDER']['TAX_VALUE'],
'transactionShipping'=>$arResult['ORDER']['PRICE_DELIVERY'],
'transactionProducts'=>$arProducts,
'transactionCurrency'=> 'UAH',
);
$this->SetViewTarget("gtm-layer");
echo '<script>dataLayer=['.json_encode($dataLayer).'];</script>';
$this->EndViewTarget();
$_SESSION['SHOW_GA_TRANC'][] = $arResult['ORDER_ID'];
$APPLICATION->SetPageProperty("google_page_tag", "conversion");//page type - from google remarketing in footer script JS
$APPLICATION->SetPageProperty("google_page_tagid", implode (",",$arProdIDRemarketing));//page ID-list implode - from google remarketing in footer script JS
$APPLICATION->SetPageProperty("google_page_tagsumm", $arResult['ORDER']['PRICE']);//page type - from google remarketing in footer script JS
}`
beforeindex
class searchIndex
{
function BeforeIndexHandler($arFields)
{
if($arFields["MODULE_ID"] == "iblock" && $arFields["PARAM1"] == "catalog_merged")
{
if(array_key_exists("BODY", $arFields))
{
if(\CModule::IncludeModule("iblock")){
$arSelect = Array("ID", "PROPERTY_brand1" );
$arFilter = Array( "ID"=>intval($arFields["ITEM_ID"]), 'IBLOCK_ID' => 54 );
$res = \CIBlockElement::GetList(Array(), $arFilter, false, false, $arSelect);
if($arRes = $res->GetNext()){
$arSelect = Array("ID", "NAME", "PROPERTY_Brand_name_in_Russian" );
$arFilter = Array("ID"=>intval($arRes["PROPERTY_BRAND1_VALUE"]), );
$res = \CIBlockElement::GetList(Array(), $arFilter, false, false, $arSelect);
while($arResBrand = $res->GetNext()){
$arrRes["NAME"]=$arResBrand["NAME"];
$arrRes["RUS_NAME"][]=$arResBrand["PROPERTY_BRAND_NAME_IN_RUSSIAN_VALUE"];
}
if (is_array($arrRes))
{
$arFields["BODY"] .= " ".$arrRes["NAME"]." ".implode(" ", $arrRes["RUS_NAME"]);
$arFields["TITLE"] .= " ".implode(" ", $arrRes["RUS_NAME"]);
}
}
};
}
}
return $arFields;
}
}
перерахунок цін в ініті
`EventManager::getInstance()->addEventHandler(
'catalog',
'OnPriceUpdate',
"onUpdatePrice"
);
EventManager::getInstance()->addEventHandler(
'catalog',
'OnProductSetUpdate',
"onSetUpdate"
);
EventManager::getInstance()->addEventHandler(
'catalog',
'OnProductSetAdd',
"onSetUpdate"
);
function onUpdatePrice($arg1, $arg2 = false)
{
$ELEMENT_ID = false;
$IBLOCK_ID = false;
$OFFERS_IBLOCK_ID = false;
$PRICE_TYPE_ID = 1;
\CModule::IncludeModule("catalog");
//Check for catalog event
if(is_array($arg2) && $arg2["PRODUCT_ID"] > 0)
{
//Get iblock element
$rsPriceElement = \CIBlockElement::GetList(
array(),
array(
"ID" => $arg2["PRODUCT_ID"],
),
false,
false,
array("ID", "IBLOCK_ID")
);
if($arPriceElement = $rsPriceElement->Fetch())
{
$arCatalog = \CCatalog::GetByID($arPriceElement["IBLOCK_ID"]);
if(is_array($arCatalog))
{
//Check if it is offers iblock
if($arCatalog["OFFERS"] == "Y")
{
//Find product element
$rsElement = \CIBlockElement::GetProperty(
$arPriceElement["IBLOCK_ID"],
$arPriceElement["ID"],
"sort",
"asc",
array("ID" => $arCatalog["SKU_PROPERTY_ID"])
);
$arElement = $rsElement->Fetch();
if($arElement && $arElement["VALUE"] > 0)
{
$ELEMENT_ID = $arElement["VALUE"];
$IBLOCK_ID = $arCatalog["PRODUCT_IBLOCK_ID"];
$OFFERS_IBLOCK_ID = $arCatalog["IBLOCK_ID"];
$OFFERS_PROPERTY_ID = $arCatalog["SKU_PROPERTY_ID"];
}
}
//or iblock wich has offers
elseif($arCatalog["OFFERS_IBLOCK_ID"] > 0)
{
$ELEMENT_ID = $arPriceElement["ID"];
$IBLOCK_ID = $arPriceElement["IBLOCK_ID"];
$OFFERS_IBLOCK_ID = $arCatalog["OFFERS_IBLOCK_ID"];
$OFFERS_PROPERTY_ID = $arCatalog["OFFERS_PROPERTY_ID"];
}
//or it's regular catalog
else
{
$ELEMENT_ID = $arPriceElement["ID"];
$IBLOCK_ID = $arPriceElement["IBLOCK_ID"];
$OFFERS_IBLOCK_ID = false;
$OFFERS_PROPERTY_ID = false;
}
}
}
}
//Check for iblock event
elseif(is_array($arg1) && $arg1["ID"] > 0 && $arg1["IBLOCK_ID"] > 0)
{
//Check if iblock has offers
$arOffers = \CIBlockPriceTools::GetOffersIBlock($arg1["IBLOCK_ID"]);
if(is_array($arOffers))
{
$ELEMENT_ID = $arg1["ID"];
$IBLOCK_ID = $arg1["IBLOCK_ID"];
$OFFERS_IBLOCK_ID = $arOffers["OFFERS_IBLOCK_ID"];
$OFFERS_PROPERTY_ID = $arOffers["OFFERS_PROPERTY_ID"];
}
}
if($ELEMENT_ID)
{
if(CCatalogProductSet::isProductHaveSet($ELEMENT_ID)) return false;
$arSelect = Array("OWNER_ID", "ID");
$arFilter = Array("ITEM_ID"=>$ELEMENT_ID);
$res = CCatalogProductSet::GetList(Array("SORT" => "ASC"), $arFilter, false, Array("nPageSize"=>500), $arSelect);
while($ob = $res->GetNext())
{
if(!in_array($ob['OWNER_ID'], $arSet)) $arSet[] = $ob['OWNER_ID'];
}
if(count($arSet) > 0)
{
foreach($arSet as $setId)
{
$arSetItems = CCatalogProductSet::getAllSetsByProduct($setId, CCatalogProductSet::TYPE_GROUP);
$arComplectItems = CCatalogProductSet::getAllSetsByProduct($setId, CCatalogProductSet::TYPE_SET);
$arSetItems[] = array_shift($arComplectItems);
$sets = array_shift($arSetItems);
if(is_array($sets))
{
$sum = 0;
foreach($sets['ITEMS'] as $el)
{
$arPrice = CCatalogProduct::GetOptimalPrice($el['ITEM_ID'], 1, array(2), $renewal, array(), 's1');
$sum += $arPrice['DISCOUNT_PRICE'];
}
$arFields = Array(
"PRODUCT_ID" => $setId,
"CATALOG_GROUP_ID" => $PRICE_TYPE_ID,
"PRICE" => $sum,
"CURRENCY" => "UAH",
);
$res = CPrice::GetList(
array(),
array(
"PRODUCT_ID" => $setId,
"CATALOG_GROUP_ID" => $PRICE_TYPE_ID
)
);
if ($arr = $res->Fetch())
{
CPrice::Update($arr["ID"], $arFields);
}
}
}
}
}
}
function onSetUpdate($id, $arFields)
{
$PRICE_TYPE_ID = 1;
$set = CCatalogProductSet::getSetByID($id);
$setId = $set['OWNER_ID'];
foreach($set['ITEMS'] as $el)
{
$arPrice = CCatalogProduct::GetOptimalPrice($el['ITEM_ID'], 1, array(2), $renewal, array(), 's1');
$sum += $arPrice['DISCOUNT_PRICE'];
}
$arFields = Array(
"PRODUCT_ID" => $setId,
"CATALOG_GROUP_ID" => $PRICE_TYPE_ID,
"PRICE" => $sum,
"CURRENCY" => "UAH",
);
$res = CPrice::GetList(
array(),
array(
"PRODUCT_ID" => $setId,
"CATALOG_GROUP_ID" => $PRICE_TYPE_ID
)
);
if ($arr = $res->Fetch())
{
CPrice::Update($arr["ID"], $arFields);
}
}`
Звідки прийшов покупець
function OnOrderAddMy($ID, $arFields, $arParams) // write user INN from order data to user data
{
\CModule::IncludeModule("sale");
$orderObj = Sale\Order::load($ID);
$uid = $orderObj->getUserId(); // ID пользователя
$utype = $orderObj->getPersonTypeId();
if($utype == 1) $propFrom = 54;
else $propFrom = 55;
$propertyCollection = $orderObj->getPropertyCollection();
$somePropValue = $propertyCollection->getItemByOrderPropertyId($propFrom);
\CModule::IncludeModule("statistic");
$arFilter = array("ID" => $_COOKIE['BITRIX_SM_GUEST_ID']);
$rs = \CGuest::GetList(($by = "s_id"), ($order = "desc"), $arFilter, $is_filtered);
while ($ar = $rs->Fetch())
{
if(strlen($ar['FIRST_URL_FROM']) > 0) $from = substr($ar['FIRST_URL_FROM'], 0, 100);
else $from = 'http://softkey.ua';
\Bitrix\Main\Diag\Debug::writeToFile($ar,"stat",'/personal/log/from.txt');
}
\Bitrix\Main\Diag\Debug::writeToFile(date('Y-m-d h:I:s').' '.$ID.' '.$from,"after handler",'/personal/log/from.txt');
$somePropValue->setValue($from);
$orderObj->save();
}
Долганин обробка
`<?
if (isset($_REQUEST['work_start']))
{
define("NO_AGENT_STATISTIC", true);
define("NO_KEEP_STATISTIC", true);
}
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_admin_before.php");
/*
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
*/
use Bitrix\Main\Loader;
use Bitrix\Sale;
Loader::includeModule('sale');
Loader::includeModule('webvision.promodo');
IncludeModuleLangFile(FILE);
$POST_RIGHT = $APPLICATION->GetGroupRight("main");
if ($POST_RIGHT == "D")
$APPLICATION->AuthForm("Доступ запрещен");
/*
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$order = Sale\Order::load(7391);
\Webvision\Promodo\Observers\status::makeTMP($order, false);
*/
$limit = 5;
$lastOrderId = 27780;
// Выведем даты всех заказов текущего пользователя за текущий месяц, отсортированные по дате заказа
if($_REQUEST['work_start'] && check_bitrix_sessid())
{
if($_REQUEST["lastid"] > 0) $id = $_REQUEST["lastid"];
else $id = 27100;
$arFilter = Array(
"<ID" => $lastOrderId,
">ID" => $id
);
$db_sales = CSaleOrder::GetList(array("ID" => "ASC"), $arFilter, false, array("nTopCount" => $limit));
while ($ar_sales = $db_sales->Fetch())
{
$order = Sale\Order::load($ar_sales["ID"]);
\Webvision\Promodo\Observers\status::makeTMP($order, false);
$lastID = intval($ar_sales["ID"]);
}
$rsLeftBorder = CSaleOrder::GetList(array("ID" => "ASC"), array(">ID" => $lastID, "<=ID" => $lastOrderId));
$leftBorderCnt = $rsLeftBorder->SelectedRowsCount();
$rsAll = CSaleOrder::GetList(array("ID" => "ASC"), array( "<ID" => $lastOrderId));
$allCnt = $rsAll->SelectedRowsCount();
$p = round(100*$leftBorderCnt/$allCnt, 2);
echo 'CurrentStatus = Array('.$p.',"'.($p < 100 ? '&lastid='.$lastID : '').'","Обрабатываю запись с ID #'.$lastID.'");';
die();
}
$clean_test_table = '
'.''.
''.
''.
''.
'
Текущее действие |
$aTabs = array(array("DIV" => "edit1", "TAB" => "Обработка"));
$tabControl = new CAdminTabControl("tabControl", $aTabs);
$APPLICATION->SetTitle("Обработка элементов инфоблока");
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_admin_after.php");
?>
<script type="text/javascript"> var bWorkFinished = false; var bSubmit; function prepare () { CHttpRequest.Send('?prepare=Y&lang=&'); } function set_start(val) { document.getElementById('work_start').disabled = val ? 'disabled' : ''; document.getElementById('work_stop').disabled = val ? '' : 'disabled'; document.getElementById('progress').style.display = val ? 'block' : 'none'; if (val) { ShowWaitWindow(); document.getElementById('result').innerHTML = ''; document.getElementById('status').innerHTML = 'Работаю...'; document.getElementById('percent').innerHTML = '0%'; document.getElementById('indicator').style.width = '0%'; CHttpRequest.Action = work_onload; CHttpRequest.Send('?work_start=Y&lang=&'); } else CloseWaitWindow(); } function work_onload(result) { try { eval(result); iPercent = CurrentStatus[0]; strNextRequest = CurrentStatus[1]; strCurrentAction = CurrentStatus[2]; document.getElementById('percent').innerHTML = iPercent + '%'; document.getElementById('indicator').style.width = iPercent + '%'; document.getElementById('status').innerHTML = 'Работаю...'; if (strCurrentAction != 'null') { oTable = document.getElementById('result_table'); oRow = oTable.insertRow(-1); oCell = oRow.insertCell(-1); oCell.innerHTML = strCurrentAction; oCell = oRow.insertCell(-1); oCell.innerHTML = ''; } if (strNextRequest && document.getElementById('work_start').disabled) CHttpRequest.Send('?work_start=Y&lang=&' + strNextRequest); else { set_start(0); bWorkFinished = true; } } catch(e) { CloseWaitWindow(); document.getElementById('work_start').disabled = ''; alert('Сбой в получении данных'); } } </script> $tabControl->Begin();$tabControl->BeginNextTab();
?>
<input type=button value="Старт" id="work_start" onclick="set_start(1)" />
<input type=button value="Стоп" disabled id="work_stop" onclick="bSubmit=false;set_start(0)" />
<input type=button value="Подготовка" id="prepare" onclick="prepare()" />
<div id="progress" style="display:none;" width="100%">
<br />
<div id="status"></div>
<table border="0" cellspacing="0" cellpadding="2" width="100%">
<tr>
<td height="10">
<div style="border:1px solid #B9CBDF">
<div id="indicator" style="height:10px; width:0%; background-color:#B9CBDF"></div>
</div>
</td>
<td width=30> <span id="percent">0%</span></td>
</tr>
</table>
</div>
<div id="result" style="padding-top:10px"></div>
</td>
</tr>
карта сайту
`<?
ini_set("memory_limit", "512M");
if (!$_SERVER["DOCUMENT_ROOT"]) {
require_once dirname(FILE) . '/../../config.php'; // забираем отсюда конфиг
}
use Bitrix\Highloadblock as HL;
use Bitrix\Main;
use Bitrix\Main\IO;
use Bitrix\Main\SiteTable;
use Bitrix\Main\Localization\Loc;
use Bitrix\Seo\RobotsFile;
use Bitrix\Seo\SitemapIblock;
use Bitrix\Seo\SitemapTable;
use Bitrix\Seo\SitemapIndex;
use Bitrix\Seo\SitemapRuntime;
use Bitrix\Seo\SitemapRuntimeTable;
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_before.php");
if (!CModule::IncludeModule('iblock')) {
return false;
}
define('PROTOCOL', ($_SERVER['HTTPS'] === true) ? 'https' : 'http');
// Catalog - sitemap_000
$urlTemplate = "
%s%s
%s
%s
%s
";
$prefix = CNext::siteUrl();
$content = $filterContent = '';
// main page
$content .= sprintf($urlTemplate
,$prefix.'/'
,null
, date('c')
,'1',
'Weekly'
);
Main\Loader::includeModule('seo');
$PID = 3;
$dbSitemap = SitemapTable::getById($PID);
$arSitemap = $dbSitemap->fetch();
$dbSite = SiteTable::getByPrimary($arSitemap['SITE_ID']);
$arSitemap['SITE'] = $dbSite->fetch();
$arSitemap['SETTINGS'] = unserialize($arSitemap['SETTINGS']);
$PID2 = 2;
$dbSitemapOdessa = SitemapTable::getById($PID2);
$arSitemapOdessa = $dbSitemapOdessa->fetch();
$dbSiteOdessa = SiteTable::getByPrimary($arSitemapOdessa['SITE_ID']);
$arSitemapOdessa['SITE'] = $dbSiteOdessa->fetch();
$arSitemapOdessa['SETTINGS'] = unserialize($arSitemapOdessa['SETTINGS']);
$sections = getStruct($arSitemap);
foreach($sections as $section)
{
$url = $prefix.$section.'/';
$content .= sprintf($urlTemplate
,$url
,null
,$date ? $date : date('c')
,'0.9',
'Weekly'
);
}
foreach($arSitemapOdessa['SETTINGS']['IBLOCK_SECTION'] as $key => $val)
if($val == 'Y')
{
$arSiteIb[$key] = $arSitemapOdessa['SITE']['DIR'];
$arSectionIbId[$key] = $key;
}
foreach($arSitemap['SETTINGS']['IBLOCK_SECTION'] as $key => $val)
if($val == 'Y')
{
$arSiteIb[$key] = $arSitemap['SITE']['DIR'];
$arSectionIbId[$key] = $key;
}
$content .= getIbSection($arSectionIbId, $arSiteIb, $urlTemplate);
foreach($arSitemapOdessa['SETTINGS']['IBLOCK_ELEMENT'] as $key => $val)
if($val == 'Y')
{
$arElIb[$key] = $arSitemapOdessa['SITE']['DIR'];
$arElIbId[$key] = $key;
}
foreach($arSitemap['SETTINGS']['IBLOCK_ELEMENT'] as $key => $val)
if($val == 'Y')
{
$arElIb[$key] = $arSitemap['SITE']['DIR'];
$arElIbId[$key] = $key;
}
$content .= getIbEl($arElIbId, $arElIb, $urlTemplate);
$startMap = '';
$endMap = '';
// Write to file
$CATALOG_FILE_PATH = rel2abs($_SERVER['DOCUMENT_ROOT'], 'sitemap.xml');
$contentMap = $startMap . $content . $endMap;
if ($file_000 = fopen($CATALOG_FILE_PATH, "wb")) {
$int_content = fwrite($file_000, $contentMap );
fclose($file_000);
} else {
echo 'Ошибка записи в файл '.$CATALOG_FILE_PATH;
}
function getStruct($arSitemap, $dir = '/')
{
$list = \CSeoUtils::getDirStructure(
$arSitemap['SETTINGS']['logical'] == 'Y',
$arSitemap['SITE_ID'],
$dir
);
foreach($list as $dir)
{
$dirKey = "/".ltrim($dir['DATA']['ABS_PATH'], "/");
if($dir['TYPE'] != 'F')
{
if(!isset($arSitemap['SETTINGS']['DIR'][$dirKey])
|| $arSitemap['SETTINGS']['DIR'][$dirKey] == 'Y')
{
$arDirList[] = $dirKey;
foreach($arSitemap['SETTINGS']['FILE'] as $dirKeySettting => $checked)
{
if($checked == 'Y')
{
if(strncmp($arCurrentDir['ITEM_PATH'], $dirKeySettting, $len) === 0)
{
$fileName = IO\Path::combine(
SiteTable::getDocumentRoot($arSitemap['SITE_ID']),
$dirKeySettting
);
if(!is_dir($fileName))
{
$f = new IO\File($fileName, $arSitemap['SITE_ID']);
if($f->isExists()
&& !$f->isSystem()
&& preg_match($arSitemap['SETTINGS']['FILE_MASK_REGEXP'], $f->getName())
)
{
$sitemapFile->addFileEntry($f);
$NS['files_count']++;
}
}
}
}
}
$child = getStruct($arSitemap, $dirKey);
if(count($child) > 0) $arDirList = array_merge($arDirList, $child);
}
}
}
return $arDirList;
}
function getIbSection($arSettingsIds, $arSite, $urlTemplate)
{
$content = '';
foreach($arSettingsIds as $ibId)
{
$sort = Array('SORT' => 'ASC');
$filter = Array('IBLOCK_ID' => $ibId, 'ACTIVE' => 'Y', 'GLOBAL_ACTIVE' => 'Y', 'DEPTH_LEVEL' => 1);
$select = Array('ID', 'TIMESTAMP_X', 'SECTION_PAGE_URL', 'CODE');
$resDbSections = CIBlockSection::GetList($sort, $filter, false, $select);
$sections = $filterMap = Array();
while ($arSec = $resDbSections->GetNext()) {
$sections[$arSec['ID']] = $arSec;
if ($stmp = MakeTimeStamp($arSec['TIMESTAMP_X'])) {
$date = date("c", $stmp);
}
$content .= sprintf($urlTemplate
,CNext::siteUrl().setSiteDir($arSite[$arSec['IBLOCK_ID']], $arSec['SECTION_PAGE_URL'])
,null
,$date ? $date : date('c')
,'0.9',
'Weekly'
);
//echo '
'; print_r($content); echo '';
}
}
return $content;
}
function getIbEl($arSettingsIds, $arSite, $urlTemplate)
{
$content = '';
foreach($arSettingsIds as $ibId)
{
$sort = Array('SORT' => 'ASC');
$filter = Array(
'IBLOCK_ID' => $ibId,
'ACTIVE'=>'Y',
'SECTION_ACTIVE' => 'Y',
'SECTION_GLOBAL_ACTIVE' => 'Y'
);
$select = Array('ID', 'TIMESTAMP_X', 'DETAIL_PAGE_URL');
$resDbProducts = CIBlockElement::GetList($sort, $filter, false, false, $select);
while ($arEl = $resDbProducts->GetNext()) {
if ($stmp = MakeTimeStamp($arEl['TIMESTAMP_X'])) {
$date = date("c", $stmp);
}
$content .= sprintf($urlTemplate
,CNext::siteUrl().setSiteDir($arSite[$arEl['IBLOCK_ID']], $arEl['DETAIL_PAGE_URL'])
,null
,$date ? $date : date('c')
,'0.7',
'Monthly'
);
}
}
return $content;
}
function setSiteDir($siteDir, $url)
{
return substr_replace($url, $siteDir, 0, 1);
}
?>
`
перевірити купон
$arCoupon = \Bitrix\Sale\Internals\DiscountCouponTable::getList(array('filter' => array('=COUPON' => $coupon))) -> fetchAll();
if(count($arCoupon) > 0)
{
CCatalogDiscountCoupon::SetCoupon($coupon);
}
д7 кеш
$сache = Bitrix\Main\Data\Cache::createInstance();
$cacheDir = 'hidden';
$cacheId = 'hidden_items';
if ($сache->initCache(900, $cacheId, $cacheDir))
{
$ids = $сache->getVars();
echo '<pre>!!'; print_r($ids); echo '</pre>';
}
elseif ($сache->startDataCache())
{
$arSelect = Array("ID");
$arFilter = Array("IBLOCK_ID"=>$arParams['IBLOCK_ID'], "!PROPERTY_SCECIAL_GROUP_ITEM" => false,"ACTIVE_DATE"=>"Y", "ACTIVE"=>"Y");
$res = CIBlockElement::GetList(Array(), $arFilter, false, Array("nPageSize"=>5000), $arSelect);
while($ob = $res->GetNextElement())
{
$arFields = $ob->GetFields();
$ids[] = $arFields['ID'];
}
echo '<pre>'; print_r($ids); echo '</pre>';
$сache->endDataCache($ids);
}
orm d7
https://yadi.sk/d/k8Tq9crb3EP7Wo
$res = \AB\Iblock\Element::getList([
'select' => [
'ID',
'TYPE' => 'PROPERTY.TYPE',
'EMAIL' => 'PROPERTY.EMAIL',
'ITEM_NAME' => 'PROPERTY.ITEM_NAME',
'ID_ORDER' => 'PROPERTY.ID_ORDER'
],
'filter' => [
'IBLOCK_ID' => self::$ib_id,
'PROPERTY.ID_ORDER' => $id
]
]);
$items = $res->fetchAll();
foreach($items as $item)
{
$ids = $item['ID'];
if(!in_array($item['ID'], $ids)) $arRes[] = $item;
}
Не відправляти лист
cron.php
global $cancelNotSend;
$cancelNotSend = 'Y';
AddEventHandler("main", "OnBeforeEventAdd", Array("wv\WV_Helper", "OnBeforeEventAddHandler"));
public function OnBeforeEventAddHandler(&$event, &$lid, &$arFields)
{
global $cancelNotSend;
if($cancelNotSend == 'Y' && $event == 'SALE_ORDER_CANCEL') $arFields = array();
}
перша велика буква на кирилиці
`if(!function_exists(upFirstLetter)){
function upFirstLetter($text, $encoding = 'UTF-8')
{
$str = mb_strtolower($text, $encoding);
$str = mb_ereg_replace('^[\ ]+', '', $str);
$str = mb_strtoupper(mb_substr($str, 0, 1, $encoding), $encoding).
mb_substr($str, 1, mb_strlen($str), $encoding);
return $str;
}
}`
Додати колонку в таблицю
ALTER TABLE wv_seo_filter_objects ADD COLUMN CANONICAL CHAR(50) NULL AFTER NAME;
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.