Version: current

      1 <?php
      2 // Контроллер обработки запросов от 1С
      3 class Import1C_Controller extends ContentController implements PermissionProvider {
      4
      5     static $debug = true;
      6
      7     static $upload_limit = 26214400; // 25МБ; 100MB - много, php валится по памяти при конструировании SS_HTTPRequest в action контроллера
      8
      9     static $controllers = array();
     10
     11     private static $max_log_count = 30;
     12
     13     static function get_log($type, $new=false) {
     14         $logId = (int)Session::get('Import1C.ImportLogID');
     15         if (!$new) {
     16             self::debug("ImportLogID: " . $logId);
     17             // !! Всегда возвращаем Лог по ID - если не нашли, то ошибка и взаимодействие заново !!
     18             return DataObject::get_by_id('Import1CLog', $logId);
     19         }
     20
     21
     22         /*
     23         $log = Import1CLog::get_last_log();
     24         if ($log && $log->Status == 'process') {
     25             $log->EndTime = $log->LastEdited;
     26             $log->addStatus('error', _t('ProductCatalogImportTask.ScriptUnexpectStop','Импорт неожиданно прекратил работу'));
     27         }
     28         */
     29
     30         // почистим старые Import1CLog
     31         $max_log_count = self::$max_log_count - 1;
     32         if ($oldImportLogs = DataObject::get('Import1CLog', '', 'ID DESC', '', "{$max_log_count},100")) {
     33             foreach($oldImportLogs as $oldImportLog) {
     34                 $oldImportLog->delete();
     35             }
     36         }
     37
     38         // заведем новый
     39         $importLog = new Import1CLog();
     40         $importLog->Type = $type;
     41         $importLog->write();
     42         $importLog->addLog(_t('ProductCatalogImport.ImportStarted', 'Import Session Started'));
     43         if (isset($_SERVER['REMOTE_ADDR'])) {
     44             $importLog->addLog(_t('ProductCatalogImport.FromIP', 'From IP: ') .  $_SERVER['REMOTE_ADDR']);
     45         }
     46
     47         Session::set('Import1C.ImportLogID', $importLog->ID);
     48         Session::save();
     49         return $importLog;
     50     }
     51
     52     static function debug_log($data) {
     53         if (self::$debug)
     54             file_put_contents(TEMP_FOLDER . '/1c.log', $data."\n", FILE_APPEND);
     55     }
     56
     57     function providePermissions() {
     58         return array(
     59             'EXCHANGE_1C' => array(
     60                 'name' => _t('EXCHANGE_1C.EXCHANGE_1C_ORDERS', 'Export orders to 1C'),
     61                 'category' => _t('Permissions.PERMISSIONS_CATEGORY', 'Roles and access permissions'),
     62                 'help' => _t('EXCHANGE_1C.EXCHANGE_1C_ORDERS_HELP', 'Ability to export orders to 1C.'),
     63                 'sort' => 400
     64             )
     65         );
     66     }
     67
     68     function init() {
     69         parent::init();
     70
     71         self::debug_log(date("\n\n-------\nc"));
     72         self::debug_log('ip: ' . $_SERVER['REMOTE_ADDR']);
     73         self::debug_log('request: ' . $_SERVER['REQUEST_URI']);
     74
     75         self::debug_log('checkAuth:');
     76         self::debug_log('cookie: ' . var_export($_COOKIE, true));
     77         self::debug_log('session: ' . var_export($_SESSION, true));
     78         self::debug_log('member: ' . Member::currentUserID());
     79
     80         // если не авторизованы по сессии
     81         if (!Permission::check('EXCHANGE_1C')) {
     82             self::debug_log("Try HTTP auth with login: {$_SERVER[PHP_AUTH_USER]} pass: {$_SERVER[PHP_AUTH_PW]}");
     83             // HTTP авторизация
     84             // либо возвращает $member либо умирает с кодом 401
     85             $member = BasicAuth::requireLogin('1C EXCHANGE', 'EXCHANGE_1C');
     86             if ($member === true) {
     87                 // cli mode or DB not ready
     88                 self::debug_log('cli mode');
     89             }
     90             else {
     91                 $member->logIn();
     92                 Session::save();
     93
     94                 self::debug_log("access granted to: {$member->ID} ({$member->Email})");
     95             }
     96         }
     97     }
     98
     99     function index($request) {
    100         $type = $request->requestVar('type');
    101         $mode = $request->requestVar('mode');
    102
    103         if ($mode == 'checkauth') {
    104             /*
    105                 catalog + checkauth - не должен возвращать failure даже если подмодуля нет (т.к. используется для проверки связи)
    106                 catalog + * - возвращает failure если подмодуль не зарегистрирован
    107                 sale + * - возвращает failure если подмодуль не зарегистрирован
    108             */
    109             if (($type == 'catalog') || (isset(self::$controllers[$type]) && class_exists(self::$controllers[$type]))) {
    110                 $log = self::get_log($type, true); // заводим новый лог тут
    111                 echo "success\n" . session_name()."\n" . session_id() . "\n";
    112             } else {
    113                 echo "failure\n";
    114                 echo "wrong exchange state ({$type}:{$mode})\n";
    115             }
    116             return;
    117         }
    118
    119         $log = self::get_log($type);
    120         if (!$log) {
    121             echo "failure\n";
    122             echo "wrong exchange state ({$type}:{$mode}), need restart\n";
    123             return;
    124         }
    125
    126         if (isset(self::$controllers[$type]) && class_exists(self::$controllers[$type])) {
    127             $controller = new self::$controllers[$type];
    128             if ($controller->hasMethod($mode)) {
    129                 $controller->$mode($request); // как-то криииво ((((
    130             } else {
    131                 $log->addStatus('error', "Неверный режим: {$type}:{$mode}");
    132                 echo "failure\n";
    133                 echo "invalid type: {$type}:{$mode}\n";
    134             }
    135         } else {
    136             $log->addStatus('error', "Неверный режим: {$type}:{$mode}");
    137             echo "failure\n";
    138             echo "invalid type: {$type}:{$mode}\n";
    139         }
    140         return;
    141     }
    142 }
    143

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