<?
/*Version 0.3 2011-04-25*/
AddEventHandler("iblock", "OnAfterIBlockElementUpdate", "DoIBlockAfterSave");
AddEventHandler("iblock", "OnAfterIBlockElementAdd", "DoIBlockAfterSave");
AddEventHandler("catalog", "OnPriceAdd", "DoIBlockAfterSave");
AddEventHandler("catalog", "OnPriceUpdate", "DoIBlockAfterSave");
function DoIBlockAfterSave($arg1, $arg2 = false)
{
$ELEMENT_ID = false;
$IBLOCK_ID = false;
$OFFERS_IBLOCK_ID = false;
$OFFERS_PROPERTY_ID = false;
if (CModule::IncludeModule('currency'))
$strDefaultCurrency = CCurrency::GetBaseCurrency();
//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 which 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)
{
static $arPropCache = array();
if(!array_key_exists($IBLOCK_ID, $arPropCache))
{
//Check for MINIMAL_PRICE property
$rsProperty = CIBlockProperty::GetByID("MINIMUM_PRICE", $IBLOCK_ID);
$arProperty = $rsProperty->Fetch();
if($arProperty)
$arPropCache[$IBLOCK_ID] = $arProperty["ID"];
else
$arPropCache[$IBLOCK_ID] = false;
}
if($arPropCache[$IBLOCK_ID])
{
//Compose elements filter
if($OFFERS_IBLOCK_ID)
{
$rsOffers = CIBlockElement::GetList(
array(),
array(
"IBLOCK_ID" => $OFFERS_IBLOCK_ID,
"PROPERTY_".$OFFERS_PROPERTY_ID => $ELEMENT_ID,
),
false,
false,
array("ID")
);
while($arOffer = $rsOffers->Fetch())
$arProductID[] = $arOffer["ID"];
if (!is_array($arProductID))
$arProductID = array($ELEMENT_ID);
}
else
$arProductID = array($ELEMENT_ID);
$minPrice = false;
$maxPrice = false;
//Get prices
$rsPrices = CPrice::GetList(
array(),
array(
"PRODUCT_ID" => $arProductID,
)
);
while($arPrice = $rsPrices->Fetch())
{
if (CModule::IncludeModule('currency') && $strDefaultCurrency != $arPrice['CURRENCY'])
$arPrice["PRICE"] = CCurrencyRates::ConvertCurrency($arPrice["PRICE"], $arPrice["CURRENCY"], $strDefaultCurrency);
$PRICE = $arPrice["PRICE"];
if($minPrice === false || $minPrice > $PRICE)
$minPrice = $PRICE;
if($maxPrice === false || $maxPrice < $PRICE)
$maxPrice = $PRICE;
}
//Save found minimal price into property
if($minPrice !== false)
{
CIBlockElement::SetPropertyValuesEx(
$ELEMENT_ID,
$IBLOCK_ID,
array(
"MINIMUM_PRICE" => $minPrice,
"MAXIMUM_PRICE" => $maxPrice,
)
);
}
}
}
}
/******
* ЧПУ *
******/
AddEventHandler("iblock", "OnAfterIBlockElementAdd", array("MyEventHandlerClass", "IBlockElementAddCodeFromNameAfterAdd"));
AddEventHandler("iblock", "OnBeforeIBlockElementUpdate", array("MyEventHandlerClass", "IBlockElementAddCodeFromNameBeforeUpdate"));
AddEventHandler("iblock", "OnBeforeIBlockSectionAdd", array("MyEventHandlerClass", "IBlockSectionAddCodeFromNameBeforeAdd"));
AddEventHandler("iblock", "OnBeforeIBlockSectionUpdate", array("MyEventHandlerClass", "IBlockSectionAddCodeFromNameBeforeUpdate"));
class MyEventHandlerClass
{
function IBlockElementAddCodeFromNameAfterAdd(&$arFields)
{
$arFields["CODE"] = Translit::UrlTranslit($arFields["NAME"]);
if(isset($GLOBALS["GRABBER"]["IBLOCK"]["TYPES"]["news"]) and in_array($arFields["IBLOCK_ID"], $GLOBALS["GRABBER"]["IBLOCK"]["TYPES"]["news"]) and $arFields["ACTIVE_FROM"])
{
if($stmp = MakeTimeStamp($arFields["ACTIVE_FROM"]))
{
$arFields["CODE"] = date("d-m-Y", $stmp).".".$arFields["CODE"];
}
}
$arFields["CODE"] .= ".".$arFields["ID"];
$arNewFields = array(
"CODE" => $arFields["CODE"],
);
$el = new CIBlockElement;
$el->Update($arFields["ID"], $arNewFields);
}
function IBlockElementAddCodeFromNameBeforeUpdate(&$arFields)
{
if(isset($arFields["NAME"]))
{
$arFields["CODE"] = Translit::UrlTranslit($arFields["NAME"]);
if(isset($GLOBALS["GRABBER"]["IBLOCK"]["TYPES"]["news"]) and in_array($arFields["IBLOCK_ID"], $GLOBALS["GRABBER"]["IBLOCK"]["TYPES"]["news"]) and $arFields["ACTIVE_FROM"])
{
if($stmp = MakeTimeStamp($arFields["ACTIVE_FROM"]))
{
$arFields["CODE"] = date("d-m-Y", $stmp).".".$arFields["CODE"];
}
}
$arFields["CODE"] .= ".".$arFields["ID"];
}
}
function IBlockSectionAddCodeFromNameBeforeAdd(&$arFields)
{
$arFields["CODE"] = Translit::UrlTranslit($arFields["NAME"]);
}
function IBlockSectionAddCodeFromNameBeforeUpdate(&$arFields)
{
if(isset($arFields["NAME"]))
{
$arFields["CODE"] = Translit::UrlTranslit($arFields["NAME"]);
}
}
}
/*****************************************************
* Кеширование разлиной часто используемой информации *
*****************************************************/
$obPHPCache = new CPHPCache;
if($obPHPCache->InitCache(1800, 'grabber_init_cache', "/"))
{
$VARS = $obPHPCache->GetVars();
$GLOBALS["GRABBER"] =& $VARS;
}
if($obPHPCache->StartDataCache())
{
$VARS = array();
if(CModule::IncludeModule("iblock"))
{
$VARS["IBLOCK"]["TYPES"] = array();
$resIBlock = CIBlock::GetList();
while($arIBlock = $resIBlock->Fetch())
{
$VARS["IBLOCK"]["TYPES"][$arIBlock["IBLOCK_TYPE_ID"]][] = $arIBlock["ID"];
}
}
$obPHPCache->EndDataCache($VARS);
$GLOBALS["GRABBER"] =& $VARS;
}
/***********************************
* Вспомогательные функции и классы *
***********************************/
class Translit
{
function Transliterate($string)
{
$cyr=array(
"Щ",
"Ш",
"Ч",
"Ц",
"Ю",
"Я",
"Ж",
"А",
"Б",
"В",
"Г",
"Д",
"Е",
"Ё",
"З",
"И",
"Й",
"К",
"Л",
"М",
"Н",
"О",
"П",
"Р",
"С",
"Т",
"У",
"Ф",
"Х",
"Ь",
"Ы",
"Ъ",
"Э",
"Є",
"Ї",
"щ",
"ш",
"ч",
"ц",
"ю",
"я",
"ж",
"а",
"б",
"в",
"г",
"д",
"е",
"ё",
"з",
"и",
"й",
"к",
"л",
"м",
"н",
"о",
"п",
"р",
"с",
"т",
"у",
"ф",
"х",
"ь",
"ы",
"ъ",
"э",
"є",
"ї"
);
$lat=array(
"Shh",
"Sh",
"Ch",
"C",
"Ju",
"Ja",
"Zh",
"A",
"B",
"V",
"G",
"D",
"Je",
"Jo",
"Z",
"I",
"J",
"K",
"L",
"M",
"N",
"O",
"P",
"R",
"S",
"T",
"U",
"F",
"Kh",
"'",
"Y",
"`",
"E",
"Je",
"Ji",
"shh",
"sh",
"ch",
"c",
"ju",
"ja",
"zh",
"a",
"b",
"v",
"g",
"d",
"je",
"jo",
"z",
"i",
"j",
"k",
"l",
"m",
"n",
"o",
"p",
"r",
"s",
"t",
"u",
"f",
"kh",
"'",
"y",
"`",
"e",
"je",
"ji"
);
for($i=0; $i<count($cyr); $i++)
{
$c_cyr = $cyr[$i];
$c_lat = $lat[$i];
$string = str_replace($c_cyr, $c_lat, $string);
}
$string = preg_replace("/([qwrtpsdfghklzxcvbnmQWRTPSDFGHKLZXCVBNM]+)[jJ]e/", "\${1}e", $string);
$string = preg_replace("/([qwrtpsdfghklzxcvbnmQWRTPSDFGHKLZXCVBNM]+)[jJ]/", "\${1}'", $string);
$string = preg_replace("/([eyuioaEYUIOA]+)[Kk]h/", "\${1}h", $string);
$string = preg_replace("/^kh/", "h", $string);
$string = preg_replace("/^Kh/", "H", $string);
return $string;
}
function UrlTranslit($string)
{
$string = preg_replace("/[_\s\.,?!\[\](){}]+/", "_", $string);
$string = preg_replace("/-{2,}/", "--", $string);
$string = preg_replace("/_-+_/", "--", $string);
$string = preg_replace("/[_\-]+$/", "", $string);
$string = Translit::Transliterate($string);
$string = ToLower($string);
$string = preg_replace("/j{2,}/", "j", $string);
$string = preg_replace("/[^0-9a-z_\-]+/", "", $string);
return $string;
}
}
AddEventHandler("main", "OnAfterUserRegister", "OnBeforeUserRegisterHandler");
AddEventHandler("socialservices", "OnAfterUserRegister", "OnBeforeUserRegisterHandler");
AddEventHandler("main", "OnAfterUserAdd", "OnBeforeUserRegisterHandler");
AddEventHandler("socialservices", "OnAfterUserAdd", "OnBeforeUserRegisterHandler");
function OnBeforeUserRegisterHandler(&$arFields)
{
//создаём профиль
//PERSON_TYPE_ID - идентификатор типа плательщика, для которого создаётся профиль
$arProfileFields = array(
"NAME" => "Профиль покупателя (".$arFields['LOGIN'].')',
"USER_ID" => $arFields['USER_ID'],
"PERSON_TYPE_ID" => 1
);
$PROFILE_ID = CSaleOrderUserProps::Add($arProfileFields);
$fp = fopen('/var/www/logs/bitrix_log.txt', 'a');
fwrite($fp, $PROFILE_ID);
//если профиль создан
if ($PROFILE_ID)
{
//формируем массив свойств
$PROPS=Array(
array(
"USER_PROPS_ID" => $PROFILE_ID,
"ORDER_PROPS_ID" => 1,
"NAME" => "ISSOCIAL",
"VALUE" => "YES"
)
);
//добавляем значения свойств к созданному ранее профилю
foreach ($PROPS as $prop)
CSaleOrderUserPropsValue::Add($prop);
}
}
if(isset($_SERVER['PHP_AUTH_USER'])) {
// error_log("PHP_AUTH_USER: ".$_SERVER['PHP_AUTH_USER'].":".$_SERVER['PHP_AUTH_PW']);
}
?>
function OnBeforeUserRegisterHandler(&$arFields)
{
if(CModule::IncludeModule("sale")) // подключаем модуль и-магазин
{
//создаём профиль
//PERSON_TYPE_ID - идентификатор типа плательщика, для которого создаётся профиль
$arProfileFields = array(
"NAME" => "Профиль покупателя (".$arFields['LOGIN'].')',
"USER_ID" => $arFields['USER_ID'],
"PERSON_TYPE_ID" => 1
);
$PROFILE_ID = CSaleOrderUserProps::Add($arProfileFields);
$fp = fopen('/var/www/logs/bitrix_log.txt', 'a');
fwrite($fp, $PROFILE_ID);
//если профиль создан
if ($PROFILE_ID)
{
//формируем массив свойств
$PROPS=Array(
array(
"USER_PROPS_ID" => $PROFILE_ID,
"ORDER_PROPS_ID" => 1,
"NAME" => "ISSOCIAL",
"VALUE" => "YES"
)
);
//добавляем значения свойств к созданному ранее профилю
foreach ($PROPS as $prop)
CSaleOrderUserPropsValue::Add($prop);
}
}
}