Вход Регистрация
Файл: mg-core/lib/exchange1c.php
Строк: 252
<?php
/**
 * Класс Exchange1c - предназначен для обмена данными между "1с - Управление Торговлей" и Moguta.CMS.
 * - Импортирует товары и заказы
 *
 * @author Авдеев Марк <mark-avdeev@mail.ru>
 * @package moguta.cms
 * @subpackage Libraries
 */
class Exchange1c {

public 
$startTime null;
public 
$maxExecTime null;
public 
$mode null;  
public 
$type null;
public 
$filename null;
public 
$auth null;
public 
$tempCounter 0// удалить после внедрения процесса создания категорий

public function __construct() {/*
$_SERVER['PHP_AUTH_PW'] = "123456";
$_SERVER['PHP_AUTH_USER'] = "mark-avdeev@mail.ru";
$_GET['mode'] = 'import';
$_GET['type'] = "catalog";
//$_GET['filename'] = "offers.xml";
$_GET['filename'] = "import.xml";
*/
Storage::$noCache 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";
}

/**
 * 2 шаг - сообщаес в 1с клиент о поддержке работы с архивами.
 */
public function init() {
$zip extension_loaded('zip')?"yes":"no";
echo 
"zip=".$zip."n";
echo 
"file_limit=0n";
}

/**
 * 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)){
  
DB::query('DELETE FROM `mg_product` WHERE 1');
  
DB::query('DELETE FROM `mg_category` WHERE 1');
  
$_SESSION['lastCountOffer1cImport'] = 0;
  
$_SESSION['lastCountProduct1cImport'] = 0;
  echo 
"successn";
}else{
echo 
"failuren";
}
}else{
echo 
"failuren";
}

}

/**
 * 4 шаг - запуск процесса импорта файла выгрузки.
 */
public function import() {
$this->processImportXml($this->filename);
echo 
"successn";
echo 
session_name()."n";
echo 
session_id()."n";
}

/**
 * 5 шаг - распаковывает архив с данными по выгрузкам заказов и товаров.
 */
public static function extractZip($file) {

if (
file_exists($file)) {
$zip = new ZipArchive;
$res $zip->open($fileZIPARCHIVE::CREATE);

if (
$res === TRUE) {
$sep DIRECTORY_SEPARATOR;
$dirname dirname(__FILE__);
$realDocumentRoot str_replace($sep.'mg-core'.$sep.'lib'''$dirname);
$zip->extractTo($realDocumentRoot);
$zip->close();
unlink($file);
return 
true;
} else {
return 
false;
}
}
return 
false;
}


public function 
processImportXml($filename){
  
$sep DIRECTORY_SEPARATOR;
  
$dirname dirname(__FILE__);
  
$realDocumentRoot str_replace($sep.'mg-core'.$sep.'lib'''$dirname);

  
  
$lastPositionProduct $_SESSION['lastCountProduct1cImport'];
  
$lastPositionOffer $_SESSION['lastCountOffer1cImport'];
  
$xml $this->getImportXml($filename);
  if (
$xml && $filename == 'import.xml') {  
   
      
$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];       
        }
        
        
        
$dataProd = array(
         
'title' => $name,
         
'url' => 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($description157),
         
'recommend' => 0,
         
'activity' => 1,
         
'new' => 0,
         
'variants' => '',
         
'related' => '',
         
'inside_cat' => '',
         
'1c_id' => (string)$item->Ид[0],           
         
'weight' => '0',
        );
         
        
$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];          
      
}
      
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 = (string) $item->ШтрихКод[0]; 
        
     
/*   MG::loger('
          UPDATE `'.PREFIX.'product`
          SET '.DB::buildPartQuery(array('price'=>$price, 'count'=>$count)).'
          WHERE 1c_id = %d
        ');*/
        
DB::query('
          UPDATE `'
.PREFIX.'product`
          SET '
.DB::buildPartQuery(array('price'=>$price'count'=>$count'code'=>$code)).'
          WHERE 1c_id = %d
        '
$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();
                }
       
       
          
      }     
      
unlink($filename);
 
      
$_SESSION['lastCountOffer1cImport'] = 0;  
  } else {
      echo 
"Ошибка загрузки XMLn";
      foreach(
libxml_get_errors() as $error) {
          echo 
"t"$error->message;
      }
  }
}

# Обход дерева групп полученных из 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]['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) {  
  
  
$parent MG::translitIt($category['parentname'], 1);
  
  
$data = array(
    
'title' => $category['name'],
    
'url' => MG::translitIt($category['name'], 1),
    
'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' => MG::get('category')->getParentUrl($category['parent_id'])
  );
  
  
$data MG::get('category')->addCategory($data);
   
    
//echo "<br> создана группа:".$category['name'];
  
return $data['id'];
}

public function 
getImportXml($filename){
//  MG::loger('temp_'.$filename);
  
$xml simplexml_load_file($filename);
  
//$xml = simplexml_load_file('min_temp_'.$filename);
  
return $xml;

}
}
?>
Онлайн: 0
Реклама