PageRenderTime 43ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/controllers/DefaultController.php

https://bitbucket.org/reredesign/bitrix-module
PHP | 235 lines | 187 code | 22 blank | 26 comment | 82 complexity | 78ec15bcce11617163ced54141093e22 MD5 | raw file
  1. <?php
  2. /**
  3. * @author ReRe Design studio
  4. * @email webmaster@rere-design.ru
  5. */
  6. class DefaultController extends RController
  7. {
  8. protected $_result = array();
  9. protected $fileLimit = 8000000;
  10. protected $zip = false;
  11. protected $dir = '_upload1C';
  12. public $clear = false;
  13. public $timestamp = 0;
  14. private $_parseTree;
  15. public $_status;
  16. public $status = 0;
  17. public $adminNotify = 0;
  18. public function actionIndex($type = null, $mode = null, $filename = null, $dir = false)
  19. {
  20. if ($dir) $dir = $this->baseDir . $dir . DIRECTORY_SEPARATOR;
  21. $this->_status = Yii::app()->user->getState(Yii::app()->request->requestUri);
  22. if ($this->adminNotify) mail(Yii::app()->params['adminEmail'], 'COME ' . Yii::app()->session->sessionID, "REQUEST: " . print_r($_REQUEST, 1) . "\r\nSERVER: " . print_r($_SERVER, 1));
  23. switch ($mode):
  24. // Авторизация, отдаем сессию
  25. case 'checkauth':
  26. if ($this->register())
  27. $this->result(array('success', 'PHPSESSID', Yii::app()->session->sessionID));
  28. else {
  29. $this->result('failure', 0);
  30. }
  31. break;
  32. // Вход, отдаем настройки
  33. case 'init':
  34. if (Yii::app()->user->isGuest && !$this->register()) break;
  35. if (!Yii::app()->user->hasState('dir')) {
  36. $dir = $this->baseDir . date('Y-m-d_H-i_') . Yii::app()->user->id . DIRECTORY_SEPARATOR;
  37. Yii::app()->user->setState('dir', $dir);
  38. }
  39. $this->result(array('zip=' . ($this->zip ? 'yes' : 'no'), 'file_limit=' . $this->fileLimit));
  40. break;
  41. // Файл, получаем файл
  42. case 'file':
  43. if (Yii::app()->user->isGuest && !$this->register()) break;
  44. $fileData = file_get_contents("php://input");
  45. if (empty($fileData))
  46. $this->result(array('failure', 'data is empty'), 0);
  47. if (!$dir = Yii::app()->user->getState('dir'))
  48. $this->result(array('failure', 'can`t get session dir'), 0);
  49. if (!$this->ensureDirectory(dirname($dir . $filename)))
  50. $this->result(array('failure', 'can`t create dir in path ' . $dir . $filename), 0);
  51. if (!$fp = fopen($dir . $filename, "ab"))
  52. $this->result(array('failure', 'can`t open file ' . $filename), 0);
  53. if (!fwrite($fp, $fileData))
  54. $this->result(array('failure', 'can`t write in file ' . $filename), 0);
  55. $this->result('success');
  56. break;
  57. // Обрабатываем данные
  58. case 'import':
  59. if (Yii::app()->user->isGuest && !$this->register()) break;
  60. if (!$dir && !$dir = Yii::app()->user->getState('dir'))
  61. $this->result(array('failure', 'can`t get session dir'), 0);
  62. Yii::app()->params['parseDir'] = $dir;
  63. if (!file_exists($dir . $filename))
  64. $this->result(array('failure', 'can`t find file ' . $dir . $filename), 0);
  65. if ($this->zip && end(explode('.', $filename)) == 'zip') {
  66. $this->unzip($dir, $filename);
  67. $this->result('success');
  68. break;
  69. }
  70. $this->timestamp = filemtime($dir . $filename);
  71. if (!$xml = new XMLReader())
  72. $this->result(array('failure', 'can`t create xml reader'), 0);
  73. if (!$xml->open($dir . $filename))
  74. $this->result(array('failure', 'can`t open xml file ' . $dir . $filename), 0);
  75. $data = false;
  76. while ($xml->read()) {
  77. if ($xml->getAttribute('СодержитТолькоИзменения') == 'false')
  78. $this->clear = $this->timestamp;
  79. foreach ($this->parseTree as $key => $val)
  80. if ($xml->name == $key && $xml->nodeType == XMLReader::ELEMENT)
  81. if (is_array($data)) $data += $this->parse($xml, $val);
  82. else $this->parse($xml, $val);
  83. }
  84. Yii::app()->user->setState(Yii::app()->request->requestUri, null);
  85. if ($data) CVarDumper::dump($data, 10, 1);
  86. // if($this->clear) ImportModel::clearBase($this->clear);
  87. $this->result('success');
  88. break;
  89. // Отдаем файл с заказами
  90. case 'query':
  91. if ($type == 'sale') OrderXml::printThis();
  92. break;
  93. // Возвращаем такой же ответ
  94. case 'success':
  95. $this->result('success');
  96. mail(Yii::app()->params['adminEmail'], '1C FINISHED ' . $mode, "REQUEST: " . print_r($_REQUEST, 1) . "\r\nSERVER: " . print_r($_SERVER, 1));
  97. break;
  98. // Если ничего не найдено пишем ошибку
  99. default:
  100. mail(Yii::app()->params['adminEmail'], '1C ERROR ' . $mode, "REQUEST: " . print_r($_REQUEST, 1) . "\r\nSERVER: " . print_r($_SERVER, 1));
  101. if(!$type && $this->_status > 0){
  102. sleep(5);
  103. $this->refresh();
  104. } else $this->result(array('failure', 'invalid mode'));
  105. endswitch;
  106. if (!$this->_result) $this->result(array('failure', 'invalid action or not logged in'));
  107. 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));
  108. $this->_result[] = '';
  109. echo implode("\r\n", $this->_result);
  110. }
  111. public function register()
  112. {
  113. $model = new LoginForm();
  114. $model->attributes = array(
  115. 'email' => $_SERVER['PHP_AUTH_USER'],
  116. 'password' => $_SERVER['PHP_AUTH_PW'],
  117. );
  118. return ($model->validate() && $model->login($_SERVER['PHP_AUTH_PW']));
  119. }
  120. public function result($data, $return = true)
  121. {
  122. if($this->status) Yii::app()->user->setState(Yii::app()->request->requestUri, $this->status);
  123. $data = (array)$data;
  124. $this->_result = CMap::mergeArray($this->_result, $data);
  125. if (!$return) die(implode("\r\n", $this->_result));
  126. else return true;
  127. }
  128. protected function getParseTree()
  129. {
  130. if (!$this->_parseTree) $this->_parseTree = require_once(dirname(__FILE__) . '/../config/parse.php');
  131. return $this->_parseTree;
  132. }
  133. /**
  134. * Parse universally.
  135. * @param $xml XMLReader
  136. * @param $values array
  137. * @return array
  138. */
  139. public function parse(&$xml, $values)
  140. {
  141. $data = array();
  142. $depth = $i = 0;
  143. do {
  144. $this->status++;
  145. if ($xml->name == $values['start'] && $xml->nodeType == XMLReader::ELEMENT) {
  146. $depth = $xml->depth;
  147. $i++;
  148. }
  149. if ($i) {
  150. foreach ($values['array'] as $key => $val) {
  151. if (is_string($val) && $value = $this->getValue($xml, $key))
  152. $data[$values['name']][$i][$val] = $value;
  153. elseif (is_array($val) && $xml->name == $key && $xml->nodeType == XMLReader::ELEMENT) {
  154. $data[$values['name']][$i] += $this->parse($xml, $val);
  155. }
  156. }
  157. }
  158. if ($values['save'] && $xml->name == $values['start'] && $xml->nodeType == XMLReader::END_ELEMENT) {
  159. if ($this->status > $this->_status) {
  160. // echo (time()-$_SERVER['REQUEST_TIME']) .' ' . $this->_status . '-' . $this->status . '<br>';
  161. ImportModel::createElement($data[$values['name']][$i], $values['name'], false, $this->timestamp, $this->clear);
  162. if ($this->life) $this->result('progress', false);
  163. }
  164. $data = array();
  165. }
  166. if ($xml->nodeType == XMLReader::END_ELEMENT && $depth == $xml->depth + 1) break;
  167. } while ($xml->read());
  168. return $data;
  169. }
  170. public function getValue(&$xml, $key)
  171. {
  172. if ($xml->name == $key && $xml->nodeType == XMLReader::ELEMENT)
  173. while ($xml->read())
  174. if ($xml->nodeType == XMLReader::TEXT) return $xml->value;
  175. elseif ($xml->nodeType == XMLReader::END_ELEMENT) break;
  176. return false;
  177. }
  178. public function ensureDirectory($directory)
  179. {
  180. if (!is_dir($directory)) {
  181. $this->ensureDirectory(dirname($directory));
  182. if (!mkdir($directory))
  183. return false;
  184. }
  185. return true;
  186. }
  187. public function unzip($dir, $filename)
  188. {
  189. $zip = new ZipArchive;
  190. if ($zip->open($dir . $filename) === true) {
  191. $zip->extractTo($dir);
  192. $zip->close();
  193. return true;
  194. }
  195. return false;
  196. }
  197. /*public function actionClearAll()
  198. {
  199. if (Yii::app()->user->checkAccess('administrator')) {
  200. $sql = 'DELETE FROM page WHERE module_id=8 AND (LEVEL>1 OR ISNULL(LEVEL));';
  201. Yii::app()->db->createCommand($sql)->execute();
  202. }
  203. }*/
  204. public function getLife()
  205. {
  206. $time = time() - $_SERVER['REQUEST_TIME'];
  207. return ($time > (20)) || Yii::getLogger()->memoryUsage > ((ini_get('memory_limit') - 5) * 1024 * 1024);
  208. }
  209. public function getBaseDir()
  210. {
  211. return Yii::getPathOfAlias('webroot.data.' . $this->dir) . DIRECTORY_SEPARATOR;
  212. }
  213. }