Version: current

      1 <?php
      2 // Контроллер обработки запросов импорта каталога из 1С
      3 class ImportCatalog1C_Controller extends Import1C_Controller {
      4
      5     static $zip = 'yes';
      6
      7     function init($request) {
      8         $log = Import1C_Controller::get_log('catalog');
      9         $log->addStage('init', 'Согласование параметров обмена');
     10         $log->addLog(sprintf("import mode: zip=%s file_limit=%d", self::$zip, Import1C_Controller::$upload_limit));
     11
     12         printf("zip=%s\nfile_limit=%d\n", self::$zip, Import1C_Controller::$upload_limit);
     13         return;
     14     }
     15
     16     function file($request) {
     17         $log = Import1C_Controller::get_log('catalog');
     18         if (!$log) {
     19             echo "failure\n";
     20             echo "wrong exchange state (catalog:file), need restart\n";
     21             return;
     22         }
     23         $log->addStage('file');
     24         $filename = $request->requestVar('filename');
     25
     26         $upload_file = Base1CExchanger::absolute_import_path($filename);
     27         if ($request->getBody()) {
     28             // создаем папки по пути файлов
     29             $isInFolder = preg_match("!^(.*)/([^/]+)$!", $upload_file, $filepathMatches);
     30             if($isInFolder) {
     31                 $folderName = $filepathMatches[1];
     32                 $fileName = $filepathMatches[2];
     33                 if (!is_dir($folderName)) {
     34                     if (!mkdir($folderName, Filesystem::$folder_create_mask, true)) {
     35                         $log->addStatus('error', "Ошибка создания папки: {$folderName}");
     36                         echo "failure\n";
     37                         echo "Can't mkdir: {$folderName}\n";
     38                     }
     39                 }
     40             }
     41
     42             $filePutFlag = 0;
     43             if ($log->Files("Filename = '{$filename}'")->Count()) {
     44                 $filePutFlag = FILE_APPEND;
     45             }
     46             else {
     47                 $queue = $log->addUploadFile($filename);
     48             }
     49             file_put_contents($upload_file, $request->getBody(), $filePutFlag);
     50
     51             if ($log->Files()->Count() % 10 == 0) {
     52                 $log->addStage('file', sprintf(_t('ProductCatalogImport.UploadFilesCount', '%d files uploaded'), $log->Files()->Count()));
     53             }
     54             echo "success\n";
     55         }
     56         else {
     57             $msg = sprintf(_t('ProductCatalogImport.FileUploadFail', 'Upload %s Fail'), $filename);
     58             $log->addLog($msg, 'error');
     59             $log->addStatus('error', $msg);
     60             echo "failure\n";
     61             echo "Can't upload file: {$filename}\n";
     62         }
     63         return;
     64     }
     65
     66     function import($request) {
     67         ini_set('max_execution_time', 1800);
     68         $log = Import1C_Controller::get_log('catalog');
     69         if (!$log) {
     70             echo "failure\n";
     71             echo "wrong exchange state (catalog:import), need restart\n";
     72             return;
     73         }
     74
     75         Import1C_Controller::debug_log("stage: " . $log->Stage);
     76         if ($log->Stage != 'import') {
     77             $log->addLog(sprintf(_t('ProductCatalogImport.UploadFilesCount', '%d files uploaded'), $log->Files()->Count()));
     78
     79             if (self::$zip == 'yes') {
     80                 $log->addStage('unzip', 'Распаковка архива');
     81                 if ($zipList = $log->Files('Filename RLIKE \'.*\\.zip$\'', 'ID')) {
     82                     foreach ($zipList as $zip) {
     83                         $log->addLog(sprintf(_t("ProductCatalogImport.Unzipfile", "Unzip %s"), $zip->Filename));
     84
     85                         $ziper = new ZipArchive;
     86                         $res = $ziper->open(Base1CExchanger::absolute_import_path($zip->Filename));
     87                         $rs = false;
     88                         if ($res === true) {
     89                             $rs = $ziper->extractTo(Base1CExchanger::absolute_import_path(''));
     90                             $ziper->close();
     91                         }
     92                         if ($rs) {
     93                             unlink(Base1CExchanger::absolute_import_path($zip->Filename));
     94                         } else {
     95                             $log->addLog("Unzip error ($res): ", 'error');
     96                             $log->addStatus('error', "Ошибка распаковки архива");
     97                             echo "failure\n";
     98                             echo "Unzip error:\n" . join("\n", $output) . "\n";
     99                             return;
    100                         }
    101                     }
    102                 }
    103             }
    104         }
    105
    106         $log->addStage('import', 'Ожидаем начала импорта');
    107
    108         // FIXME перенести в Import1CLog::addImportTask()
    109         $taskDir = '_tasks/' . $log->ID;
    110         $taskFolder = Base1CExchanger::absolute_import_path($taskDir);
    111         if (!is_dir($taskFolder)) {
    112             if (!mkdir($taskFolder, Filesystem::$folder_create_mask, true)) {
    113                 $log->addLog("Ошибка создания папки: {$taskFolder}", 'error');
    114                 $log->addStatus('error', "Ошибка создания папки очереди задач");
    115                 echo "failure\n";
    116                 echo "Can't create import queue folder\n";
    117             }
    118         }
    119
    120         $filename = $request->requestVar('filename');
    121         $taskName = preg_replace('!/!', '-', $filename);
    122         $uploadedPath = Base1CExchanger::absolute_import_path($filename);
    123         $taskPath = $taskFolder . '/' . $taskName;
    124         if (is_file($uploadedPath)) {
    125             // здесь только сохраняем файлы запуска импорта, иначе скрипт не может отработать по лимиту времени
    126
    127             if (!rename($uploadedPath, $taskPath)) {
    128                 $log->addLog("Ошибка переноса: {$filename} в {$taskPath}", 'error');
    129                 $log->addStatus('error', "Ошибка импорта файла: {$filename} в каталог загрузки");
    130                 echo "failure\n";
    131                 echo "Can't move: {$filename} to task queue\n";
    132             }
    133
    134             if (strpos($filename, 'import') !== false) {
    135                 $operation = 'catalog';
    136             }
    137             elseif (strpos($filename, 'offers') !== false) {
    138                 $operation = 'offers';
    139             }
    140             else {
    141                 $operation = 'orders';
    142             }
    143             $log->addImportTask($taskDir . '/' . $taskName, $operation);
    144             echo "success\n";
    145         }
    146         else {
    147             $log->addStatus('error', "Ошибка импорта файла {$filename} - файл не найден");
    148             echo "failure\n";
    149             echo "Bad file: {$filename}\n";
    150         }
    151         return;
    152     }
    153 }
    154

[Raise a SilverStripe Framework issue/bug](https://github.com/silverstripe/silverstripe-framework/issues/new)
- [Raise a SilverStripe CMS issue/bug](https://github.com/silverstripe/silverstripe-cms/issues/new)
- Please use the Silverstripe Forums to ask development related questions. -