/controllers/DefaultController.php
PHP | 235 lines | 187 code | 22 blank | 26 comment | 82 complexity | 78ec15bcce11617163ced54141093e22 MD5 | raw file
- <?php
- /**
- * @author ReRe Design studio
- * @email webmaster@rere-design.ru
- */
- class DefaultController extends RController
- {
- protected $_result = array();
- protected $fileLimit = 8000000;
- protected $zip = false;
- protected $dir = '_upload1C';
- public $clear = false;
- public $timestamp = 0;
- private $_parseTree;
- public $_status;
- public $status = 0;
- public $adminNotify = 0;
- public function actionIndex($type = null, $mode = null, $filename = null, $dir = false)
- {
- if ($dir) $dir = $this->baseDir . $dir . DIRECTORY_SEPARATOR;
- $this->_status = Yii::app()->user->getState(Yii::app()->request->requestUri);
- if ($this->adminNotify) mail(Yii::app()->params['adminEmail'], 'COME ' . Yii::app()->session->sessionID, "REQUEST: " . print_r($_REQUEST, 1) . "\r\nSERVER: " . print_r($_SERVER, 1));
- switch ($mode):
- // Авторизация, отдаем сессию
- case 'checkauth':
- if ($this->register())
- $this->result(array('success', 'PHPSESSID', Yii::app()->session->sessionID));
- else {
- $this->result('failure', 0);
- }
- break;
- // Вход, отдаем настройки
- case 'init':
- if (Yii::app()->user->isGuest && !$this->register()) break;
- if (!Yii::app()->user->hasState('dir')) {
- $dir = $this->baseDir . date('Y-m-d_H-i_') . Yii::app()->user->id . DIRECTORY_SEPARATOR;
- Yii::app()->user->setState('dir', $dir);
- }
- $this->result(array('zip=' . ($this->zip ? 'yes' : 'no'), 'file_limit=' . $this->fileLimit));
- break;
- // Файл, получаем файл
- case 'file':
- if (Yii::app()->user->isGuest && !$this->register()) break;
- $fileData = file_get_contents("php://input");
- if (empty($fileData))
- $this->result(array('failure', 'data is empty'), 0);
- if (!$dir = Yii::app()->user->getState('dir'))
- $this->result(array('failure', 'can`t get session dir'), 0);
- if (!$this->ensureDirectory(dirname($dir . $filename)))
- $this->result(array('failure', 'can`t create dir in path ' . $dir . $filename), 0);
- if (!$fp = fopen($dir . $filename, "ab"))
- $this->result(array('failure', 'can`t open file ' . $filename), 0);
- if (!fwrite($fp, $fileData))
- $this->result(array('failure', 'can`t write in file ' . $filename), 0);
- $this->result('success');
- break;
- // Обрабатываем данные
- case 'import':
- if (Yii::app()->user->isGuest && !$this->register()) break;
- if (!$dir && !$dir = Yii::app()->user->getState('dir'))
- $this->result(array('failure', 'can`t get session dir'), 0);
- Yii::app()->params['parseDir'] = $dir;
- if (!file_exists($dir . $filename))
- $this->result(array('failure', 'can`t find file ' . $dir . $filename), 0);
- if ($this->zip && end(explode('.', $filename)) == 'zip') {
- $this->unzip($dir, $filename);
- $this->result('success');
- break;
- }
- $this->timestamp = filemtime($dir . $filename);
- if (!$xml = new XMLReader())
- $this->result(array('failure', 'can`t create xml reader'), 0);
- if (!$xml->open($dir . $filename))
- $this->result(array('failure', 'can`t open xml file ' . $dir . $filename), 0);
- $data = false;
- while ($xml->read()) {
- if ($xml->getAttribute('СодержитТолькоИзменения') == 'false')
- $this->clear = $this->timestamp;
- foreach ($this->parseTree as $key => $val)
- if ($xml->name == $key && $xml->nodeType == XMLReader::ELEMENT)
- if (is_array($data)) $data += $this->parse($xml, $val);
- else $this->parse($xml, $val);
- }
- Yii::app()->user->setState(Yii::app()->request->requestUri, null);
- if ($data) CVarDumper::dump($data, 10, 1);
- // if($this->clear) ImportModel::clearBase($this->clear);
- $this->result('success');
- break;
- // Отдаем файл с заказами
- case 'query':
- if ($type == 'sale') OrderXml::printThis();
- break;
- // Возвращаем такой же ответ
- case 'success':
- $this->result('success');
- mail(Yii::app()->params['adminEmail'], '1C FINISHED ' . $mode, "REQUEST: " . print_r($_REQUEST, 1) . "\r\nSERVER: " . print_r($_SERVER, 1));
- break;
- // Если ничего не найдено пишем ошибку
- default:
- mail(Yii::app()->params['adminEmail'], '1C ERROR ' . $mode, "REQUEST: " . print_r($_REQUEST, 1) . "\r\nSERVER: " . print_r($_SERVER, 1));
- if(!$type && $this->_status > 0){
- sleep(5);
- $this->refresh();
- } else $this->result(array('failure', 'invalid mode'));
- endswitch;
- if (!$this->_result) $this->result(array('failure', 'invalid action or not logged in'));
- if ($this->adminNotify) mail(Yii::app()->params['adminEmail'], 'RESULT ALL ' . Yii::app()->session->sessionID, implode("\r\n", $this->_result) . "\r\n\r\nREQUEST: " . print_r($_REQUEST, 1) . "\r\nSERVER: " . print_r($_SERVER, 1));
- $this->_result[] = '';
- echo implode("\r\n", $this->_result);
- }
- public function register()
- {
- $model = new LoginForm();
- $model->attributes = array(
- 'email' => $_SERVER['PHP_AUTH_USER'],
- 'password' => $_SERVER['PHP_AUTH_PW'],
- );
- return ($model->validate() && $model->login($_SERVER['PHP_AUTH_PW']));
- }
- public function result($data, $return = true)
- {
- if($this->status) Yii::app()->user->setState(Yii::app()->request->requestUri, $this->status);
- $data = (array)$data;
- $this->_result = CMap::mergeArray($this->_result, $data);
- if (!$return) die(implode("\r\n", $this->_result));
- else return true;
- }
- protected function getParseTree()
- {
- if (!$this->_parseTree) $this->_parseTree = require_once(dirname(__FILE__) . '/../config/parse.php');
- return $this->_parseTree;
- }
- /**
- * Parse universally.
- * @param $xml XMLReader
- * @param $values array
- * @return array
- */
- public function parse(&$xml, $values)
- {
- $data = array();
- $depth = $i = 0;
- do {
- $this->status++;
- if ($xml->name == $values['start'] && $xml->nodeType == XMLReader::ELEMENT) {
- $depth = $xml->depth;
- $i++;
- }
- if ($i) {
- foreach ($values['array'] as $key => $val) {
- if (is_string($val) && $value = $this->getValue($xml, $key))
- $data[$values['name']][$i][$val] = $value;
- elseif (is_array($val) && $xml->name == $key && $xml->nodeType == XMLReader::ELEMENT) {
- $data[$values['name']][$i] += $this->parse($xml, $val);
- }
- }
- }
- if ($values['save'] && $xml->name == $values['start'] && $xml->nodeType == XMLReader::END_ELEMENT) {
- if ($this->status > $this->_status) {
- // echo (time()-$_SERVER['REQUEST_TIME']) .' ' . $this->_status . '-' . $this->status . '<br>';
- ImportModel::createElement($data[$values['name']][$i], $values['name'], false, $this->timestamp, $this->clear);
- if ($this->life) $this->result('progress', false);
- }
- $data = array();
- }
- if ($xml->nodeType == XMLReader::END_ELEMENT && $depth == $xml->depth + 1) break;
- } while ($xml->read());
- return $data;
- }
- public function getValue(&$xml, $key)
- {
- if ($xml->name == $key && $xml->nodeType == XMLReader::ELEMENT)
- while ($xml->read())
- if ($xml->nodeType == XMLReader::TEXT) return $xml->value;
- elseif ($xml->nodeType == XMLReader::END_ELEMENT) break;
- return false;
- }
- public function ensureDirectory($directory)
- {
- if (!is_dir($directory)) {
- $this->ensureDirectory(dirname($directory));
- if (!mkdir($directory))
- return false;
- }
- return true;
- }
- public function unzip($dir, $filename)
- {
- $zip = new ZipArchive;
- if ($zip->open($dir . $filename) === true) {
- $zip->extractTo($dir);
- $zip->close();
- return true;
- }
- return false;
- }
- /*public function actionClearAll()
- {
- if (Yii::app()->user->checkAccess('administrator')) {
- $sql = 'DELETE FROM page WHERE module_id=8 AND (LEVEL>1 OR ISNULL(LEVEL));';
- Yii::app()->db->createCommand($sql)->execute();
- }
- }*/
- public function getLife()
- {
- $time = time() - $_SERVER['REQUEST_TIME'];
- return ($time > (20)) || Yii::getLogger()->memoryUsage > ((ini_get('memory_limit') - 5) * 1024 * 1024);
- }
- public function getBaseDir()
- {
- return Yii::getPathOfAlias('webroot.data.' . $this->dir) . DIRECTORY_SEPARATOR;
- }
- }