Current Path : /home/bitrix/ext_www/ballu.in.ua/import/ |
Current File : /home/bitrix/ext_www/ballu.in.ua/import/.functions.php |
<? // вывод переменной с новой строкой function echol($str){ if(!empty($str)){ if(is_array($str)){ print_r($str); echo "\n"; }else echo $str."\n"; } } // вывод переменной с пробелом function echos($str, $sep=""){ if(!empty($str)){ if(is_array($str)){ foreach($str as $st) echo $st." "; }else echo $str." "; } } function removeBOM($str=""){ if(substr($str, 0,3) == pack("CCC",0xef,0xbb,0xbf)) { $str=substr($str, 3); } return $str; } function ReadCSV($file){ if(!is_file($file)) return false; clearBom($file); $handle = fopen($file, "r"); while (!feof($handle)) { $row = fgetcsv ( $handle ,0,";"); foreach($row as $k => $v) $row[$k] = trim($v); $out[] = $row; } fclose($handle); return $out; } function CSVExport($arIn){ $cnt = 0; foreach($arIn as $k=>$v){ if(!$cnt > 0) echo implode(";", array_keys($v))."\n"; echo implode(";", $v)."\n"; $cnt++; } } function getInputFiles($path="."){ global $INPUT_PATH; $filelist = array(); if ($handle = opendir($path)) { while ($entry = readdir($handle)) { if(!is_dir($INPUT_PATH."/".$entry)) $filelist[] = $entry; //else echo "-- $INPUT_PATH/$entry --"; } closedir($handle); } return $filelist; } function getInputDirs($path="."){ global $INPUT_PATH; $dirlist = array(); if ($handle = opendir($path)) { while ($entry = readdir($handle)) { if(is_dir($INPUT_PATH."/".$entry)&& strpos($entry, ".")!==0) $dirlist[] = $entry; //else echo "-- $INPUT_PATH/$entry --"; } closedir($handle); } return $dirlist; } function clearBom($file){ //$str = file_get_contents($file); //$str = utf8_encode($str); //$str = str_replace("\xEF\xBB\xBF",'',$str); //$str = removeBOM($str); /*$str1 = iconv( "windows-1251", 'UTF-8', $str); if(!empty($str1)) $str = $str1 else $str1 = iconv( "ISO-8859-5", 'UTF-8', $str); if(!empty($str1)) $str = $str1 else*/ /*echo mb_detect_encoding($str, array("utf-8","ISO-8859-5", "windows-1251"), TRUE)." >".valid_utf8($str)." <"; if( mb_detect_encoding($str) != "UTF-8") $str = iconv( "windows-1251", 'UTF-8', $str); else { //$str = removeBOM($str); //$str = iconv('UTF-8', 'windows-1251', $str); //$str = iconv('windows-1251', 'UTF-8', $str); }*/ //file_put_contents($file, $str); } function loadInputFile($inputname, $directory="input"){ global $_FILES; $target_dir = $directory."/"; $target_file = $target_dir . date("Y_m_d_"). strtolower(basename($_FILES[$inputname]["name"])); $uploadOk = 1; $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); //echol($target_file); // Check if file already exists if (file_exists($target_file)) { $out.= "Sorry, file already exists.\n"; $uploadOk = 0; } /*// Check file size if ($_FILES["fileToUpload"]["size"] > 500000) { echo "Sorry, your file is too large."; $uploadOk = 0; }*/ // Allow certain file formats if($imageFileType != "csv" ) { $out.= "Sorry, only CSV files are allowed.\n"; $uploadOk = 0; } // Check if $uploadOk is set to 0 by an error if ($uploadOk == 0) { $out.= "Sorry, your file was not uploaded.\n"; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES[$inputname]["tmp_name"], $target_file)) { //clearBom($target_file); $out.= "The file ". basename( $_FILES[$inputname]["name"]). " has been uploaded.\n"; } else { $out.= "Sorry, there was an error uploading your file.\n"; } } return $out; } function unsetAr($arr,$fld){ foreach($arr as $k => $item){ unset($item[$fld]); $out[$k] = $item; } return $out; } function groupAr($arr, $fld){ foreach($arr as $k=>$Item){ $key = $Item[$fld]; unset($Item[$fld]); if(!empty($key)) $out[$key][] = $Item; } return $out; } // Удаляет промежуточный слой ключей в подчиненном массие, переподчиняет с пустыми ключами function shiftLayer($arr){ foreach($arr as $k=>$val){ foreach($val as $v) if(is_array($v)&&count($v)==1) $out[$k][] = array_pop($v); } return $out; } function getColValues($arIn, $key){ foreach($arIn as $item){ if(!empty($item[$key])) $out[$item[$key]]+=1; } return array_keys($out); } function strToMerge($str){ $nk = strtoupper($str); $nk = str_replace( array(" ",",",".","/","+","-","#","_"), "", $nk); //$nk = str_replace( array("__","___"), "_", $nk ); return $nk; } // чистит ключ в массиве на пробелы и регистр - приводит к верхнему регистру function cleanKey($arr){ if(is_array($arr)) { foreach($arr as $k => $v){ $nk = strToMerge($k); $out[$nk] = $v; } } else $out = strToMerge($arr); return $out; } // УДАЛЯЕТ ПОДСТРОКУ - очистка данных function cleanStr($str, $sub){ return str_replace($sub, "", $str); } function cleanTilda($arIn){ foreach ($arIn as $k => $v) { foreach ($v as $code => $val) { if($code{0}=="~") unset( $arIn[$k][$code]); } } return $arIn; } function correctPicPath($in){ global $picPath; global $outPicStr; if(is_array($in)){ foreach($in as $k => $pic){ $out[$k] = $picPath.cleanStr($pic, $outPicStr); } }else{ $out = $picPath.cleanStr($in, $outPicStr); } return $out; } function addSelfMorePicList($arr){ global $fieldConfig; global $MORE_PIC_FIELD; foreach($arr as $k=>$el){ if(!empty($el[$MORE_PIC_FIELD])){ foreach($el[$MORE_PIC_FIELD] as $key => $pic) if(!empty($pic)){ $el[$MORE_PIC_FIELD][$key] = correctPicPath($pic); if (empty($el[$MORE_PIC_FIELD][$key])) unset ($el[$MORE_PIC_FIELD][$key]); } else unset($el[$MORE_PIC_FIELD][$key]); } $out[$k] = $el; } return $out; } function addMorePicList($arr,$pic,$fld){ global $fieldConfig; global $MORE_PIC_FIELD; foreach($arr as $k=>$el){ if(is_array($pic[ $el[$fld] ])) { $fl = $el[$fld]; unset($el[$fld]); $el[$MORE_PIC_FIELD] = correctPicPath($pic[ $fl ]); $fieldConfig[$MORE_PIC_FIELD] = "PIC"; } $out[$k] = $el; } return $out; } function cropImage($img, $picPath = "/tmp/croppics/"){ $filename = $_SERVER["DOCUMENT_ROOT"].CFile::getPath($img); if (!file_exists($filename)) { return "nofile"; } $new_name = $_SERVER["DOCUMENT_ROOT"].$picPath.strtolower( pathinfo( $filename, PATHINFO_FILENAME )).".jpg"; $out = $picPath.strtolower( pathinfo( $filename, PATHINFO_FILENAME )).".jpg"; $img = GetImage($filename); //var_dump($img); //imagejpeg($img, $new_name, 100); $cropped = imagecropauto($img, IMG_CROP_THRESHOLD, 0.5, 16777215); //var_dump($cropped); if ($cropped !== false) { // in case a new image resource was returned imagejpeg($cropped, $new_name, 100); // we destroy the original image // $img = $cropped; // and assign the cropped image to $im } else return "false"; imagedestroy($img); imagedestroy($cropped); $out = '<img src="'.$out.'" height="100" alt="" />'; //$out = $new_name; return $out; } function newcropImage($img, $picPath = "/tmp/croppics/"){ $filename = $img; $offset = 10; if (!file_exists($filename)) { return "nofile"; } $new_name = $_SERVER["DOCUMENT_ROOT"].$picPath.strtolower( pathinfo( $filename, PATHINFO_FILENAME )).".jpg"; $out = $picPath.strtolower( pathinfo( $filename, PATHINFO_FILENAME )).".jpg"; if(file_exists($new_name)) return $out; $img = GetImage($filename); //var_dump($img); //imagejpeg($img, $new_name, 100); $cropped = imagecropauto($img, IMG_CROP_THRESHOLD, 0.5, 16777215); //var_dump($cropped); if ($cropped !== false) { // in case a new image resource was returned //достроить до квадрата $sx = imagesx($cropped); $sy = imagesy($cropped); //лавная сторона для достраивания $ms = (($sx>$sy)? $sx:$sy)+2*$offset; $borderedRect = imagecreatetruecolor($ms, $ms); $white = imagecolorallocate($borderedRect, 255, 255, 255); imagefill($borderedRect, 0, 0, $white); $nsx = intdiv($ms, 2)-intdiv($sx, 2); $nsy = intdiv($ms, 2)-intdiv($sy, 2); imagecopy ( $borderedRect , $cropped , $nsx , $nsy , 0 , 0 , $sx , $sy ); imagejpeg($borderedRect, $new_name, 90); } else return "false"; imagedestroy($img); imagedestroy($cropped); imagedestroy($borderedRect); //$out = '<img src="'.$out.'" style="max-width:620px;max-height:620px;" alt="" />'; //$out = $new_name; return $out; } function GetImage( $pointer ) { $image_data = file_get_contents($pointer); $img = imagecreatefromstring($image_data); if($img != false) return $img; else return false; /* switch ( strtolower( pathinfo( $pointer, PATHINFO_EXTENSION ))) { case 'jpeg': case 'jpg': try{ echo $pointer; if($out = imagecreatefromjpeg($pointer)) return $out; //Очевидно, 1 никогда не будет равняться 2... if(empty($out)){ //Генерируем исключение. throw new Exception("Ошибка! файл $pointer"); } } //Перехватываем (catch) исключение, если что-то идет не так. catch (Exception $ex) { //Выводим сообщение об исключении. return false;// $ex->getMessage(); } break; case 'png': return imagecreatefrompng($pointer); break; case 'gif': return imagecreatefromgif($pointer); break; default: return ('File "'.$pointer.'" is not valid jpg, png or gif image.'); break; }*/ } function correctSTPics($arr){ foreach($arr as $k => $el){ if( !empty($el["DETAIL_PICTURE"]) ) $el["DETAIL_PICTURE"] = correctPicPath($el["DETAIL_PICTURE"]); if( !empty($el["PREVIEW_PICTURE"]) ) $el["PREVIEW_PICTURE"] = correctPicPath($el["PREVIEW_PICTURE"]); $out[$k] = $el; } return $out; } function managePictures($arIn){ global $MAKE_PIC_UPDATE; global $fieldConfig; foreach($fieldConfig as $key => $type){ if( strtoupper($type) == "PIC" || strtoupper($type)=="PHOTO") $picfield[]=$key; elseif( $key=="DETAIL_PICTURE" ) $picfield[]=$key; elseif( $key=="PREVIEW_PICTURE" ) $picfield[]=$key; } //echol($picfield); foreach($arIn as $k => $el){ foreach($picfield as $key){ if($MAKE_PIC_UPDATE == true && (!empty($el[$key]))){ if(is_array($el[$key])){ foreach($el[$key] as $kpic => $pic){ $el[$key][$kpic] = CFile::MakeFileArray($pic); } }else{ $el[$key] = CFile::MakeFileArray($el[$key]); } }else unset($el[$key]); } $out[$k]=$el; } //echol($picfield); return $out; } function findLinkByName($arr, $brfld, $ibl, $new_code){ global $LINESIBLOCK; $el_match = allElements($ibl, array("ID","NAME"), "NAME"); $el_match = cleanKey($el_match); //echol($el_match); foreach($arr as $k => $el){ $to_find = cleanKey($el[$brfld]); if(!empty($to_find) && !empty($el_match[ $to_find ])){ $el[ $new_code ] = $el_match[ $to_find ]["ID"]; }elseif($ibl == $LINESIBLOCK){ /*loadNewSeria($to_find);*/ } # ============!!!!!!!!!!!!! ДОПИСАТЬ СОЗДАНИ ПУСТЫХ СЕКЦИЙ (РАЗДЕЛОВ) !!!!!!!!!!!============= $out[$k] = $el; } return $out; } function mergeFields1String($fields, $use_key=""){ $names = array_shift($fields); foreach( $fields as $it ){ $mkey = ""; foreach( $names as $k => $n){ if($n==$use_key) $mkey=$it[ $k ]; $out[ $n ] = $it[ $k ]; } if(empty($use_key)) $arOut[]=$out; else $arOut[$mkey]=$out; } return $arOut; } function addPicturePath($arIn){ foreach($arIn as $k => $el){ if(!empty($el["DETAIL_PICTURE"])) $el["DETAIL_PICTURE_PATH"]= CFile::GetPath($el["DETAIL_PICTURE"]); if(!empty($el["PREVIEW_PICTURE"])) $el["PREVIEW_PICTURE_PATH"]= CFile::GetPath($el["PREVIEW_PICTURE"]); $out[$k] = $el; } return $out; } function getSections($id) { $out_res = CIBlockElement::GetElementGroups($id, true); while($gr = $out_res->Fetch()){ $out[] = $gr; } return $out; } function addSectionsList($arIn, $separator =" - ") { foreach($arIn as $id => $el){ $sects = getSections($id); $sect = array(); if(!empty($sects)){ foreach($sects as $k => $v) $sect[]=$v["NAME"]."(".$v["ID"].")"; $el["SECTIONS"] = implode($separator, $sect); } $out[$id] = $el; } return $out; } function allSectionElements($IBL, $section, $Fields = false, $mainField = "ID", $page = false, $filter=array()){ if(is_array($Fields)) $arSelect = $Fields; else $arSelect = false; $arFilter = array("IBLOCK_ID" => $IBL, "SECTION_ID" => $section); if(!empty($filter)) $arFilter=array_merge($arFilter,$filter); if($page != false) $pager = array("nPageSize"=>$page); else $pager = false; $res = CIBlockElement::GetList(Array(), $arFilter, false, $pager, $arSelect); while($row = $res->GetNext()) { $out[$row[$mainField]]=$row; } return $out; } function filteredSectionElements($sectionid, $filters=array(), $select=array(), $page = false){ global $IBLOCK; if(is_array($select)) $arSelect = $select; else $arSelect = false; $arFilter = array("IBLOCK_ID" => $IBLOCK); if($sectionid != false) $arFilter["SECTION_ID"] = $sectionid; if(!empty($filters) && !isset($filters["PROPERTY_all"])) $arFilter=array_merge($arFilter,$filters); //echol( $arFilter ); if($page != false) $pager = array("nPageSize"=>$page); else $pager = false; $res = CIBlockElement::GetList(Array(), $arFilter, false, $pager, $arSelect); while($row = $res->GetNext()) { $out[]=$row; } return $out; } function allElements($IBL, $Fields = false, $mainField = "ID", $page = false){ if(is_array($Fields)) $arSelect = $Fields; else $arSelect = false; $arFilter = array("IBLOCK_ID" => $IBL); if($page != false) $pager = array("nPageSize"=>$page); else $pager = false; $res = CIBlockElement::GetList(Array(), $arFilter, false, $pager, $arSelect); while($row = $res->GetNext()) { $out[$row[$mainField]]=$row; } return $out; } function loadBoldLines($arIn, $IBL){ global $el; global $GLOBALTEST; global $SILENTPROPS; $sect_match = allElements($IBL, array("ID","NAME","CODE"), "CODE"); //echol($sect_match); $ces = array("ACTIVE","NAME","CODE"); $arLoad = Array( "IBLOCK_ID" => $IBL ); foreach($arIn as $k => $Item){ foreach($Item as $key => $val){ if(in_array($key,$ces)){ $arLoad[$key] = $val; if($key=="NAME" && (empty($Item["CODE"]))){ $arTrans = array( "replace_space"=>"_", "replace_other"=>"_", "delete_repeat_space"=>true, "change_case"=>"L" ); $code = Cutil::translit($val,"ru",$arTrans); $arLoad["CODE"] = $code; } } else { $arLoad["PROPERTY_VALUES"][$key] = $val; } } if(!empty($arLoad["NAME"])){ if(is_array($sect_match[$arLoad["CODE"]])) { $ELID = $sect_match[$arLoad["CODE"]]["ID"]; echo "\nto update $ELID"; if($SILENTPROPS != true) { echo " with \n "; echol($arLoad); } if($GLOBALTEST != true){ $el->Update($ELID,$arLoad); } } elseif($GLOBALTEST == true){ echo "\nTo add element"; if($SILENTPROPS != true) { echo " with \n "; echol($arLoad); } } else { if( $ELID = $el->Add($arLoad) ){ echo "\nAdded $ELID"; if($SILENTPROPS != true) { echo " with \n "; echol($arLoad); } } else echo "Error: ".$el->LAST_ERROR; } } } } // простой загрузчик цен массой из списка function loadPrices($arIn, $sections = false){ global $IBLOCK; global $SILENTPROPS; $el_match = findMatches($arIn); //echol($arIn); //$fromsection = allSectionElements($IBLOCK, $sections, array("ID","NAME","ACTIVE","PROPERTY_ARTIKUL")); foreach ( $arIn as $k => $el){ if(!empty($el_match[$k]["ID"])) { $toUpdate[ $el_match[$k]["ID"] ] = $el_match[$k]; unset($arIn[$k]); //unset($fromsection[ $el_match[$k]["ID"] ]); } } /* для поиска необновленных цен из разделов - скармливается или айдишник раздела, или массив айдишников echo count($fromsection)." <-- \n\n"; foreach($fromsection as $k => $v){ echo $k." - ".$v["ACTIVE"]." = ".$v["PROPERTY_ARTIKUL_VALUE"]."\n"; } echol($fromsection); echol( "found -> ".count($toUpdate)."\n\n" ); */ //if($SILENTPROPS==false) echol($toUpdate); foreach($toUpdate as $id => $el){ if(empty($el["commerce"]["AVAILABLE"])) $available = false; else $available = $el["commerce"]["AVAILABLE"]; if(empty($el["commerce"]["ZAKUPKA"])) $zakupka = false; else $zakupka = $el["commerce"]["ZAKUPKA"]; updatePrice($id,$el["commerce"]["PRICE"],$available,$zakupka); if($SILENTPROPS==false) echol("$id => ".$el["commerce"]["PRICE"]." -> $available po $zakupka \n"); } //echol($toUpdate); return $out; } function splitKeys($arr){ global $KEY_FIELDS; $keys = $KEY_FIELDS; foreach ($arr as $el){ foreach($keys as $id => $k){ if (!in_array(strtoupper($k), array("ID","NAME","CODE","XML_ID"))) $key = "PROPERTY_".$k."_VALUE"; else $key = $k; if(!empty($el[$key])&&$key!="ID") $out[$k][ cleanKey($el[$key]) ] = $el["ID"]; } } return $out; } function findMatches($arIn){ global $IBLOCK; $elems = allElements($IBLOCK, array("ID", "NAME", /*"PROPERTY_ARTIKUL", "PROPERTY_PRODUCTION_CODE",*/"XML_ID"), "ID"); # !!!!!!!!!!!!!!!!!!!!!!! СЕДЛАТЬ ЧТБОЫ ПАРЕМТРЫ ДЛЯ ФУНКЦИИ выше брались из клобальной переменной настроек !!!!!!!!!!!!!!!! $elems = splitKeys($elems); foreach($arIn as $k => $el){ if(!empty($el["ID"])) $out[$k] = $el; elseif(!empty($el["XML_ID"]) && !empty($elems["XML_ID"][ cleanKey($el["XML_ID"]) ]) ) { $el["ID"] = $elems["XML_ID"][ cleanKey($el["XML_ID"]) ]; $out[$k] = $el; } elseif( !empty($el["ARTIKUL"]) && !empty($elems["ARTIKUL"][ cleanKey($el["ARTIKUL"]) ]) ) { $el["ID"] = $elems["ARTIKUL"][ cleanKey($el["ARTIKUL"]) ]; //if(empty($elems["ARTIKUL"][ $el["ARTIKUL"] ])) echol($el); $out[$k]=$el; } elseif( !empty($el["PRODUCTION_CODE"]) && !empty($elems["PRODUCTION_CODE"][ $el["PRODUCTION_CODE"] ] ) ) { $el["ID"] = $elems["PRODUCTION_CODE"][ $el["PRODUCTION_CODE"] ]; $out[$k]=$el; } } //echol( count($out)." -> ".count($arIn)."\n\n" ); return $out; } function loadDataWithMatchSearch($arIn){ global $IBLOCK; $el_match = findMatches($arIn); foreach ( $arIn as $k => $el){ if(!empty($el_match[$k]["ID"])) { $toUpdate[ $el_match[$k]["ID"] ] = $el_match[$k]; unset($arIn[$k]); }elseif(empty($el["NAME"]) && empty($el["CODE"]) && empty($el["ARTIKUL"]) && empty($el["RODUCTION_CODE"])) unset($arIn[$k]); } $toAdd = $arIn; echol( count($toAdd)." -> ".count($toUpdate)." = "."\n\n" ); $arLoad = prepare_to_load($toUpdate); MakeLoad($arLoad); //echol($toAdd); $arLoad = prepare_to_load($toAdd); MakeLoad($arLoad); return $out; } function prepare_to_load($arIn){ global $fieldConfig; foreach ($fieldConfig as $code => $type) { if($type == "S" || $type == "L" || $type == "PIC") { $props[] = $code; if($code == "BRAND_NAME") { $props[]="BRAND"; $fieldConfig["BRAND"] = "EL"; } if($code == "SERIA_NAME"){ $props[]="SERIA"; $fieldConfig["SERIA"] = "EL"; } } } foreach($arIn as $k => $el){ foreach($props as $code){ $arLoad["PROPERTY_VALUES"][$code] = $el[$code]; unset($el[$code]); if(empty($arLoad["PROPERTY_VALUES"][$code])) unset($arLoad["PROPERTY_VALUES"][$code]); } foreach($el as $code => $val){ $arLoad[$code] = $val; } $out[$k]=$arLoad; } return $out; } function MakeLoad($arIn){ global $el; global $GLOBALTEST; global $SILENTPROPS; global $IBLOCK; global $CHANGE_CODE_ON_UPDATE; foreach($arIn as $k => $arLoad){ $arLoad["IBLOCK_ID"] = $IBLOCK; // проверка на заполненность символьного кода у товаров на добавление if(empty($arLoad["ID"]) && empty($arLoad["CODE"]) && !empty( $arLoad["NAME"] )) { $arTrans = array( "replace_space"=>"_", "replace_other"=>"_", "delete_repeat_space"=>true, "change_case"=>"L" ); $code = Cutil::translit($arLoad["NAME"],"ru",$arTrans); $arLoad["CODE"] = $code; }elseif(!empty( $arLoad["ID"] ) && !empty($arLoad["CODE"]) && $CHANGE_CODE_ON_UPDATE!=true ) { unset( $arLoad["CODE"] ); } if(!empty($arLoad["DETAIL_TEXT"])) $arLoad["DETAIL_TEXT_TYPE"] = "html"; $commerce_el = $arLoad["commerce"]; unset($arLoad["commerce"]); //$res = UpdateProduct($ELID, $arLoad, true); if(!empty($arLoad["NAME"])){ if(!empty($arLoad["ID"])) { $ELID = $arLoad["ID"]; unset($arLoad["ID"]); echo "\nto update $ELID"; if($SILENTPROPS != true) { echo " with \n "; echol($arLoad); } if($GLOBALTEST != true){ $res = UpdateProduct($ELID, $arLoad, true); } } elseif($GLOBALTEST == true){ echo "\nTo add element"; if($SILENTPROPS != true) { echo " with \n "; echol($arLoad); } } else { if( $ELID = $el->Add($arLoad, false, true, true) ){ echo "\nAdded $ELID"; if($SILENTPROPS != true) { echo " with \n "; echol($arLoad); } //добавить коммерческие характеристики $arFields = array( "ID" => $ELID, "CAN_BUY_ZERO" => "Y", "QUANTITY_TRACE" => "N", "CAN_BUY_ZERO" => "Y", "NEGATIVE_AMOUNT_TRACE" => "N" ); CCatalogProduct::Add($arFields); } else echo "Error: ".$el->LAST_ERROR; } } // echol($commerce_el); // обновление коммерс-характеристик if(!empty($commerce_el) && !empty($ELID)){ // поиск закупочной цены if( empty($commerce_el["ZAKUPKA"]) ) $zakupka = false; else $zakupka = $commerce_el["ZAKUPKA"]; updatePrice($ELID, $commerce_el["PRICE"] , $commerce_el["AVAILABLE"] , $zakupka); } } //CIBlockSection::ReSort($IBLOCK); } //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! function UpdateProduct($id, $item, $resize = false){ global $fieldConfig; global $el; global $MORE_PIC_FIELD; global $SILENTPROPS; global $GLOBALTEST; if(empty($id) || empty($item)) return "empty"; //echo "here"; //стандартные свойства $commerce = $item["commerce"]; unset ($item["commerce"]); $props = $item["PROPERTY_VALUES"]; unset ($item["PROPERTY_VALUES"]); unset($item["ID"]); // обновление самого элемента if(!empty($item)) $res = $el->Update($id, $item, false, true, true); elseif($SILENTPROPS !=true ) echo "generalSkip\n"; //echol($commerce); // обновление комменции if(!empty($commerce)){ if(empty($commerce["AVAILABLE"])) $available = false; else $available = $commerce["AVAILABLE"]; if(empty($commerce["ZAKUPKA"])) $zakupka = false; else $zakupka = $commerce["ZAKUPKA"]; updatePrice($id,$commerce["PRICE"],$available,$zakupka); } // обновление картинок if(!empty($props[$MORE_PIC_FIELD])){ CIBlockElement::SetPropertyValuesEx($id, $IBLOCK, array($MORE_PIC_FIELD => Array ("VALUE" => array("del" => "Y")))); CIBlockElement::SetPropertyValueCode($id, $MORE_PIC_FIELD, $props[$MORE_PIC_FIELD]); unset($props[$MORE_PIC_FIELD]); } if(!empty($props)) foreach($props as $key => $v){ if($GLOBALTEST !=true ) CIBlockElement::SetPropertyValueCode($id, $key, $v); if($SILENTPROPS !=true ) echo "done $id -> $key \n"; } //echol($props); // обновление доп характеристик // перезаливка картинок // echol($fieldConfig); // echol($id); // echol($item); return "ok"; } function updatePrice($id,$price = false ,$available = "N",$zakupka=false){ if($id <= 0) return false; global $quantity_no; global $quantity_available; global $canbuyzero; global $measure; global $base_price; $catFields = array( "QUANTITY" => (($available == "N" || $available=="нет")? $quantity_no:$quantity_available), "CAN_BUY_ZERO" => $canbuyzero, "MEASURE" => $measure, ); if(strlen($available)==3 || $available!="Y") $catFields["QUANTITY"] = $quantity_no; else $catFields["QUANTITY"] = $quantity_available; //echo $available."\n"; if($zakupka > 0){ $catFields["PURCHASING_PRICE"] = $zakupka; $catFields["PURCHASING_CURRENCY"] = "RUB"; } //echol($catFields); CCatalogProduct::Update($id, $catFields); if($price != false){ $boolResult = CPrice::DeleteByProduct($id); $arFields = Array( "PRODUCT_ID" => $id, "CATALOG_GROUP_ID" => $base_price, "PRICE" => $price, "CURRENCY" => "RUB", ); //echol($arFields); CPrice::Add($arFields); //echo "\nprice Updated"; } return true; } function SetOverCategory($arIn){ global $fieldConfig; global $CAT_CONFIG; //echol($fieldConfig); foreach($fieldConfig as $code => $type){ if(strtoupper($type)=="CAT") { $category = $code; break; } } if(empty($category)) return $arIn; foreach($arIn as $k=>$el){ if(!empty($el[ $category ])) { $el["IBLOCK_SECTION_ID"] = $CAT_CONFIG[ trim($el[ $category ]) ]; unset($el[ $category ]); } $out[$k] = $el; } return $out; //foreach(); } function manageCommerce($arIn){ global $fieldConfig; global $MAKE_COMMERCE_UPDATE; foreach($fieldConfig as $key => $type){ if($type=="PR"){ $comFields[]=$key; } } //echol($comFields); foreach($arIn as $k => $el){ foreach($comFields as $key){ if(!empty($el[$key]) && $MAKE_COMMERCE_UPDATE == true ) if(strtoupper($type)=="PRICE" || strtoupper($type)=="ZAKUPKA" ) $el["commerce"][$key] = clearPrice($el[$key]); else $el["commerce"][$key] = $el[$key]; unset($el[$key]); } $out[$k] = $el; } return $out; } function clearPrice($pr = "р."){ $out = trim(str_replace(array(" ",",00р.","р.","-"),"",$pr)); return $out; } function addCommonFields($arIn) { # code... global $addCommonFields; foreach($arIn as $k => $v){ $out[$k] = array_merge($addCommonFields, $v); } return $out; } function UpdateIblockStringListProperties($arIn){ global $fieldConfig; global $fieldNameConfig; global $IBLOCK; global $ibp; // по конфигу разобрать свойства - отобрать списки и строки foreach($fieldConfig as $code => $type){ if($type=="S") $strFields[$code]=1; if($type=="L") $listFields[$code]=1; } // собираем занчения для входящих элементов foreach($arIn as $k => $el){ foreach ($strFields as $code => $is) if(!empty($el[$code])) $toUp["string"][$code] +=1; foreach ($listFields as $code => $is) if(!empty($el[$code])) $toUp["list"][$code][$el[$code]] +=1; // !!!!!!!!!!!! дописать множественные характеристики здесь } //echol($toUp); // Для строк провести проверку и добавить если ее не существует по коду foreach($toUp["string"] as $code => $count){ checkStringProperty($code); } // Для Списков // собрать значения из эементов источника // Получаем сохраненные значения из инфоблока foreach($toUp["list"] as $code => $val ){ $res = CIBlockProperty::GetByID($code, $IBLOCK); if($ar_res = $res->GetNext()){ // свойство найдено $embtmp = GetIBEnumList($code); foreach($embtmp["VALUES"] as $embel){ $toUp["mergeList"][$code][$embel["VALUE"]] = $embel["ID"] ; $toUp["merged"][$code][$embel["ID"]] = array( "VALUE" => $embel["VALUE"], "DEF" => $embel["DEF"], "SORT" => $embel["SORT"] ); } $properties[ $code ] = $ar_res["ID"]; }else{ // свойство не найдено $properties[ $code ] = "new"; } } //echol($properties); // смерджить массивы //$toUp["merged"] = $toUp["mergeList"]; foreach( $toUp["list"] as $code => $vals ){ foreach ($vals as $val => $counter){ $valb = cleanKey($val); $found = false; foreach($toUp["mergeList"][$code] as $v => $id){ if( cleanKey($v) == $valb ) $found=true; } if(!$found){ $toUp["merged"][$code][]=array( "VALUE" => $val, "DEF" => "N", "SORT" => $counter*100 ); } } } //echol ($toUp); // произвести добавление или обновление хараткеристики в инфоблоке foreach($properties as $code => $id){ if($id !="new"){ // Обновляем существующее свойство $arUp = $toUp["merged"][$code]; //echol($arUp); $res = $ibp->UpdateEnum($id, $arUp); }else{ if(!empty($fieldNameConfig[$code])) $title = $fieldNameConfig[$code]; else $title = $code; // Добавляем новое свойство $arFields = Array( "NAME" => $title, "ACTIVE" => "Y", "SORT" => "100", "CODE" => $code, "PROPERTY_TYPE" => "L", "IBLOCK_ID" => $IBLOCK, "VALUES" => $toUp["merged"][$code] ); //echol($arFields); $PropID = $ibp->Add($arFields); } } // готовим к выводу и переворачиваем новые значения списков для связки со значениями элементов foreach($properties as $code => $id){ $embtmp = GetIBEnumList( $code ); $readyembed[$code] = turnToLinks($embtmp); } //echol($readyembed); /*приведение к ключам*/ foreach($readyembed as $k => $v) { foreach($v as $in => $id) { //echo $in." -- ".trim(strtolower($in))."\n"; $readyembed[$k][ trim(strtolower($in)) ] = $id; if(md5($in) != md5(trim(strtolower($in)))) unset($readyembed[$k][$in]); } } //echol($readyembed); // запись новых значений списков в элементы foreach($arIn as $k => $el){ foreach($readyembed as $key => $vals){ $el[$key] = $vals[ trim(strtolower($el[$key])) ]; } $out[$k] = $el; } //echol($out); return $out; } // переворачивает массив значений ембед-массива после функции getIBEnumList для поиска у элементов function turnToLinks($arIn){ //echol($arIn); foreach($arIn["VALUES"] as $el){ $out[ $el["VALUE"] ] = $el["ID"]; } return $out; } function checkStringProperty($code, $name=false, $sort=100){ global $IBLOCK; global $ibp; global $fieldNameConfig; $res = CIBlockProperty::GetByID($code, $IBLOCK); if($ar_res = $res->GetNext()){ echo "got $code \n"; return true; }elseif(!empty($code)){ if($name==false){ if(!empty($fieldNameConfig[$code])) $name = $fieldNameConfig[$code]; } $arFields = Array( "NAME" => (($name==false)? $code:$name), "ACTIVE" => "Y", "SORT" => $sort, "CODE" => $code, "PROPERTY_TYPE" => "S", "IBLOCK_ID" => $IBLOCK ); $PropID = $ibp->Add($arFields); echo "create $code \n"; return true; } } /* // возвращает значения характеристики типа список по коду свойства "COUNT" = количество, "VALUES" = значения */ function GetIBEnumList($arProp){ global $IBLOCK; $property_enums = CIBlockPropertyEnum::GetList(Array("DEF"=>"DESC", "SORT"=>"ASC"), Array("IBLOCK_ID"=>$IBLOCK, "CODE"=>$arProp)); while($enum_fields = $property_enums->GetNext()) { $out["VALUES"][] = $enum_fields; //print_r($enum_fields); } $out["COUNT"] = count($out["VALUES"]); return $out; } function GetElementSections($elem, $arSelect=array("ID","NAME")){ $db_old_groups = CIBlockElement::GetElementGroups($elem, true, $arSelect); while($ar_group = $db_old_groups->Fetch()){ $out[$ar_group["ID"]]=$ar_group; } return $out; } function TransformEmbed($arIn){ foreach($arIn as $code => $arPr){ if(is_array($arPr)) foreach($arPr["VALUES"] as $Item) $arOut[ $code ][ $Item["VALUE"] ] = $Item["ID"]; } return $arOut; } function formEmbed($arIn){ if(is_array($arIn)) foreach($arIn["VALUES"] as $Item) $arOut[ $Item["VALUE"] ] = $Item["VALUE"]; return $arOut; } //-------------------------------------------------------------------------------- function getSectionList($IBL, $parent = false, $cntEl = "Y", $arSelect = array("ID","NAME","SECTION_ID")){ $arSelect = Array("UF_*"); //пользовательское поле UF_PAGE_LINK $bIncCnt = array( "ELEMENT_SUBSECTIONS" => ($cntEl=="N"?"N":"Y") ); $arFilter = Array("IBLOCK_ID" => $IBL); if($parent!=false && $parent!="all") $arFilter["SECTION_ID"] = $parent; elseif($parent!="all") $arFilter["DEPTH_LEVEL"] = 1; $res = CIBlockSection::GetList(Array("SORT"=>"ASC"), $arFilter, $bIncCnt, $arSelect); while($arRes = $res->GetNext()){ $out[]=$arRes; } return $out; } function makeLevels($arParents){ foreach($arParents as $sec){ if(empty($sec["IBLOCK_SECTION_ID"])) $arLev["root"][]=$sec["ID"]; else $arLev[$sec["IBLOCK_SECTION_ID"]][] = $sec["ID"]; } $arIn = [ "DATA" => $arLev, "LEVELS" => [ 1 => $arLev["root"]] ]; $depth=0; do{ $depth++; $children = $arIn["LEVELS"][$depth]; foreach($children as $child){ if(!empty($arIn["DATA"][$child])) foreach($arIn["DATA"][$child] as $ch2) $arIn["LEVELS"][$depth+1][]=$ch2; } }while(!empty($arIn["LEVELS"][$depth])); return $arIn["LEVELS"]; } function allSections($IBL, $cntEl = "Y", $arSelect = array("ID","NAME","SECTION_ID")){ $arSelect = Array("UF_*"); //пользовательское поле UF_PAGE_LINK $bIncCnt = array( "ELEMENT_SUBSECTIONS" => ($cntEl=="N"?"N":"Y") ); $arFilter = Array("IBLOCK_ID" => $IBL); $res = CIBlockSection::GetList(Array("SORT"=>"ASC"), $arFilter, $bIncCnt, $arSelect); while($arRes = $res->GetNext()){ $out[]=$arRes; } return $out; } function getParentsForSection($secid, $IBL=false){ if($IBL!=false) $IBLOCK = $IBL; else { global $IBLOCK; $IBL = $IBLOCK; } $res = CIBlockSection::GetNavChain($IBL, $secid); while($row = $res->GetNext()){ //print_r($row); //if($secid != $row["ID"]){ $out[$row["ID"]]=getSectionInfo($row["ID"]); //} } return $out; } function getSectionChildren($section){ global $IBLOCK; $arFilter = array('IBLOCK_ID' => $IBLOCK); $arSelect = array("UF_*"); $rsSection = CIBlockSection::GetTreeList($arFilter, $arSelect); while($arSection = $rsSection->Fetch()) { if($section != false){ if( $arSection["ID"]==$section || in_array($arSection["IBLOCK_SECTION_ID"], array_keys($arSecs)) ){ $arSecs[$arSection["ID"]]=$arSection; } }else{ $arSecs[$arSection["ID"]]=$arSection; } } return $arSecs; } function getSectionInfo($section) { global $IBLOCK; $select = Array("UF_*"); //пользовательское поле UF_PAGE_LINK $bIncCnt = array( "ELEMENT_SUBSECTIONS" => "Y" ); $arFilter = Array("IBLOCK_ID" => $IBLOCK, "ID" => $section); $res = CIBlockSection::GetList(Array("SORT"=>"ASC"), $arFilter, $bIncCnt, $select); while($arRes = $res->GetNext()){ $out=$arRes; } return $out; } function sectionFiltersParce($sect) { if(empty($sect)) return; //echol($sect); $props = json_decode($sect["UF_ELEMENT_FILTER"], true); return $props; } function updateSections($load, $origin=false, $ibl=false){ global $IBLOCK; global $bs; foreach($origin as $k => $s){ if(!empty($s)) $arIds[$s["XML_ID"]] = $s["ID"]; } foreach($load as $xmlid=>$arSec){ $arSec["XML_ID"] = $xmlid; if(empty($ibl) && empty($arSec["IBLOCK_ID"])) $arSec["IBLOCK_ID"] = $IBLOCK; elseif(!empty($ibl) && empty($arSec["IBLOCK_ID"])) $arSec["IBLOCK_ID"] = $ibl; if(!empty($arIds[$xmlid])) { $id = $arIds[$xmlid]; $res = $bs->Update($id, $arSec, false); echol("updated ".$id); }elseif(!empty($arSec["NAME"])){ $id = $bs->Add($arSec); echol("added ".$id); } $arOut[$xmlid] = $id; } return $arOut; } function updateSection($arIn, $IBL=false){ global $IBLOCK; global $bs; foreach($arIn as $id=>$arSec){ $res = $bs->Update($id, $arSec, false); } } function relinkElements($arIn){ foreach($arIn as $id => $secs){ linkElementToSection($id,$secs,"add"); } } function linkElementToSection($id, $sections = array(), $action="add"){ global $IBLOCK; if(empty($sections)) return false; $db_old_groups = CIBlockElement::GetElementGroups($id, true, array("ID")); /*echol($sections); echo "=== ";*/ if($action=="add") $ar_new_groups = $sections; else $ar_new_groups = array(); while($ar_group = $db_old_groups->Fetch()){ if(!in_array($ar_group["ID"], $sections)) $ar_new_groups[] = $ar_group["ID"]; $arOldGroups[]=$ar_group["ID"]; } $check = ((count($ar_new_groups) != count($arOldGroups))? true:false); /*echol($arOldGroups); echo "--->"; echol($ar_new_groups); echo "\n\n";*/ if($check){ CIBlockElement::SetElementSection($id, $ar_new_groups); \Bitrix\Iblock\PropertyIndex\Manager::updateElementIndex($IBLOCK, $id); //echo "done $id\n"; } return true; } //--------------------------------------------------------------------- // !!!!!!!!!!!!!!!!!!!!!! ex getPropList function getPropsList() { global $IBLOCK; $properties = CIBlockProperty::GetList(Array("sort"=>"asc", "name"=>"asc"), Array("ACTIVE"=>"Y", "IBLOCK_ID"=>$IBLOCK)); while ($prop_fields = $properties->GetNext()) { $out[]=$prop_fields; } return $out; } function setFieldConfig() { global $fieldConfig; global $ELEMENT_FIELDS; global $LIST_VALUES; foreach($ELEMENT_FIELDS as $code => $prop) $fieldConfig[$code] = $prop["TYPE"]; $ibProps = getPropList(); foreach($ibProps as $prop){ $fieldConfig[ $prop["CODE"] ] = $prop["PROPERTY_TYPE"]; if($prop["CODE"] =="MORE_PHOTO") $fieldConfig[ $prop["CODE"] ] = "PIC"; $ELEMENT_FIELDS[ "PROPERTY_".$prop["CODE"] ] = array( "ID" => $prop["ID"], "NAME" => $prop["NAME"], "CODE" => $prop["CODE"], "TYPE" => $prop["PROPERTY_TYPE"], "MULTIPLE" => $prop["MULTI"], "SORT" => $prop["SORT"] ); if($prop["PROPERTY_TYPE"]=="L"){ $lvals = getIBEnumList($prop["CODE"]); foreach($lvals["VALUES"] as $val) $LIST_VALUES[ $prop["ID"]][ $val["ID"] ] = $val["VALUE"]; } } } ?>