FileStorage.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. <?php
  2. // @requires $_SERVER['SERVER_NAME']
  3. Lib::loadClass('RouteBase');
  4. Lib::loadClass('Response');
  5. Lib::loadClass('Request');
  6. Lib::loadClass('UI');
  7. Lib::loadClass('Http');
  8. Lib::loadClass('FileStorage');
  9. /*
  10. # upload API: `index.php?_route=FileStorage&_task=upload&name={file_name}`
  11. */
  12. class Route_FileStorage extends RouteBase {
  13. public function handleAuth() {
  14. if (!User::logged()) {
  15. User::authByRequest();
  16. }
  17. }
  18. public function defaultAction() {
  19. UI::gora();
  20. UI::menu();
  21. try {
  22. echo '...';
  23. } catch (Exception $e) {
  24. UI::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
  25. }
  26. UI::dol();
  27. }
  28. public function uploadStreamAction() {
  29. Response::sendTryCatchJson(array($this, 'uploadStreamResponseCallback'));
  30. }
  31. public function uploadStreamResponseCallback() {
  32. $response = array();
  33. $response['type'] = 'danger';
  34. $response['msg'] = "Wystąpił nieznany błąd podczas wgrywania pliku";
  35. $sqlLabel = V::get('name', '', $_REQUEST);
  36. // read contents from the input stream
  37. $inputHandler = fopen('php://input', "r");
  38. $idFile = FileStorage::addFileStream($inputHandler, $sqlLabel);
  39. $response['id'] = $idFile;
  40. $fileObject = FileStorage::getFileById($idFile);
  41. if ($fileObject['exists']) {
  42. $response['type'] = 'success';
  43. $response['msg'] = "Wgrano plik nr {$idFile}";
  44. }
  45. return $response;
  46. }
  47. public function uploadAction() {
  48. try {
  49. $fileContent = Request::getRequestBody();
  50. $sqlLabel = V::get('name', '', $_REQUEST);
  51. FileStorage::addFile($fileContent, $sqlLabel);
  52. echo 'file uploaded';
  53. } catch (Exception $e) {
  54. echo "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage();
  55. }
  56. }
  57. public function uploadFromBinaryTestAction() {
  58. try {
  59. $fileContent = Request::getRequestBody();
  60. $filePath = FileStorage::getRootStoragePath() . '/test-upload-data.txt';
  61. $fp = fopen($filePath, 'w');
  62. fwrite($fp, $fileContent);
  63. fclose($fp);
  64. echo 'file uploaded?';
  65. } catch (Exception $e) {
  66. echo "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage();
  67. }
  68. }
  69. public function downloadAction() {
  70. try {
  71. $id = V::get('id', 0, $_REQUEST, 'int');
  72. if ($id <= 0) throw new Exception("Error Wrong file id");
  73. $fileObject = FileStorage::getFileById($id);
  74. if (!$fileObject['exists']) throw new HttpException("File not exists", 404);
  75. header('Content-Description: File Transfer');
  76. header('Content-Type: ' . $fileObject['mimeType']);
  77. header('Content-Disposition: attachment; filename="' . $fileObject['name'] . '"');
  78. header('Expires: 0');
  79. header('Cache-Control: must-revalidate');
  80. header('Pragma: public');
  81. header('Content-Length: ' . $fileObject['size']);
  82. readfile($fileObject['absolutePath']);
  83. exit;
  84. } catch (HttpException $e) {
  85. Http::sendHeaderByCode($e->getCode());
  86. die($e->getMessage());
  87. } catch (Exception $e) {
  88. die("Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
  89. }
  90. }
  91. public function downloadTestAction() {
  92. try {
  93. $filePath = FileStorage::getRootStoragePath() . '/test-upload-data.txt';
  94. if (!file_exists($filePath)) throw new Exception("file not exists!");
  95. header('Content-Description: File Transfer');
  96. header('Content-Type: application/octet-stream');
  97. header('Content-Disposition: attachment; filename="'.basename($filePath).'"');
  98. header('Expires: 0');
  99. header('Cache-Control: must-revalidate');
  100. header('Pragma: public');
  101. header('Content-Length: ' . filesize($filePath));
  102. readfile($filePath);
  103. exit;
  104. } catch (Exception $e) {
  105. echo "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage();
  106. }
  107. }
  108. public function uploadFromFormTestAction() {
  109. try {
  110. // $fileContent = Request::getRequestBody();
  111. DBG::_(true, true, '_POST', $_POST, __CLASS__, __FUNCTION__, __LINE__);
  112. // $filePath = FileStorage::getRootStoragePath() . '/test-upload-data.txt';
  113. // $fp = fopen($filePath, 'w');
  114. // fwrite($fp, $fileContent);
  115. // fclose($fp);
  116. // echo 'file uploaded?';
  117. } catch (Exception $e) {
  118. echo "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage();
  119. }
  120. }
  121. public function uploadFormTestAction() {
  122. UI::gora();
  123. UI::menu();
  124. try {
  125. // multiple: <input type="file" id="file_input" multiple="multiple" />
  126. // only images: <input type="file" id="file_input" multiple="multiple" accept="image/*" />
  127. ?>
  128. <div class="container">
  129. <form>
  130. <input type="file" id="file_input" style="display:block; width:100%; height:200px; background-color:silver; text-align:center">
  131. </form>
  132. <button class="btn btn-primary" id="upload_file_as_stream_btn">upload as stream</button>
  133. <button class="btn btn-success" id="upload_file_as_binary_btn">upload as binary</button>
  134. <button class="btn btn-default" id="upload_file_as_form_btn">upload as form</button>
  135. <a class="btn btn-default" href="index.php?_route=FileStorage&_task=downloadTest" target="_blank">download</a>
  136. <blockquote>
  137. <p>root storage path: <code><?php echo FileStorage::getRootStoragePath(); ?></code></p>
  138. <p>table name: <code><?php echo FileStorage::getTableName(); ?></code></p>
  139. <p>IP: <code><?php echo Request::getUserIp(); ?></code></p>
  140. </blockquote>
  141. </div>
  142. <?php
  143. $sqlTblName = FileStorage::getTableName();
  144. $params = array();
  145. $params['caption'] = "Files in '{$sqlTblName}'";
  146. $params['rows'] = array_map(function($row) {
  147. $row['FILE_SIZE'] = V::humanFileSize($row['FILE_SIZE']);
  148. unset($row['FILE_HASH']);
  149. $row['rel_path'] = FileStorage::generateFilePathHashFromId($row['ID']);
  150. $downloadLink = "index.php?_route=FileStorage&_task=download&id={$row['ID']}";
  151. $row['download'] = '<a href="' . $downloadLink . '" target="_blank">download</a>';
  152. return $row;
  153. }, DB::getPDO()->fetchAll("
  154. select t.ID
  155. , t.FILE_HASH
  156. , t.FILE_LABEL
  157. , t.FILE_TYPE
  158. , t.FILE_MIME_TYPE
  159. , t.FILE_MTIME
  160. , t.FILE_SIZE
  161. , t.FILE_VERSION
  162. , t.A_STATUS
  163. , t.A_RECORD_CREATE_DATE as created
  164. , t.A_RECORD_CREATE_AUTHOR as author
  165. , t.A_RECORD_UPDATE_DATE as updated
  166. , t.A_RECORD_UPDATE_AUTHOR as editor
  167. , t.A_ADM_COMPANY as zapisDla
  168. , t.A_CLASSIFIED as odczytDla
  169. , INET_NTOA(t.A_USER_IP) as IP
  170. from `{$sqlTblName}` t
  171. order by ID DESC
  172. limit 100
  173. "));
  174. UI::table($params);
  175. ?>
  176. <script>
  177. document.getElementById('file_input').addEventListener('change', function() {
  178. for (var i = 0; i < this.files.length; i++){
  179. var file = this.files[i];
  180. // This code is only for demo ...
  181. console.group("File "+i);
  182. console.log("name : " + file.name);
  183. console.log("size : " + file.size);
  184. console.log("type : " + file.type);
  185. console.log("date : " + file.lastModified);
  186. console.groupEnd();
  187. }
  188. }, false);
  189. function uploadFileAsForm(file) {
  190. var serverUrl = '<?php echo Request::getPathUri() . "index.php?_route=FileStorage&_task=uploadFromFormTest"; ?>';
  191. var xhr = new XMLHttpRequest();
  192. var fd = new FormData();
  193. xhr.open("POST", serverUrl, true);
  194. xhr.onreadystatechange = function() {
  195. if (xhr.readyState == 4 && xhr.status == 200) {
  196. // Every thing ok, file uploaded
  197. console.log(xhr.responseText); // handle response.
  198. }
  199. };
  200. fd.append("upload_file", file);
  201. xhr.send(fd);
  202. }
  203. function uploadFileAsStream(file) {
  204. var serverUrl = '<?php echo Request::getPathUri() . "index.php?_route=FileStorage&_task=uploadStream"; ?>';
  205. var _dbg = true;
  206. // .set('Accept', 'application/json')
  207. superagent.post(serverUrl + '&name=' + file.name)
  208. .set('Content-Type', file.type)
  209. .send(file)
  210. .end(function(err, res) {
  211. if(_dbg)console.log('DBG: res:', res, 'res.body:', res.body);
  212. if (res.status != 200) {
  213. jQuery.notify("Wystąpił błąd: " + res.text, 'error')
  214. } else if (res.body && res.body.msg && res.body.type) {
  215. var notifyType = ('danger' == res.body.type) ? 'error' : res.body.type;
  216. jQuery.notify("Wgrano plik:" + JSON.stringify(res.body), notifyType)
  217. } else if (res.body && res.body.id && res.body.id > 0) {
  218. jQuery.notify("Wgrano plik:" + JSON.stringify(res.body), 'success')
  219. } else {
  220. jQuery.notify("Wystąpił błąd: " + JSON.stringify(res.body), 'error')
  221. }
  222. })
  223. }
  224. function uploadFileAsBinary(file) {
  225. var serverUrl = '<?php echo Request::getPathUri() . "index.php?_route=FileStorage&_task=upload"; ?>';
  226. var _dbg = true;
  227. // .set('Accept', 'application/json')
  228. superagent.post(serverUrl + '&name=' + file.name)
  229. .set('Content-Type', file.type)
  230. .send(file)
  231. .end(function(err, res) {
  232. if(_dbg)console.log('DBG: res:', res, 'res.body:', res.body);
  233. })
  234. return
  235. jQuery.ajax({
  236. type: "POST",
  237. beforeSend: function (request) {
  238. request.setRequestHeader("Content-Type", file.type);
  239. },
  240. url: serverUrl,
  241. data: file,
  242. processData: false,
  243. contentType: false,
  244. success: function (data) {
  245. console.log("File available at: ", data);
  246. },
  247. error: function (data) {
  248. var obj = jQuery.parseJSON(data);
  249. alert(obj.error);
  250. }
  251. })
  252. }
  253. jQuery('#upload_file_as_stream_btn').on('click', function() {
  254. var fileInput = document.getElementById('file_input')
  255. if (!fileInput) return false;// TODO: error msg
  256. if (!fileInput.files) return false;// TODO: error msg
  257. if (!fileInput.files.length) return false;// TODO: error msg
  258. var fileInfo = fileInput.files[0];
  259. console.log('fileInfo', fileInfo);
  260. uploadFileAsStream(fileInfo);
  261. });
  262. jQuery('#upload_file_as_binary_btn').on('click', function() {
  263. var fileInput = document.getElementById('file_input')
  264. if (!fileInput) return false;// TODO: error msg
  265. if (!fileInput.files) return false;// TODO: error msg
  266. if (!fileInput.files.length) return false;// TODO: error msg
  267. var fileInfo = fileInput.files[0];
  268. console.log('fileInfo', fileInfo);
  269. uploadFileAsBinary(fileInfo);
  270. });
  271. jQuery('#upload_file_as_form_btn').on('click', function() {
  272. var fileInput = document.getElementById('file_input')
  273. if (!fileInput) return false;// TODO: error msg
  274. if (!fileInput.files) return false;// TODO: error msg
  275. if (!fileInput.files.length) return false;// TODO: error msg
  276. var fileInfo = fileInput.files[0];
  277. console.log('fileInfo', fileInfo);
  278. uploadFileAsForm(fileInfo);
  279. });
  280. </script>
  281. <?php
  282. } catch (Exception $e) {
  283. UI::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
  284. }
  285. UI::dol();
  286. }
  287. public function generatePathTestAction() {
  288. try {
  289. $start = 0;
  290. $start = 446071;
  291. $limit = $start + 100;
  292. echo '<pre>';
  293. for ($i = $start; $i < $limit; $i++) {
  294. FileStorage::generateFilePathHashFromId($i);
  295. }
  296. echo '</pre>';
  297. } catch (Exception $e) {
  298. echo "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage();
  299. }
  300. }
  301. public function reinstallAction() {
  302. UI::gora();
  303. UI::menu();
  304. FileStorage::reinstall();
  305. UI::dol();
  306. }
  307. }