Услуги профессионального Битрикс-программиста

Подгрузка фото к товарам из 1С


Фото в 1С не хранятся, из-за экономии места, задача обновлять с фтп, выводить товары только те, для которых есть с фото
сделала на обработчиках в init.php
AddEventHandler( "iblock", "OnBeforeIBlockElementAdd", "MyOnBeforeIBlockElementAdd");
AddEventHandler( "iblock", "OnBeforeIBlockElementUpdate", "MyOnBeforeIBlockElementUpdate");
UploadMorePhotos - непосредственно функция, которая по артикулу загружает фотки
вызывается при добавлении и изменении
здесь загружены обработчики целиком (мне на память), т.е. они еще название меняют, цвета обобщенные и тд
function MyOnBeforeIBlockElementAdd(&$arFields){
    $arCatalogID = array(9, 10); //9-man, 10-woman
    $arOfferID = array(13, 14); //13-man, 14-woman
    

    if(in_array($arFields['IBLOCK_ID'], $arCatalogID) && CModule::IncludeModule('iblock')){ 
        $articlePropId = ($arFields['IBLOCK_ID'] == 9) ? 288 : 297;
        //получаем артикул
        foreach($arFields["PROPERTY_VALUES"][$articlePropId] as $arProp){
            if(isset($arProp["VALUE"])){                
                $article_full = trim($arProp["VALUE"]);
               
                break;
            }
        }                
        UploadMorePhotos($arFields,$article_full); //собственно вот она
        $brandName = GetSetBrand($arFields);
        if(!empty($brandName) && !empty($article_full)) {                           
            $arFields["NAME"] = trim($article_full).' '.trim($brandName);                   
        }                
    }
    if((in_array($arFields['IBLOCK_ID'], $arCatalogID)||in_array($arFields['IBLOCK_ID'], $arOfferID)) && isset($arFields["PROPERTY_VALUES"]) && CModule::IncludeModule('highloadblock')){
        SetGeneralColors($arFields);
    }
}
function MyOnBeforeIBlockElementUpdate(&$arFields){
    //AddMessage2Log($arFields);
    $arCatalogID = array(9, 10); //9-man, 10-woman
    $arOfferID = array(13, 14); //13-man, 14-woman
    
    if(in_array($arFields['IBLOCK_ID'], $arCatalogID) && CModule::IncludeModule('iblock')){        
        if(isset($arFields["PROPERTY_VALUES"])){
            $articlePropId = ($arFields['IBLOCK_ID'] == 9) ? 288 : 297;    
            //получаем артикул
            $article_full = "";
            if(isset($arFields["PROPERTY_VALUES"][$articlePropId])){
                foreach($arFields["PROPERTY_VALUES"][$articlePropId] as $arProp){
                    if(isset($arProp["VALUE"])){                
                        $article_full = trim($arProp["VALUE"]);                            
                        break;
                    }
                    else{
                        
                    }
                }
            }
            else{
                $arSelect = Array("NAME", "PROPERTY_".$articlePropId);
                $arFilter = Array("IBLOCK_ID"=>$arCatalogID, "ID"=>$arFields['ID']);
                $result = CIBlockElement::GetList(Array(), $arFilter, false, array(), $arSelect);
                if($arElement = $result->GetNext()){                
                    $article_full = trim($arElement['PROPERTY_'.$articlePropId.'_VALUE']);                                
                }

            }
            
            UploadMorePhotos($arFields,$article_full);
            $brandName = GetSetBrand($arFields);
            if(!empty($brandName) && !empty($article_full)) {                           
                $arFields["NAME"] = trim($article_full).' '.trim($brandName);                   
            } 



        }
        else{
            $arSelect = Array("ACTIVE", "ID");
            $arFilter = Array("IBLOCK_ID"=>$arFields['IBLOCK_ID'], "ID"=>$arFields['ID']);
            $result = CIBlockElement::GetList(Array(), $arFilter, false, array(), $arSelect);
            if($arElement = $result->Fetch()){                
                $arFields["ACTIVE"] = $arElement["ACTIVE"];
            }            
        }
    }

    if((in_array($arFields['IBLOCK_ID'], $arCatalogID)||in_array($arFields['IBLOCK_ID'], $arOfferID)) && isset($arFields["PROPERTY_VALUES"]) && CModule::IncludeModule('highloadblock')){
        SetGeneralColors($arFields);
    }
}
вспомогательная функция
function array_orderby()
{
    $args = func_get_args();
    $data = array_shift($args);
    foreach ($args as $n => $field) {
        if (is_string($field)) {
            $tmp = array();
            foreach ($data as $key => $row)
                $tmp[$key] = $row[$field];
            $args[$n] = $tmp;
            }
    }
    $args[] = &$data;
    call_user_func_array('array_multisort', $args);
    return array_pop($args);
}
function UploadMorePhotos(&$arFields,$article){
    if(!empty($arFields['IBLOCK_ID'])){
        $photosPropId = ($arFields['IBLOCK_ID'] == 9) ? 293 : 302;
        if(!empty($article)){
            $article = explode(" ", $article);
            $article = $article[0];
                       
            if(isset($arFields["PROPERTY_VALUES"][$photosPropId])){                
                foreach($arFields["PROPERTY_VALUES"][$photosPropId] as $photoKey => &$arPhotoOld){
                    $arPhotoOld["VALUE"]["del"]="Y";                    
                }
            }           
            
            $arPhotos = [];               
            if (is_dir($p = $_SERVER["DOCUMENT_ROOT"]."/upload/photos/".$article)){                
                if($dir = opendir($p)){        
                    $i=0;
                    if(!isset($arFields["PROPERTY_VALUES"][$photosPropId])){                        
                        $arFields["PROPERTY_VALUES"][$photosPropId] = [];                        
                        $res = CIBlockElement::GetProperty($arFields["IBLOCK_ID"], $arFields["ID"], "sort", "asc", array("ID" => $photosPropId));
                        while ($ob = $res->GetNext()){                            
                            $arFields["PROPERTY_VALUES"][$photosPropId][$ob["PROPERTY_VALUE_ID"]]["VALUE"]["del"]="Y";
                        }                        
                    }
                    
                    while (false !== $item = readdir($dir)){                        
                        $photo = CFile::MakeFileArray($p."/".$item);       
                        //$photo["DESCRIPTION"] = $arFields["NAME"]."_".$i."_".time(); 
                        if(!empty($photo['size'])){
                            $arPhotos[] = $photo;    
                        }                        
                    }                    
                    $arPhotos = array_orderby($arPhotos, 'name', SORT_ASC);  //сортируем по названию                  
                    foreach($arPhotos as  $arPhoto){                        
                        $arFields["PROPERTY_VALUES"][$photosPropId][] = $arPhoto;   
                    }    
                    $arFields["DETAIL_PICTURE"] = $arFields["PREVIEW_PICTURE"] = $arPhotos[0] ?? false;
                     
                    $i++;
                    closedir($dir);
                }
            }
            if(empty($arPhotos)){                
               $arFields["ACTIVE"] = "N"; 
            }
        }
        else{
            $arFields["ACTIVE"] = "N";
        }
    }
    //AddMessage2Log($arPhotos);
    return ($arFields["ACTIVE"]=="Y");
}


старое

скрипт, который обходит товары
"iNumPage"=>1 меняем на 2,3,4 и тд
//die();
//$param = "man";
$param = "woman";


if($param  == "man"){
    $iblockId = 9;
    $articlePropId = 288;
}
else{
    $iblockId = 10;
    $articlePropId = 297;
}
CModule::IncludeModule('iblock');
$arFilter = Array(
  "IBLOCK_ID"=>$iblockId
);

$arSelect = Array("ID","IBLOCK","PROPERTY_".$articlePropId,"ACTIVE");
$res = CIBlockElement::GetList(Array("id"=>"asc"), $arFilter, false, Array("nPageSize"=>10000,"iNumPage"=>1), $arSelect);

$el = new CIBlockElement; 
while($arItem = $res->Fetch()){
   $vendorCode = $arItem["PROPERTY_".$articlePropId."_VALUE"];
   $arUpd = [];
    $detailPicture = false;
    $arPhotos = [];
    if(!empty($vendorCode)){
        $article = trim($vendorCode);
        $article = explode(" ", $article);
        $article = $article[0];
        $t = $_SERVER["DOCUMENT_ROOT"]."/upload/photos/".$article;
        if (is_dir($p = $_SERVER["DOCUMENT_ROOT"]."/upload/photos/".$article)){
            if ($dir = opendir($p)){                
                while (false !== $item = readdir($dir)){               
                    if(!$detailPicture){
                        $detailPicture = CFile::MakeFileArray($p."/".$item);                       
                    }                     
                    $arPhotos[] = CFile::MakeFileArray($p."/".$item);                    
                }
                closedir($dir);
            }
        }
    }
    
    if($detailPicture){
        $arUpd["PREVIEW_PICTURE"] = $detailPicture;
        $arUpd["DETAIL_PICTURE"] = $detailPicture;    
        $arUpd["ACTIVE"] = "Y";       
        sort($arPhotos);
        CIBlockElement::SetPropertyValuesEx( $arItem['ID'], false, array("MORE_PHOTO" => $arPhotos ) );               
        
    }
    elseif($arItem["ACTIVE"]=="Y"){  
        $arUpd["ACTIVE"] = "N";                  
    }    
   
    if(!empty($arUpd)){       
        $result = $el->Update($arItem['ID'], $arUpd);                       
        if(!$result){
           echo $el->LAST_ERROR;
        }
    }   
}
обработчики, которые деактивируют товары при загрузке из 1С без фото
init.php
AddEventHandler( "iblock", "OnBeforeIBlockElementAdd", array( "nika_import", "Deactive" ));
AddEventHandler( "iblock", "OnBeforeIBlockElementUpdate", array( "nika_import", "DeactiveWithNoPhotos" ) );
class nika_import {
    function Deactive(&$arFields){//всегда деактивируем при добавлении, потому что фотки из 1С не выгружаются, будем активировать, когда фотки будем добавлять
        $arCatalogID = array(9, 10);
        if(in_array($arFields['IBLOCK_ID'], $arCatalogID) ){
            $arFields["ACTIVE"] = "N";
        }
    }
    function DeactiveWithNoPhotos(&$arFields){//деактивируем, если нет фоток
       $arCatalogID = array(9, 10);
        if(in_array($arFields['IBLOCK_ID'], $arCatalogID) ){
            
            if(empty($arFields["DETAIL_PICTURE"])){
                $arSelect = Array("ID");
                $arFilter = Array(
                    "IBLOCK_ID"=>$arFields['IBLOCK_ID'], 
                    "ID"=>$arFields['ID'],
                    "DETAIL_PICTURE" => false
                );
                $result = CIBlockElement::GetList(Array(), $arFilter, false, array(), $arSelect);
                if($arElement = $result->GetNext()){
                    $arFields["ACTIVE"] = "N";
                }
            }
        } 
    }
}
Вероника Малышева
Битрикс-программист
+7 (953) 585-13-09

Если пост был полезным, можете угостить меня "чашечкой кофе" :)
Сбер, Альфа: по номеру телефона +7 (953) 585-13-09.
Спасибо!
Смотреть все посты