Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class CMigration
- {
- private static $_instance;
- private static $dir = "/upload/catalog/";
- private static $paramFile = "param.php";
- private static $catFile = "catalog.php";
- private static $lockFile = "process.lock";
- private static $debugMode = 1;
- //5aaecf6f-0199-11e6-831c-74d43599898f
- public static $xmlRegex = "#[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-#i";
- public static $translit = Array("replace_space" => '-',"replace_other" => '-');
- public static $priceID = 5;
- public static $params = Array();
- public static $propsExeption = Array(
- "CML2_BAR_CODE",
- "TIP_TSENY_KOLLEROVKI",
- "CML2_ARTICLE",
- "CML2_LINK",
- "CML2_ATTRIBUTES",
- "CML2_TRAITS",
- "CML2_BASE_UNIT",
- "CML2_TAXES",
- "GROUP_NAME_LIST",
- "FILES",
- "R",
- "G",
- "B",
- );
- public static $linkerProperties = Array(
- "CML2_MANUFACTURER", //Производитель
- "BRAND", //Производитель
- "WORK_TYPE", //Тип работ
- "OBJECT_TYPE", //Тип объекта
- "WORK_MATERIAL", //Материал рабочей поверхности
- "LKM_TYPE", //Тип ЛКМ
- "THINNER", //Разбавитель
- "BASE", //База
- "COLOR", //Цвет
- "VOLUME_L", //Объем, л
- "VOLUME_KG", //Объем, кг
- "PLOTNOST", //Плотность
- "KVADRATURA", //Квадратура, кв.м
- "LENGTH", //Длина, мм
- "CHIPS_SIZE", //Размер крошки, мм
- "SEQUIN_COLOR", //Цвет блёсток
- "SEQUIN_SIZE", //Размер блёсток, мм
- "GLOSS", //Степень блеска
- );
- private static $noUpdateHandler = false;
- private static function setNoHandler($bool)
- {
- self::$noUpdateHandler=$bool;
- }
- public static function getNoHandler()
- {
- return self::$noUpdateHandler;
- }
- public static function exception($s)
- {
- if(self::$debugMode)
- {
- printra(func_get_args());
- }
- else
- {
- throw new Exception(func_get_args());
- }
- }
- private static function lock()
- {
- $docRoot = $_SERVER["DOCUMENT_ROOT"];
- touch($docRoot.self::$dir.self::$lockFile);
- }
- private static function locked()
- {
- $docRoot = $_SERVER["DOCUMENT_ROOT"];
- $sFile = $docRoot.self::$dir.self::$lockFile;
- $locktime = 1800;
- if (file_exists($sFile) && (time() - filemtime($sFile)) < $locktime) {
- unset($sFile);
- }
- return file_exists($sFile);
- }
- private static function unlock()
- {
- $docRoot = $_SERVER["DOCUMENT_ROOT"];
- @unlink($docRoot.self::$dir.self::$lockFile);
- }
- public static function getParams()
- {
- $docRoot = $_SERVER["DOCUMENT_ROOT"];
- $arParams = Array();
- require($docRoot.self::$dir.self::$paramFile);
- return $arParams;
- }
- public static function setParams($arParams=Array())
- {
- $docRoot = $_SERVER["DOCUMENT_ROOT"];
- ArrayToFile($arParams,"arParams",$docRoot.self::$dir.self::$paramFile);
- return $arParams;
- }
- public static function logToFile($sStr)
- {
- $sErrorLog = $_SERVER['DOCUMENT_ROOT']."/upload/catalog/log/".date("Y.m.d").".txt";
- $hFile = fopen($sErrorLog,"a+");
- fputs($hFile,date("Y.m.d H:i:s")."\t".$sStr."\n");
- fclose($hFile);
- }
- public static function cron()
- {
- try
- {
- if(!self::locked())
- {
- if(strlen($sAction = self::$params["action"]))
- {
- self::lock();
- self::logToFile("Start: {$sAction}");
- self::${"sAction"}();
- self::logToFile("End: {$sAction}");
- self::unlock();
- }
- }
- }
- catch(Exception $e)
- {
- ob_start();
- printr($e);
- $sError = ob_get_contents();
- ob_end_clean();
- self::SendError($sError);
- return false;
- }
- return true;
- }
- public static function next()
- {
- $arParams = self::getParams();
- if(!$arParams["action"] || $arParams["action"]=="done") return false;
- global $APPLICATION;
- echo '
- <script>
- window.setTimeout(function() {
- window.location.href = "'.$APPLICATION->GetCurPage().'";
- }, "300");
- </script>
- ';
- }
- public static function SendError($sError)
- {
- $obEvent = new CEvent();
- $obEvent->Send("CRON_ERROR","s1",Array("ERROR"=>$sError));
- printr($sError);
- }
- public static function checkStart()
- {
- $sFunctionName = "CMigration::start();";
- $obAgent = new CAgent();
- $obExists = $obAgent->GetList(Array(), Array("NAME" => $sFunctionName));
- if($arExists = $obExists->fetch())
- {
- $obAgent->Delete($arExists["ID"]);
- }
- $arAdd = Array(
- "NAME" => $sFunctionName,
- "AGENT_INTERVAL" => 1,
- "NEXT_EXEC" => date("d.m.Y H:i:s", time() + 60),
- "IS_PERIOD" => "N"
- );
- $obAgent->Add($arAdd);
- }
- public static function start()
- {
- self::removeIBlockLink();
- self::syncProperties();
- self::setParams(Array("action"=>"syncSections"));
- }
- public static function removeIBlockLink()
- {
- CCatalog::UnLinkSKUIBlock(IB_SKU);
- }
- public static function GetLinkerIBlocks()
- {
- if(!isset($GLOBALS["L_IBLOCK"]))
- {
- $GLOBALS["LINKER_IBLOCK"]=Array();
- $obIBlocks = CIBlock::GetList(Array("ID"=>"ASC"),Array("TYPE"=>"links"));
- while($arIBlock = $obIBlocks->Fetch())
- {
- $GLOBALS["L_IBLOCK"][$arIBlock["CODE"]]=$arIBlock["ID"];
- }
- }
- return $GLOBALS["L_IBLOCK"];
- }
- public static function processLinkerIBlock($arProperty)
- {
- $iIBlockID=false;
- if(!empty($arProperty) && $arProperty["CODE"])
- {
- $arIBlocks = self::GetLinkerIBlocks();
- global $APPLICATION;
- $arFields = Array(
- "SORT"=>$arProperty["SORT"],
- "CODE" => ToUpper(trim($arProperty["CODE"])),
- "IBLOCK_TYPE_ID" => "links",
- "NAME" => self::cleanString($arProperty["NAME"]),
- "VERSION" => 2,
- "WORKFLOW" => "N",
- "SITE_ID" => Array("s1"),
- "GROUP_ID" => Array("2" => "R")
- );
- $arFields["DETAIL_PAGE_URL"]="/catalog/fil-".ToLower($arFields["CODE"])."-is-#CODE#/";
- $obNewIBlock = new CIBlock();
- $arSettings = Array();
- $arSettings["CODE"]["WF_TYPE"] = "N";
- $arSettings["CODE"]["IS_REQUIRED"] = "Y";
- $arSettings["CODE"]["DEFAULT_VALUE"]["UNIQUE"] = "Y";
- $arSettings["CODE"]["DEFAULT_VALUE"]["TRANSLITERATION"] = "Y";
- if(!isset($arIBlocks[$arProperty["CODE"]]))
- {
- if(!($iIBlockID = $obNewIBlock->Add($arFields)))
- {
- self::exception("AF: Error creating infoblock - ".$obNewIBlock->LAST_ERROR);
- $APPLICATION->ThrowException("AF: Error creating infoblock - ".$obNewIBlock->LAST_ERROR);
- }
- }
- else
- {
- $iIBlockID = $arIBlocks[$arProperty["CODE"]];
- /*if(!($obNewIBlock->Update($iIBlockID, $arFields)))
- {
- self::exception("AF: Error creating infoblock - ".$obNewIBlock->LAST_ERROR);
- $APPLICATION->ThrowException("AF: Error creating infoblock - ".$obNewIBlock->LAST_ERROR);
- }*/
- }
- CIBlock::SetFields($iIBlockID, $arSettings);
- }
- return $iIBlockID;
- }
- public static function syncProperties()
- {
- $obSkuProperties = CIBlockProperty::GetList(Array(),Array("IBLOCK_ID"=>IB_CATALOG));
- $arSkuProperties = Array();
- while($arSkuProperty = $obSkuProperties->Fetch())
- {
- $arSkuProperties[$arSkuProperty["CODE"]]=$arSkuProperty;
- }
- $obCatProperties = CIBlockProperty::GetList(Array(),Array("IBLOCK_ID"=>IB_SKU));
- $arCatProperties = Array();
- $iPropertySort=0;
- while($arCatProperty = $obCatProperties->Fetch())
- {
- if(in_array($arCatProperty["CODE"],self::$propsExeption)) continue;
- if(preg_match("#^CML2_#",$arCatProperty["XML_ID"]) || preg_match(self::$xmlRegex,$arCatProperty["XML_ID"]))
- {
- switch($arCatProperty["PROPERTY_TYPE"])
- {
- case "F":
- $arPropertyFields = Array(
- "NAME" => $arCatProperty["NAME"],
- "ACTIVE" => "Y",
- "SORT" => $iPropertySort,
- "CODE" => $arCatProperty["CODE"],
- "PROPERTY_TYPE" => "F",
- "IBLOCK_ID" => IB_CATALOG,
- "WITH_DESCRIPTION" => "Y",
- "MULTIPLE"=>"Y",
- "XML_ID"=>""
- );
- break;
- default:
- $arPropertyFields = Array(
- "NAME" => $arCatProperty["NAME"],
- "ACTIVE" => "Y",
- "SORT" => $iPropertySort,
- "CODE" => $arCatProperty["CODE"],
- "PROPERTY_TYPE" => "S",
- "IBLOCK_ID" => IB_CATALOG,
- "WITH_DESCRIPTION" => "Y",
- "MULTIPLE"=>"Y",
- "MULTIPLE_CNT"=>1,
- "XML_ID"=>""
- );
- if(in_array($arCatProperty["CODE"], self::$linkerProperties) && ($iIBlockID = self::processLinkerIBlock($arPropertyFields)))
- {
- $arPropertyFields["PROPERTY_TYPE"]="E";
- $arPropertyFields["LINK_IBLOCK_ID"]=$iIBlockID;
- }
- break;
- }
- $obNewProperty = new CIBlockProperty();
- $iPropertySort++;
- if(!isset($arSkuProperties[$arCatProperty["CODE"]]))
- {
- if(!$obNewProperty->Add($arPropertyFields))
- {
- self::exception("AF: Error creating property - ".$obNewProperty->LAST_ERROR,__LINE__);
- }
- }
- else
- {
- $iPropertyID = $arSkuProperties[$arCatProperty["CODE"]]["ID"];
- //printra("upd ",$iPropertyID,$arPropertyFields);
- if(0)
- {
- //&&!$obNewProperty->Update($iPropertyID,$arPropertyFields)
- self::exception("AF: Error updating property - ".$obNewProperty->LAST_ERROR,__LINE__);
- }
- }
- $arSkuProperties[$arCatProperty["CODE"]]=$arPropertyFields;
- $arCatProperties[$arCatProperty["CODE"]]=$arCatProperty;
- }
- }
- return true;
- }
- public static function syncSections()
- {
- $arResult=Array();
- /**
- * Get SKU + Catalog Sections
- */
- self::setNoHandler(true);
- $arSelect = Array(
- "ID",
- "NAME",
- "IBLOCK_ID",
- "ACTIVE",
- "IBLOCK_SECTION_ID",
- "XML_ID",
- "SORT",
- "UF_*"
- );
- $obSections = CIBlockSection::getList(
- Array("DEPTH_LEVEL"=>"ASC"),
- Array("IBLOCK_ID"=>IB_CATALOG),
- false,
- $arSelect
- );
- while($arSection = $obSections->fetch())
- {
- $arResult["CATALOG"][$arSection["XML_ID"]]=$arSection;
- }
- $obSections = CIBlockSection::getList(
- Array("DEPTH_LEVEL"=>"ASC"),
- Array("IBLOCK_ID"=>IB_SKU),
- false,
- $arSelect
- );
- while($arSection = $obSections->fetch())
- {
- $arResult["SKU"][$arSection["ID"]]=$arSection;
- }
- $sHash = md5(serialize($arResult));
- /**
- * Cache block
- */
- $iCacheTime=360000000;
- $sCacheDir="/migration/sections";
- $obCache = new CPHPCache();
- if(!$obCache->InitCache($iCacheTime, $sHash, $sCacheDir))
- {
- $obCache->StartDataCache();
- global $CACHE_MANAGER;
- $CACHE_MANAGER->StartTagCache($sCacheDir);
- $obNewSection = new CIBlockSection();
- foreach($arResult["SKU"] as $arSection)
- {
- $sCRC = md5(serialize($arSection));
- $arFields = Array(
- "IBLOCK_ID"=>IB_CATALOG,
- "ACTIVE"=>$arSection["ACTIVE"],
- "UF_CRC"=>$sCRC,
- "SORT"=>$arSection["SORT"],
- "NAME"=>$arSection["NAME"],
- "XML_ID"=>"cat_{$arSection["ID"]}",
- "IBLOCK_SECTION_ID"=>$arResult["CATALOG"]["cat_{$arSection["IBLOCK_SECTION_ID"]}"]["ID"],
- "CODE"=>CUtil::translit($arSection["NAME"],"ru",self::$translit)
- );
- if(isset($arResult["CATALOG"]["cat_{$arSection["ID"]}"]))
- {
- $arCatSection = $arResult["CATALOG"]["cat_{$arSection["ID"]}"];
- if($arCatSection["UF_CRC"]!=$sCRC)
- {
- if(!$obNewSection->Update($arCatSection["ID"],$arFields,false))
- {
- self::exception($obNewSection->LAST_ERROR,$arFields);
- }
- }
- }
- else
- {
- if($iItemID = $obNewSection->Add($arFields,false))
- {
- $arResult["CATALOG"]["cat_{$arSection["ID"]}"]=Array("ID"=>$iItemID)+$arFields;
- }
- else
- {
- self::exception($obNewSection->LAST_ERROR,$arFields);
- }
- }
- }
- /**
- * Deactivate sections
- */
- /*foreach($arResult["CATALOG"] as $arCatSection)
- {
- if(preg_match("#^cat_(\d+)$#",$arCatSection["XML_ID"],$arMatches))
- {
- $iSKUSectionID = IntVal($arMatches[1]);
- if(isset($ar))
- }
- }*/
- CIBlockSection::ReSort(IB_CATALOG);
- $CACHE_MANAGER->RegisterTag(IB_CATALOG);
- $CACHE_MANAGER->EndTagCache();
- $obCache->EndDataCache($arResult);
- }
- else
- {
- $arResult = $obCache->GetVars();
- }
- self::setNoHandler(false);
- self::setParams(Array("action"=>"saveFiles"));
- return true;
- }
- public static function saveFiles()
- {
- $docRoot = $_SERVER["DOCUMENT_ROOT"];
- /**
- * Get Linker IBlocks Values
- * $GLOBALS["LINK_IB"][$iIBlockID][$sName]=$iItemID;
- */
- $GLOBALS["LINK_IB"]=Array();
- $obItems = \Bitrix\Iblock\ElementTable::getList(
- Array(
- "filter"=>Array(
- "IBLOCK.TYPE.ID"=>"links",
- "WF_PARENT_ELEMENT_ID"=>false
- ),
- "select"=>Array("*")
- )
- );
- $GLOBALS["LINK_IB"]=Array();
- while($arItem = $obItems->Fetch())
- {
- $GLOBALS["LINK_IB"][$arItem["IBLOCK_ID"]][$arItem["NAME"]]=$arItem["ID"];
- }
- /**
- * Get SKU Section Links
- */
- $obItemSections = \Bitrix\Iblock\SectionElementTable::getList(
- Array(
- "filter" => Array(
- "IBLOCK_SECTION.IBLOCK_ID" => IB_SKU
- )
- )
- );
- $arItemToSections = Array();
- while($arItem = $obItemSections->Fetch())
- {
- $arItemToSections[$arItem["IBLOCK_ELEMENT_ID"]][]=$arItem["IBLOCK_SECTION_ID"];
- }
- /**
- * Get Section to section Link
- */
- $obSections = \Bitrix\Iblock\SectionTable::getList(Array(
- "filter"=>Array(
- "IBLOCK_ID"=>IB_CATALOG
- ),
- "select"=>Array("ID","XML_ID")
- ));
- $arSKUSectionToCatSection=Array();
- while($arSection = $obSections->fetch())
- {
- if(preg_match("#^cat_(\d+)$#",$arSection["XML_ID"],$arMatches))
- {
- $arSKUSectionToCatSection[$arMatches[1]]=$arSection["ID"];
- }
- }
- /**
- * Get Properties link
- */
- $obSkuProperties = CIBlockProperty::GetList(Array(),Array("IBLOCK_ID"=>IB_SKU));
- $arProperties = Array();
- $iGroupNameID = 0;
- $iGroupListNameID = 0;
- while($arSkuProperty = $obSkuProperties->Fetch())
- {
- if($arSkuProperty["CODE"]=="GROUP_NAME") $iGroupNameID=$arSkuProperty["ID"];
- if($arSkuProperty["CODE"]=="GROUP_NAME_LIST") $iGroupListNameID=$arSkuProperty["ID"];
- $arSkuProperties[$arSkuProperty["CODE"]]=$arSkuProperty["ID"];
- $arProperties[$arSkuProperty["ID"]]=$arSkuProperty;
- }
- $obCatProperties = CIBlockProperty::GetList(Array(),Array("IBLOCK_ID"=>IB_CATALOG));
- $arPropertiesCatalogToSKULink = Array();
- $arCRCProperties = Array();
- while($arCatProperty = $obCatProperties->Fetch())
- {
- if(substr_count($arCatProperty["CODE"],"CRC_"))
- {
- $arCRCProperties[]=$arCatProperty["CODE"];
- continue;
- }
- if(isset($arSkuProperties[$arCatProperty["CODE"]]))
- {
- $arPropertiesCatalogToSKULink[$arSkuProperties[$arCatProperty["CODE"]]]=$arCatProperty["CODE"];
- }
- }
- /**
- * Get Properties enum values
- */
- $arPropertyEnumToValue=Array();
- $arPropertyEnumToXMLID=Array();
- foreach($arProperties as $iPropertyID=>$arProperty)
- {
- if($arProperty["PROPERTY_TYPE"]=="L")
- {
- $obEnum = CIBlockProperty::GetPropertyEnum($iPropertyID);
- while($arItem = $obEnum->Fetch())
- {
- $arPropertyEnumToValue[$arItem["ID"]]=$arItem["VALUE"];
- $arPropertyEnumToXMLID[$arItem["ID"]]=$arItem["XML_ID"];
- }
- }
- }
- /**
- * Get Catalog element links
- */
- $arSSelect = Array("ID","XML_ID");
- foreach($arCRCProperties as $sCode) $arSSelect[]="PROPERTY_{$sCode}";
- $obCatItems = CIBlockElement::GetList(Array(),Array("IBLOCK_ID"=>IB_CATALOG),false,false,$arSSelect);
- $arCatItemsLink = Array();
- while($arCatItem = $obCatItems->fetch())
- {
- $arCatItemsLink[$arCatItem["XML_ID"]]=$arCatItem;
- }
- /**
- * Get SKU With Properties and Prices
- */
- $arLinkerIBlocks = self::GetLinkerIBlocks();
- $iTime = microtime(1);
- $arSelect = Array(
- "ID",
- "XML_ID",
- "NAME",
- "ACTIVE",
- "PROPERTY_*",
- "PROPERTY_ENUM_*",
- "PROPERTY_XML_ID_*",
- "CATALOG_QUANTITY"
- );
- $arSelect[]="CATALOG_GROUP_".BASE_PRICE_ID;
- $obSKUItems = CIBlockElement::GetList(
- Array(),
- Array(
- "ACTIVE"=>"Y",
- "IBLOCK_ID" => IB_SKU,
- Array(
- "LOGIC"=>"OR",
- Array("!PROPERTY_GROUP_NAME"=>false),
- Array("!PROPERTY_GROUP_NAME_LIST"=>false)
- )
- ),
- false,
- false,
- $arSelect
- );
- $arResult = Array();
- while($arItem = $obSKUItems->Fetch())
- {
- $sGroupName = self::cleanString($arItem["PROPERTY_{$iGroupNameID}"]);
- $sGroupNameList = self::cleanString($arPropertyEnumToValue[$arItem["PROPERTY_{$iGroupListNameID}"]]);//self::cleanString($arItem["PROPERTY_{$iGroupNameID}"]);
- $sGroupNameListXML = $arPropertyEnumToXMLID[$arItem["PROPERTY_{$iGroupListNameID}"]];
- unset($arItem["PROPERTY_{$iGroupNameID}"]);
- unset($arItem["DESCRIPTION_{$iGroupNameID}"]);
- if(!$sGroupName && !$sGroupNameListXML) continue;
- $sToMD5 = $sGroupNameListXML?:CUtil::translit($sGroupName,"ru",self::$translit);
- $sGroupXMLID = "cat_".md5($sToMD5);
- if(!isset($arResult[$sGroupXMLID]))
- {
- $sElementName = $sGroupNameList?:$sGroupName;
- $arResult[$sGroupXMLID]=Array(
- "FIELDS"=>Array(
- "IBLOCK_ID"=>IB_CATALOG,
- "ACTIVE"=>"Y",
- "NAME" => $sElementName,
- "XML_ID" => $sGroupXMLID,
- "CODE"=>CUtil::translit($sGroupName,"ru",self::$translit),
- "CATALOG_AVAILABLE"=>"N",
- "CATALOG_QUANTITY"=>0
- ),
- "PROPERTIES"=>Array("ACTIVE"=>false),
- "SECTIONS"=>Array(),
- "PRICES"=>Array(),
- "SKU_ITEMS"=>Array(),
- "CRC"=>Array()
- );
- }
- $arCatItem = &$arResult[$sGroupXMLID];
- $arCatItemFields = &$arCatItem["FIELDS"];
- $arCatItemProperties = &$arCatItem["PROPERTIES"];
- $arCatItemSections = &$arCatItem["SECTIONS"];
- $arCatPrices = &$arCatItem["PRICES"];
- $arCatItemSKU = &$arCatItem["SKU_ITEMS"];
- /**
- * Заполненные значения в каталоге + CRC
- */
- if(isset($arCatItemsLink[$sGroupXMLID]))
- {
- $arWasCatItem = $arCatItemsLink[$sGroupXMLID];
- $arCatItemFields["ID"]=$arWasCatItem["ID"];
- foreach($arWasCatItem as $sCode=>$sValue)
- {
- if(preg_match("#^PROPERTY_CRC_(\S+)_VALUE$#",$sCode,$arMatches))
- {
- $arCatItem["CRC"][$arMatches[1]]=$sValue;
- }
- }
- }
- else
- {
- //printr($arCatItem["FIELDS"]["NAME"],$sGroupXMLID);
- }
- /**
- * Перегон разделов
- */
- if(isset($arItemToSections[$arItem["ID"]]) && $sGroupXMLID)
- {
- foreach($arItemToSections[$arItem["ID"]] as $iSectionID)
- {
- if(isset($arSKUSectionToCatSection[$iSectionID]))
- {
- $iCatSectionID = $arSKUSectionToCatSection[$iSectionID];
- if(!in_array($iCatSectionID,$arCatItemSections))
- {
- $arCatItemSections[]=$iCatSectionID;
- }
- }
- }
- }
- /**
- * Перегон всех свойств в формат свойств для каталога.
- */
- foreach($arItem as $sCode=>$arValues)
- {
- if(preg_match("#^PROPERTY_(\d+)$#",$sCode,$arMatches))
- {
- $iPropertyID = IntVal($arMatches[1]);
- if(isset($arPropertiesCatalogToSKULink[$iPropertyID]))
- {
- if(!is_array($arValues))
- {
- $arValues = Array($arValues);
- $arItem["DESCRIPTION_{$iPropertyID}"]=Array($arItem["DESCRIPTION_{$iPropertyID}"]);
- }
- $iCatPropertyID = $arPropertiesCatalogToSKULink[$iPropertyID];
- if(!isset($arCatItemProperties[$iCatPropertyID]))
- {
- $arCatItemProperties[$iCatPropertyID]=Array();
- }
- $sPropertyType = $arProperties[$iPropertyID]["PROPERTY_TYPE"];
- $sPropertyCode = $arProperties[$iPropertyID]["CODE"];
- foreach($arValues as $iKey=>$value)
- {
- switch($sPropertyType)
- {
- case "L":
- $enumID = $value;
- $value=$arPropertyEnumToValue[$value];
- if(in_array($sPropertyCode,self::$linkerProperties) && (isset($arLinkerIBlocks[$sPropertyCode])))
- {
- if($sPropertyCode=="WORK_TYPE")
- {
- $arValuesStr = explode("/",$value);
- $value = Array();
- foreach($arValuesStr as $iKey=>$sValue)
- {
- if($sValue = trim($sValue))
- {
- $value[]=CIBlockExt::TouchPropertyElement($sValue,$arLinkerIBlocks[$sPropertyCode]);
- }
- }
- }
- elseif($sPropertyCode=="COLOR")
- {
- $value=CIBlockExt::TouchPropertyElement($value,$arLinkerIBlocks[$sPropertyCode], $arPropertyEnumToXMLID[$enumID]);
- }
- else
- {
- $value=CIBlockExt::TouchPropertyElement($value,$arLinkerIBlocks[$sPropertyCode]);
- }
- }
- break;
- default:
- break;
- }
- if(!is_array($value))
- {
- $value=self::cleanString($value);
- $sDescription = self::cleanString($arItem["DESCRIPTION_{$iPropertyID}"][$iKey]);
- }
- else
- {
- if(empty($value))
- {
- $value=false;
- }
- }
- /*if(!in_array($value,$arCatItemProperties[$iCatPropertyID]["VALUE"]))
- {
- $arCatItemProperties[$iCatPropertyID]["VALUE"][$iKey]=$value;
- $arCatItemProperties[$iCatPropertyID]["DESCRIPTION"][$iKey]=$sDescription;
- }*/
- /**
- * Hack with no description. Upper variant doesn't work. Debug yourself.
- */
- if(is_array($value))
- {
- foreach($value as $oneValue)
- {
- if(!in_array($oneValue,$arCatItemProperties[$iCatPropertyID]))
- {
- $arCatItemProperties[$iCatPropertyID][]=$oneValue;
- }
- }
- }
- elseif(!in_array($value,$arCatItemProperties[$iCatPropertyID]))
- {
- $arCatItemProperties[$iCatPropertyID][]=$value;
- }
- }
- if(empty($arCatItemProperties[$iCatPropertyID])) $arCatItemProperties[$iCatPropertyID]=false;
- }
- }
- }
- /**
- * Перегон цен и остатков
- */
- if($iPrice = FloatVal($arItem["CATALOG_PRICE_".BASE_PRICE_ID]))
- {
- if(($sCurrency = $arItem["CATALOG_CURRENCY_".BASE_PRICE_ID])!="RUB")
- {
- $iPrice = CCurrencyRates::ConvertCurrency($iPrice,$sCurrency,"RUB");
- }
- if(($arItem["CATALOG_QUANTITY"]>0) && ($iPrice>0))
- {
- $arCatItemFields["CATALOG_AVAILABLE"]="Y";
- $arCatItemFields["CATALOG_QUANTITY"]+=$arItem["CATALOG_QUANTITY"];
- $arCatItemProperties["ACTIVE"]=1;
- $arCatPrices[]=$iPrice;
- }
- }
- $arCatItemSKU[]=$arItem["ID"];
- }
- //die();
- ArrayToFile($arResult, "arCatItems", $docRoot.self::$dir.self::$catFile);
- //die();
- self::setParams(Array("action"=>"processCatalogItems"));
- return true;
- }
- public static function arrayCRC($array)
- {
- return md5(serialize($array));
- }
- public static function processCatalogItems()
- {
- $docRoot = $_SERVER["DOCUMENT_ROOT"];
- /**
- * @var $arCatItems array
- */
- include($docRoot.self::$dir.self::$catFile);
- $obNewElement = new CIBlockElement();
- $iTime = microtime(1);
- $bAnotherTime = false;
- self::setNoHandler(true);
- $iProcessed = 0;
- foreach($arCatItems as $iKey=>$arElement)
- {
- $iProcessed++;
- if(IntVal($arElement["PROCESSED"])) continue;
- $bUpdated = false;
- $iCatElementID = 0;
- /**
- * Create catalog element
- */
- if(IntVal($arElement["FIELDS"]["ID"]))
- {
- $iCatElementID=$arElement["FIELDS"]["ID"];
- if(self::arrayCRC($arElement["FIELDS"])!=$arElement["CRC"]["FIELDS"])
- {
- unset($arElement["FIELDS"]["CODE"]);
- if(!$obNewElement->Update($iCatElementID,$arElement["FIELDS"]))
- {
- self::exception($obNewElement->LAST_ERROR,$arElement["FIELDS"],__LINE__);
- }
- $arCatalogUpdate=Array(
- "ID"=>$iCatElementID,
- "AVAILABLE"=>$arElement["FIELDS"]["CATALOG_AVAILABLE"],
- "QUANTITY"=>$arElement["FIELDS"]["CATALOG_QUANTITY"]
- );
- CCatalogProduct::Add($arCatalogUpdate);
- $bUpdated=true;
- }
- }
- else
- {
- ///printra($arElement);
- if(!($iCatElementID = $obNewElement->Add($arElement["FIELDS"])))
- {
- self::exception($obNewElement->LAST_ERROR,$arElement["FIELDS"],__LINE__);
- }
- }
- /**
- * Set sections
- */
- if(self::arrayCRC($arElement["SECTIONS"])!=$arElement["CRC"]["SECTIONS"])
- {
- CIBlockElement::SetElementSection($iCatElementID,$arElement["SECTIONS"]);
- $bUpdated=true;
- }
- /**
- * Set properties
- */
- $arElement["PROPERTIES"]["PRICE_FROM"]=min($arElement["PRICES"]);
- $arElement["PROPERTIES"]["PRICE_TO"]=max($arElement["PRICES"]);
- $sCurrentCRC=self::arrayCRC($arElement["PROPERTIES"]);
- $arNewCRC = Array(
- "CRC_PROPERTIES"=>self::arrayCRC($arElement["PROPERTIES"]),
- "CRC_SECTIONS"=>self::arrayCRC($arElement["SECTIONS"]),
- "CRC_FIELDS"=>self::arrayCRC($arElement["FIELDS"]),
- "CRC_SKU_ITEMS"=>self::arrayCRC($arElement["SKU_ITEMS"]),
- );
- $arElement["PROPERTIES"]+=$arNewCRC;
- if($bUpdated || ($sCurrentCRC!=$arElement["CRC"]["PROPERTIES"]))
- {
- CIBlockElement::SetPropertyValuesEx($iCatElementID,IB_CATALOG,$arElement["PROPERTIES"]);
- $bUpdated=true;
- }
- /**
- * Link SKU Items
- */
- if(self::arrayCRC($arElement["SKU_ITEMS"])!=$arElement["CRC"]["SKU_ITEMS"])
- {
- foreach($arElement["SKU_ITEMS"] as $iSKUItemID)
- {
- CIBlockElement::SetPropertyValuesEx($iSKUItemID,IB_SKU,Array("CML2_LINK"=>$iCatElementID));
- }
- $bUpdated=true;
- }
- if($bUpdated)
- {
- //CIBlockElement::UpdateSearch($iCatElementID,true);
- CIBlockExt::RunUpdate($iCatElementID);
- CCacheClean::CatalogElement($iCatElementID);
- \Bitrix\Iblock\PropertyIndex\Manager::updateElementIndex(IB_CATALOG, $iCatElementID);
- }
- $arCatItems[$iKey]=Array(
- "PROCESSED"=>1,
- "ID"=>$iCatElementID
- );
- if(time()-$iTime>15)
- {
- $bAnotherTime = true;
- break;
- }
- }
- self::setNoHandler(false);
- ArrayToFile($arCatItems, "arCatItems", $docRoot.self::$dir.self::$catFile);
- if($bAnotherTime)
- {
- $params = self::getParams();
- $params["processed"] = "{$iProcessed} / ".count($arCatItems);
- self::logToFile("Processed ".$params["processed"]);
- self::setParams($params);
- }
- else
- {
- self::setParams(Array("action"=>"deactivateItems"));
- }
- return !$bAnotherTime;
- }
- public static function deactivateItems()
- {
- $docRoot = $_SERVER["DOCUMENT_ROOT"];
- /**
- * @var $arCatItems array
- */
- require($docRoot.self::$dir.self::$catFile);
- $bAnotherTime = false;
- $iTime = microtime(1);
- $obNewElement = new CIBlockElement();
- self::setNoHandler(true);
- $iProcessed=0;
- $arIDs = Array();
- foreach($arCatItems as $arItem)
- {
- $arIDs[]=$arItem["ID"];
- }
- $iCount = 0;
- if(!empty($arIDs))
- {
- $obItems = $obNewElement->GetList(
- Array(),
- Array(
- "IBLOCK_ID"=>IB_CATALOG,
- "ACTIVE"=>"Y",
- "!ID"=>$arIDs
- ),
- false,
- false,
- Array("ID")
- );
- $iCount=$obItems->SelectedRowsCount();
- while($arItem = $obItems->Fetch())
- {
- $iProcessed++;
- $obNewElement->Update($arItem["ID"],Array("ACTIVE"=>"N"));
- if(time()-$iTime>15)
- {
- $bAnotherTime=true;
- break;
- }
- }
- }
- if($bAnotherTime)
- {
- $params = self::getParams();
- $params["processed"] = "{$iProcessed} / ".$iCount;
- self::setParams($params);
- self::logToFile("Processed ".$params["processed"]);
- ArrayToFile($arCatItems, "arCatItems", $docRoot.self::$dir.self::$catFile);
- }
- else
- {
- //self::setParams(Array());
- self::setParams(Array("action"=>"updateSearch"));
- }
- self::setNoHandler(false);
- return !$bAnotherTime;
- }
- public static function updateSearch()
- {
- $obInstance = new CYandexSearch;
- $obInstance->SaveYMLFile();
- self::setParams(Array());
- return true;
- }
- public static function cleanString($s)
- {
- return trim(preg_replace("#[ ]+#", " ", $s));
- }
- private function __clone(){}
- private function __construct()
- {
- $docRoot = $_SERVER["DOCUMENT_ROOT"];
- CheckDirPath($docRoot.self::$dir);
- touch($docRoot.self::$dir.self::$paramFile);
- touch($docRoot.self::$dir.self::$catFile);
- self::$params=self::getParams();
- }
- public static function getInstance()
- {
- if(null === self::$_instance)
- {
- self::$_instance = new self();
- }
- return self::$_instance;
- }
- }
Add Comment
Please, Sign In to add comment