Version: current

      1 <?php
      2 class ProductImportAdmin extends ModelAdmin {
      3
      4     public static $managed_models = array(
      5         'ProductImportLog'
      6     );
      7
      8     static $url_segment = 'import';
      9     static $menu_title = 'Импорт';
     10     static $menu_priority = -10;
     11
     12     public static $collection_controller_class = "ProductImportAdmin_CollectionController";
     13
     14     function getLastLog(){
     15         return ProductImportLog::get_last_log();
     16     }
     17
     18     function getWaitforstart() {
     19         return file_exists(ProductCatalogImportTask::absolute_import_path('start_ok'));
     20     }
     21
     22     function getIsImportCanceled() {
     23         $rs = Session::get('Import.ImportCanceled');
     24         Session::clear('Import.ImportCanceled');
     25         return $rs;
     26     }
     27
     28     function getImportValidationMessage() {
     29         $rs = Session::get('Import.ValidationMessage');
     30         Session::clear('Import.ValidationMessage');
     31         return $rs;
     32     }
     33 }
     34
     35
     36 class ProductImportAdmin_CollectionController extends ModelAdmin_CollectionController {
     37
     38     public function getModelSidebar() {
     39         return $this->renderWith('ProductImportAdminModelSidebar');
     40     }
     41
     42     public function ImportForm() {
     43         $sc = SiteConfig::current_site_config();
     44         $fields = new FieldSet();
     45
     46         $fileField = new FileField('ImportFile', _t('ProductImportAdmin.ImportFile','Import File'));
     47         $fileField->allowedExtensions = array('xml');
     48         $uploadValidator = new Upload_Validator();
     49         $uploadValidator->setAllowedExtensions(array('xml'));
     50         $fileField->setValidator($uploadValidator);
     51         $fields->push($fileField);
     52
     53         $fields->push(new DropdownField("StartPage", _t('ImportSiteConfig.StartPage', 'Start Page'), $sc->getImportStartPageMap(), $sc->StartPage));
     54         if (class_exists('SubSite')) {
     55             $tab->push(new DropdownField("SubSite", _t('ImportSiteConfig.SubSite', 'Sub Site'), $sc->getSubSiteMap(), $sc->SubSite));
     56         }
     57         $fields->push(new DropdownField('ImportMode', _t('ProductImportAdmin.ImportMode','Import Mode'), $sc->getImportModeMap(), $sc->ImportMode));
     58         $fields->push(new DropdownField('OldItemAction', _t('ImportAdmin.OldItemAction','OldItemAction'), $sc->getOldItemActionMap(), $sc->OldItemAction));
     59         $fields->push(new CheckboxField('ClearCategory',  _t('ProductImportAdmin.ClearCategory','Clear Category'), $sc->ClearCategory=='true'));
     60         $fields->push(new CheckboxField('ClearProducts', _t('ProductImportAdmin.ClearProducts','Clear Products'), $sc->ClearProducts=='true'));
     61
     62         //$fields->push(new FileField('UploadFileToValidate', 'Файл импорта для валидации'));
     63
     64         $actions = new FieldSet(
     65             new FormAction('prepareImport', _t('ProductImportAdmin.PrepareImport','Prepare Import')),
     66             new FormAction('cancelImport', _t('ProductImportAdmin.CancelImport','Cancel Import')),
     67             new FormAction('validateImport', _t('ProductImportAdmin.ValidateImport','Validate Import File'))
     68         );
     69
     70         $validator = new RequiredFields(array('ImportFile', 'ImportMode'));
     71         $validator->setJavascriptValidationHandler('none');
     72
     73         $form = new Form(
     74             $this,
     75             'ImportForm',
     76             $fields,
     77             $actions,
     78             $validator
     79         );
     80         return $form;
     81
     82     }
     83
     84     /*
     85      * Подготовка к импорту:
     86      * - загрузка файла импорта  и копирование в нужную папку
     87      * - создание файла настроек
     88      * - создание файла start_ok
     89      *
     90      */
     91     function prepareImport($data, $form) {
     92         if (isset($data['ImportFile']['tmp_name']) && is_file($data['ImportFile']['tmp_name'])) {
     93             move_uploaded_file($data['ImportFile']['tmp_name'], ProductCatalogImportTask::absolute_import_path(ProductCatalogImportTask::getImportFileName()));
     94             $config = $this->customise(
     95                 array(
     96                     'Data' => $data
     97                 )
     98             )->renderWith('Config');
     99             file_put_contents(ProductCatalogImportTask::absolute_import_path('config.xml'), $config);
    100             file_put_contents(ProductCatalogImportTask::absolute_import_path('start_ok'), '');
    101             $form->sessionMessage(_t('ProductImportAdmin.ImportTaskCreated', 'File is uploded. Import start closely.'), 'info');
    102
    103             if (file_exists(ProductCatalogImportTask::absolute_import_path('cancelImport')))
    104                 unlink(ProductCatalogImportTask::absolute_import_path('cancelImport'));
    105             if (file_exists(ProductCatalogImportTask::absolute_import_path('validateImport')))
    106                 unlink(ProductCatalogImportTask::absolute_import_path('validateImport'));
    107         }
    108         else {
    109         }
    110         Director::redirectBack();
    111
    112     }
    113
    114     /*
    115      * Отмена импорта:
    116      * - удаление импорта  и копирование в нужную папку
    117      * - удаление файла настроек
    118      * - удаление файла start_ok
    119      *
    120      */
    121     function cancelImport($data, $form) {
    122         //if (is_file(CatalogImportTask::absolute_import_path('import.xml')))
    123         //  unlink(CatalogImportTask::absolute_import_path('import.xml'));
    124         if (is_file(ProductCatalogImportTask::absolute_import_path('config.xml')))
    125             unlink(ProductCatalogImportTask::absolute_import_path('config.xml'));
    126         if (is_file(ProductCatalogImportTask::absolute_import_path('start_ok'))) {
    127             unlink(ProductCatalogImportTask::absolute_import_path('start_ok'));
    128             $form->sessionMessage(_t('ProductImportAdmin.ImportTaskCanceled', 'Import Canceled.'), 'info');
    129             Session::set('Import.ImportCanceled',  _t('ProductImportAdmin.ImportTaskCanceled', 'Import Canceled.'));
    130         }
    131         Director::redirectBack();
    132     }
    133
    134     /*
    135      * Валидация файла импорта
    136      *
    137      */
    138     function validateImport($data, $form) {
    139         if (isset($data['ImportFile']['tmp_name']) && ($data['ImportFile']['size'] > 0) && is_file($data['ImportFile']['tmp_name'])) {
    140             $validator = new XMLValidate($data['ImportFile']['tmp_name'], ProductCatalogImportTask::module_path('catalog3.xsd'));
    141             $rs = $validator->validate();
    142             if ($rs != 'validated') {
    143                 $errorText = '';
    144                 foreach ($rs as $error)
    145                     $errorText .= _t('ProductCatalogImportTask.ValidationError', 'Validation Error') . ': ' . $error . '<br>';
    146                 if ($errorText) {
    147                     Session::set('Import.ValidationMessage',  $errorText);
    148                 }
    149             } else {
    150                 //Если нет ошибок - удаляем оставшийся файл с инфо о предыдущих ошибках валидации
    151                 if (is_file(ProductCatalogImportTask::absolute_import_path('validateImport')))  {
    152                     unlink(ProductCatalogImportTask::absolute_import_path('validateImport'));
    153                 }
    154                 Session::set('Import.ValidationMessage', _t('ProductImportAdmin.ValidationSuccess', 'Validation Success'));
    155             }
    156             unlink($data['ImportFile']['tmp_name']);
    157         }
    158         Director::redirectBack();
    159     }
    160
    161     public function CreateForm() {
    162         return false;
    163     }
    164
    165     function getResultsTable($searchCriteria) {
    166         $tf = parent::getResultsTable($searchCriteria);
    167         $tf->setHighlightConditions(array(
    168             array('rule'=>'$Status == "process"', 'class' => 'process', 'exclusive' => false),
    169             array('rule'=>'$Status == "error"', 'class' => 'error', 'exclusive' => false),
    170         ));
    171         return $tf;
    172     }
    173 }

[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. -