Файл: mg-core/controllers/exchange1c.php
Строк: 269
<?php
/**
* Класс Exchange1c - предназначен для обмена данными между "1с - Управление Торговлей" и Moguta.CMS.
* - Импортирует товары и заказы
*
* @author Авдеев Марк <mark-avdeev@mail.ru>
* @package moguta.cms
* @subpackage Libraries
*/
class Controllers_Exchange1c extends BaseController {
public $startTime = null;
public $maxExecTime = null;
public $mode = null;
public $type = null;
public $filename = null;
public $auth = null;
public $unlinkFile = false;
public $tempCounter = 0; // удалить после внедрения процесса создания категорий
public function __construct() {
if (empty($_GET['mode'])) {
MG::redirect('/');
};
MG::disableTemplate();
Storage::$noCache = true;
$this->unlinkFile = true;
$this->startTime = microtime(true);
$this->maxExecTime = min(30, @ini_get("max_execution_time"));
if (empty($this->maxExecTime)) {
$this->maxExecTime = 30;
}
$mode = (string) $_GET['mode'];
$this->mode = $mode;
$this->type = $_GET['type'];
$this->filename = $_GET['filename'];
$this->auth = USER::auth($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']);
$this->$mode();
if ($mode && $this->auth) {
$this->$mode();
}
}
/**
* 1 шаг - авторизация 1с клиента.
*/
public function checkauth() {
echo "successn";
echo session_name()."n";
echo session_id()."n";
exit;
}
/**
* 2 шаг - сообщаем в 1с клиент о поддержке работы с архивами.
*/
public function init() {
$zip = extension_loaded('zip') ? "yes" : "no";
echo "zip=".$zip."n";
echo "file_limit=0n";
exit;
}
/**
* 3 шаг - сохраняем файл выгрузки полученный из 1с.
*/
public function file() {
$filename = $this->filename;
if (isset($filename) && ($filename) > 0) {
$filename = trim(str_replace("\", "/", trim($filename)), "/");
}
if (function_exists("file_get_contents")) {
$data = file_get_contents("php://input");
file_put_contents($filename, $data);
if ($this->extractZip($filename)) {
$_SESSION['lastCountOffer1cImport'] = 0;
$_SESSION['lastCountProduct1cImport'] = 0;
echo "successn";
} else {
echo "failuren";
}
} else {
echo "failuren";
}
exit;
}
/**
* 4 шаг - запуск процесса импорта файла выгрузки.
*/
public function import() {
$this->processImportXml($this->filename);
echo "successn";
echo session_name()."n";
echo session_id()."n";
exit;
}
/**
* 5 шаг - распаковывает архив с данными по выгрузкам заказов и товаров.
*/
public static function extractZip($file) {
if (file_exists($file)) {
$zip = new ZipArchive;
$res = $zip->open($file, ZIPARCHIVE::CREATE);
if ($res === TRUE) {
$sep = DIRECTORY_SEPARATOR;
$dirname = dirname(__FILE__);
$realDocumentRoot = str_replace($sep.'mg-core'.$sep.'controllers', '', $dirname);
$zip->extractTo($realDocumentRoot);
$zip->close();
unlink($file);
return true;
} else {
return false;
}
}
return false;
}
public function processImportXml($filename) {
$importOnlyNew = false;
$sep = DIRECTORY_SEPARATOR;
$dirname = dirname(__FILE__);
$realDocumentRoot = str_replace($sep.'mg-core'.$sep.'controllers', '', $dirname);
$lastPositionProduct = $_SESSION['lastCountProduct1cImport'];
$lastPositionOffer = $_SESSION['lastCountOffer1cImport'];
$xml = $this->getImportXml($filename);
if ($xml && $filename == 'import.xml') {
foreach ($xml->Каталог[0]->attributes() as $key => $val) {
if ($key == 'СодержитТолькоИзменения' && $val == "true") {
$importOnlyNew = true;
}
}
if (empty($lastPositionProduct) && $importOnlyNew == false) {
DB::query('DELETE FROM `'.PREFIX.'product` WHERE 1');
DB::query('DELETE FROM `'.PREFIX.'category` WHERE 1');
}
$category = $this->groupsGreate($xml->Классификатор, $category, 0);
$model = new Models_Product;
$currentPosition = 0;
foreach ($xml->Каталог->Товары[0] as $item) {
$currentPosition++;
if ($currentPosition <= $lastPositionProduct) {
// MG::loger('пропускаем '.((string)$item->Ид[0]));
continue;
}
// Добавляем изображение товара в папку uploads
$imageUrl = array();
if (isset($item->Картинка)) {
foreach ($item->Картинка as $img) {
$path = $item->Картинка;
$image = basename($item->Картинка);
if (!empty($image) && is_file($path)) {
copy($path, $realDocumentRoot.$sep.'uploads'.$sep.$image);
$widthPreview = MG::getSetting('widthPreview') ? MG::getSetting('widthPreview') : 200;
$widthSmallPreview = MG::getSetting('widthSmallPreview') ? MG::getSetting('widthSmallPreview') : 50;
$heightPreview = MG::getSetting('heightPreview') ? MG::getSetting('heightPreview') : 100;
$heightSmallPreview = MG::getSetting('heightSmallPreview') ? MG::getSetting('heightSmallPreview') : 50;
$upload = new Upload(false);
$upload->_reSizeImage('70_'.$image, $realDocumentRoot.$sep.'uploads'.$sep.$image, $widthPreview, $heightPreview);
// миниатюра по размерам из БД (150*100)
$upload->_reSizeImage('30_'.$image, $realDocumentRoot.$sep.'uploads'.$sep.$image, $widthSmallPreview, $heightSmallPreview);
}
$imageUrl[] = $image;
}
}
$imageUrl = implode($imageUrl, "|");
// MG::loger('добавляем '.((string)$item->Ид[0]));
$id = (string) $item->Группы->Ид[0];
$name = (string) $item->Наименование[0];
$description = '';
if (isset($item->Описание)) {
$description = (string) $item->Описание[0];
}
foreach ($item->ЗначенияРеквизитов->ЗначениеРеквизита as $row) {
if($row->Наименование=='Полное наименование'){
$name = $row->Значение;
}
}
$id_1c = (string) $item->Ид[0];
$dataProd = array(
'title' => $name,
'url' => URL::prepareUrl(MG::translitIt($name)),
'code' => '',
'price' => 0,
'description' => $description,
'old_price' => '',
'image_url' => $imageUrl,
'count' => 0,
'cat_id' => $category[$id]['category_id'],
'meta_title' => $name,
'meta_keywords' => $name,
'meta_desc' => MG::textMore($description, 157),
'recommend' => 0,
'activity' => 1,
'new' => 0,
'related' => '',
'inside_cat' => '',
'1c_id' => $id_1c,
'weight' => '0',
);
$res = DB::query('SELECT * FROM '.PREFIX.'product WHERE `1c_id`='.DB::quote($id_1c));
if ($row = DB::fetchAssoc($res)) {
DB::query('
UPDATE `'.PREFIX.'product`
SET '.DB::buildPartQuery($dataProd).'
WHERE `1c_id`='.DB::quote($id_1c)
);
} else {
$model->addProduct($dataProd);
}
$execTime = microtime(true) - $this->startTime;
if ($execTime + 1 >= $this->maxExecTime) {
header("Content-type: text/xml; charset=utf-8");
echo "xEFxBBxBF";
echo "progressrn";
echo "Выгружено товаров: $currentPosition";
$_SESSION['lastCountProduct1cImport'] = $currentPosition;
exit();
}
// echo "<br/>". (string) $item->Наименование[0]." добавлен в ". $category[$id]['name'].' '.(string)$item->Ид[0];
}
if ($this->unlinkFile) {
unlink($filename);
}
$_SESSION['lastCountProduct1cImport'] = 0;
} elseif ($xml && $filename == 'offers.xml') {
$currentPosition = 0;
foreach ($xml->ПакетПредложений[0]->Предложения[0] as $item) {
$currentPosition++;
if ($currentPosition <= $lastPositionOffer) {
continue;
}
$id = (string) $item->Ид[0];
$price = (string) $item->Цены->Цена->ЦенаЗаЕдиницу[0];
$count = (string) $item->Количество[0];
$code = !empty($item->Артикул[0])?$item->Артикул[0]:$item->ШтрихКод[0];
$partProd = array('price' => $price, 'count' => $count, 'code' => $code, 'price_course' => $price);
DB::query('
UPDATE `'.PREFIX.'product`
SET '.DB::buildPartQuery($partProd).'
WHERE 1c_id = '.DB::quote($id).'
');
$execTime = microtime(true) - $this->startTime;
if ($execTime + 1 >= $this->maxExecTime) {
header("Content-type: text/xml; charset=utf-8");
echo "xEFxBBxBF";
echo "progressrn";
echo "Выгружено предложений: $currentPosition";
$_SESSION['lastCountOffer1cImport'] = $currentPosition;
exit();
}
}
if ($this->unlinkFile) {
unlink($filename);
}
$_SESSION['lastCountOffer1cImport'] = 0;
Storage::clear();
} else {
echo "Ошибка загрузки XMLn";
foreach (libxml_get_errors() as $error) {
echo "t", $error->message;
exit;
}
}
}
/**
* Обход дерева групп полученных из 1С
*/
function groupsGreate($xml, $category, $parent) {
if (!$parent) {
$parent = array('category_id' => 0, 'name' => '');
}
if (!isset($xml->Группы)) {
return $category;
}
foreach ($xml->Группы->Группа as $category_data) {
$name = (string) $category_data->Наименование;
$cnt = (string) $category_data->Ид;
$category[$cnt]['1c_id'] = $cnt;
$category[$cnt]['name'] = $name;
$category[$cnt]['parent_id'] = $parent['category_id'];
$category[$cnt]['parentname'] = $parent['name'];
$category[$cnt]['description'] = "Описание";
$category[$cnt]['category_id'] = $this->newCategory($category[$cnt]);
$category = $this->groupsGreate($category_data, $category, $category[$cnt]);
}
return $category;
}
/**
* Создание новой категории
*/
function newCategory($category) {
$url = URL::prepareUrl(MG::translitIt($category['name'], 1));
$parent_url = MG::get('category')->getParentUrl($category['parent_id']);
$parent = URL::prepareUrl(MG::translitIt($category['parentname'], 1));
$data = array(
'title' => $category['name'],
'url' => $url,
'parent' => $category['parent_id'],
'html_content' => $category['description'],
'meta_title' => $category['name'],
'meta_keywords' => $category['name'],
'meta_desc' => MG::textMore($category['description'], 157),
'invisible' => 0,
'parent_url' => $parent_url,
'1c_id' => $category['1c_id'],
);
$res = DB::query('SELECT * FROM '.PREFIX.'category WHERE `1c_id`='.DB::quote($category['1c_id']));
if ($row = DB::fetchAssoc($res)) {
DB::query('
UPDATE `'.PREFIX.'category`
SET '.DB::buildPartQuery($data).'
WHERE `1c_id`='.DB::quote($category['1c_id'])
);
return $row['id'];
} else {
$data = MG::get('category')->addCategory($data);
return $data['id'];
}
return 0;
}
public function getImportXml($filename) {
//$filename = 'temp_'.$filename;
// MG::loger('temp_'.$filename);
$xml = simplexml_load_file($filename);
return $xml;
}
}