Наши преимущества
function agentLoadCatalog() { /* unzip */ $arrMarks = ['Renault', 'Hyundai', 'Kia']; foreach ($arrMarks as $mark) { $archive = $_SERVER["DOCUMENT_ROOT"] . '/uploads/sync/' . $mark . '.zip'; $l = new SimpleLogger(); if (file_exists($archive)) { $l->showMessage('найден аив ' . $archive, 'success'); $extractPath = $_SERVER["DOCUMENT_ROOT"] . "/uploads/sync/"; $arUnpackOptions = [ "REMOVE_PATH" => $_SERVER["DOCUMENT_ROOT"], "UNPACK_REPLACE" => false ]; $resArchiver = CBXArchive::GetArchive($archive); $resArchiver->SetOptions($arUnpackOptions); $uRes = $resArchiver->Unpack($extractPath); if (!$uRes) { echo $resArchiver->GetErrors(); } else { $l->showMessage($archive . ' пено апакован ', 'success'); $filename = $extractPath . $mark . '/' . $mark . '.xml'; if (file_exists($filename)) { $l->showMessage('а паинга ' . $filename); CModule::IncludeModule('iblock'); /* get exist cars */ $arrExist = []; $dbElems = CIBlockElement::GetList( [], ['IBLOCK_ID' => IBLOCK_ID_AUTO], false, false, ['ID', 'XML_ID'] ); while ($one = $dbElems->GetNext()) { $arrExist[$one['XML_ID']] = $one['ID']; } $xmlData = simplexml_load_file($filename, "SimpleXMLElement", LIBXML_NOCDATA); // Сеики дл аиики $processingStats = [ 'total' => 0, 'added' => 0, 'updated' => 0, 'deleted' => 0, 'photos_total' => 0, 'photos_found' => 0, 'photos_missing' => 0, 'photo_errors' => 0, 'errors' => 0 ]; foreach ($xmlData->вомобил as $auto) { $processingStats['total']++; $vin = (string)$auto['VIN']; $l->showMessage("бабока авомобил #{$processingStats['total']}: VIN={$vin}"); // даление if (!empty($arrExist[$vin]) && (string)$auto->одан === 'а') { if(CIBlockElement::Delete($arrExist[$vin])){ $l->showMessage($vin . ' пено дален', 'success'); $processingStats['deleted']++; } else { $l->showMessage($vin . ' оибка далени', 'error'); $processingStats['errors']++; } continue; } $arrPhotos = []; $photoLog = []; // аив дл логов по оогаим $photoCounter = 0; if (!empty($auto->Фоогаии->Фоогаи)) { $l->showMessage("аало обабоки оогаий дл VIN={$vin}"); foreach ($auto->Фоогаии->Фоогаи as $index => $photo) { $photoCounter++; $originalPhotoPath = (string)$photo; $fixPhoto = str_replace('\\', '/', $originalPhotoPath); $fullFilename = $extractPath . $fixPhoto; $processingStats['photos_total']++; if (file_exists($fullFilename)) { // овека азмеа айла $fileSize = filesize($fullFilename); $maxSize = 10 * 1024 * 1024; // 10MB лими if ($fileSize > $maxSize) { $photoLog[] = [ 'status' => 'warning', 'index' => $index, 'original_path' => $originalPhotoPath, 'fixed_path' => $fixPhoto, 'message' => "Файл ликом болой: {$fileSize} бай (лими: {$maxSize})" ]; $processingStats['photo_errors']++; continue; } // овека MIME-ипа $mimeType = mime_content_type($fullFilename); $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp']; if (!in_array($mimeType, $allowedTypes)) { $photoLog[] = [ 'status' => 'warning', 'index' => $index, 'original_path' => $originalPhotoPath, 'fixed_path' => $fixPhoto, 'message' => "едопимй ип айла: {$mimeType}" ]; $processingStats['photo_errors']++; continue; } $tmpArr = CFile::MakeFileArray($fullFilename); if ($tmpArr && !isset($tmpArr['error'])) { $arrPhotos[] = ['VALUE' => $tmpArr]; // обавлем деалн иномаи в лог $photoLog[] = [ 'status' => 'success', 'index' => $index, 'original_path' => $originalPhotoPath, 'fixed_path' => $fixPhoto, 'size' => $fileSize, 'formatted_size' => formatBytes($fileSize), 'mime' => $mimeType, 'dimensions' => getimagesize($fullFilename) ?: 'N/A' ]; $processingStats['photos_found']++; $l->showMessage(" Фоо {$photoCounter}: пено загжено - {$fixPhoto} ({$fileSize} бай)", 'success'); } else { $photoLog[] = [ 'status' => 'error', 'index' => $index, 'original_path' => $originalPhotoPath, 'fixed_path' => $fixPhoto, 'message' => 'ибка оздани айлового маива: ' . ($tmpArr['error'] ?? 'неизвена оибка') ]; $processingStats['photo_errors']++; $l->showMessage(" Фоо {$photoCounter}: оибка - {$fixPhoto}", 'error'); } } else { $photoLog[] = [ 'status' => 'error', 'index' => $index, 'original_path' => $originalPhotoPath, 'fixed_path' => $fixPhoto, 'full_path' => $fullFilename, 'message' => 'Файл не найден' ]; $processingStats['photos_missing']++; $l->showMessage(" Фоо {$photoCounter}: не найдено - {$fixPhoto}", 'error'); } } // Сводка по оогаим $l->showMessage("ог по оогаим дл VIN={$vin}: найдено {$processingStats['photos_found']}/{$photoCounter}, ове {$processingStats['photos_missing']}, оибок: {$processingStats['photo_errors']}"); } else { $l->showMessage("Фоогаии ов дл VIN={$vin}", 'warning'); } // еалнй лог оогаий (олко ели е о логиова) if (!empty($photoLog)) { $photoLogSummary = []; foreach ($photoLog as $logEntry) { $statusIcon = $logEntry['status'] == 'success' ? '' : ($logEntry['status'] == 'warning' ? '' : ''); $photoLogSummary[] = sprintf( "%s [%d] %s - %s", $statusIcon, $logEntry['index'], $logEntry['original_path'], $logEntry['message'] ?? 'OK' ); } if (!empty($photoLogSummary)) { $l->showMessage("еалнй лог оогаий:"); foreach ($photoLogSummary as $logLine) { $l->showMessage(" " . $logLine); } } } $arrStickers = []; $arrStickers[] = (string)$auto->Скидка == "а" ? 'tTCEPtSq' : ''; $arrStickers[] = (string)$auto->Рекомендовано == "а" ? 'dDFV3rEk' : ''; $arrStickers[] = (string)$auto->одаок == "а" ? 'ScIQreAo' : ''; $arrFields = [ 'IBLOCK_ID' => IBLOCK_ID_AUTO, 'ACTIVE' => 'Y', 'XML_ID' => $vin, 'NAME' => (string)$auto->нон, 'PREVIEW_TEXT' => (string)$auto->пианиенон, 'DETAIL_TEXT' => (string)$auto->пиание, 'ACTIVE_FROM' => (string)$auto->ааиода, 'PROPERTY_VALUES' => [ 'BRAND' => (string)$auto->ака, 'MODEL' => (string)$auto->одел, 'YEAR' => (string)$auto->одпка, 'MILEAGE' => (string)$auto->обег, 'CONDITION' => getEnumVal('CONDITION', (string)$auto->Сооние), 'OWNER_COUNT' => (string)$auto->ладелевоТС, 'BODY' => getEnumVal('BODY', (string)$auto->зов), 'TRANSMISSION' => getEnumVal('TRANSMISSION', (string)$auto->Тип), 'DRIVE_TYPE' => getEnumVal('DRIVE_TYPE', (string)$auto->ивод), 'COLOR' => (string)$auto->Цве, 'PRICE' => (string)$auto->Цена, 'OLD_PRICE' => (string)$auto->СааЦена, 'ORIGINAL_PTS' => getEnumVal('ORIGINAL_PTS', (string)$auto->игиналТС), 'STICKERS' => $arrStickers, 'AUTO_TYPE' => getEnumVal('AUTO_TYPE', ((string)$auto->овй == "а" ? 'овй' : 'С побегом')), 'FAVORITE' => getEnumVal('FAVORITE', (string)$auto->збаннй), 'TECH' => (string)$auto->ТениекиеХаакеиики, 'PICTURES' => !empty($arrPhotos) ? $arrPhotos : '', 'CAR_DEALERSHIP' => (string)$auto->Ц, 'DC' => $mark, 'SALE_BLOCKS' => [(string)$auto->анне] ] ]; $elem = new CIBlockElement(); if (!empty($arrExist[$vin])) { // ели апдейим каинки - далим ае if (!empty($arrPhotos)) { $res = CIBlockElement::SetPropertyValuesEx( $arrExist[$vin], IBLOCK_ID_AUTO, [ 'PICTURES' => [ 'VALUE' => ['del' => 'Y'] ] ] ); } $res = $elem->Update($arrExist[$vin], $arrFields); if ($res) { $l->showMessage($vin . ' пено обновлен', 'success'); $processingStats['updated']++; } else { $l->showMessage($vin . ' оибка обновлени = ' . $elem->LAST_ERROR, 'error'); $processingStats['errors']++; } } else { $res = $elem->Add($arrFields); if ($res) { // павка на лай налии одного и ого же аво в вгзке неколко аз $arrExist[$vin] = $res; $l->showMessage($vin . ' пено добавлен', 'success'); $processingStats['added']++; } else { $l->showMessage($vin . ' оибка добавлени = ' . $elem->LAST_ERROR, 'error'); $processingStats['errors']++; } } unset($elem); } // огова аиика $l->showMessage("======= Т РТ ======="); $l->showMessage("его обабоано авомобилей: {$processingStats['total']}"); $l->showMessage("обавлено нов: {$processingStats['added']}"); $l->showMessage("бновлено: {$processingStats['updated']}"); $l->showMessage("Удалено: {$processingStats['deleted']}"); $l->showMessage("ибок: {$processingStats['errors']}"); $l->showMessage("Фоогаии: найдено {$processingStats['photos_found']}, ове {$processingStats['photos_missing']}, оибок {$processingStats['photo_errors']}"); $l->showMessage('паинг завеен', 'success'); } else { $l->showMessage('в аиве не обнажен айл ' . $filename, 'error'); } /* del extracted */ $dir = $extractPath . $mark . '/'; $files = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST ); foreach ($files as $fileinfo) { $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink'); $todo($fileinfo->getRealPath()); } if (rmdir($dir)) { $l->showMessage('диекои ' . $dir . ' оиена и пено далена', 'success'); } else { $l->showMessage('оибка далени диекоии ' . $dir, 'error'); } } if (unlink($archive)) { $l->showMessage('аив ' . $archive . ' пено дален', 'success'); } else { $l->showMessage('оибка далени аива ' . $archive, 'error'); } } else { $l->showMessage('аив ' . $archive . ' не найден'); } CEventLog::Add([ "SEVERITY" => "INFO", "AUDIT_TYPE_ID" => "TYPE_LOAD_CATALOG", "MODULE_ID" => "main", "ITEM_ID" => $mark, "DESCRIPTION" => $l->getTextLog(), ]); } return "agentLoadCatalog();"; } /** * помогаелна нки дл омаиовани азмеа айла */ function formatBytes($bytes, $precision = 2) { $units = ['B', 'KB', 'MB', 'GB', 'TB']; $bytes = max($bytes, 0); $pow = floor(($bytes ? log($bytes) : 0) / log(1024)); $pow = min($pow, count($units) - 1); $bytes /= pow(1024, $pow); return round($bytes, $precision) . ' ' . $units[$pow]; }