Resumable.php 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. <?php
  2. namespace Dilab;
  3. use Cake\Filesystem\File;
  4. use Cake\Filesystem\Folder;
  5. use Dilab\Network\Request;
  6. use Dilab\Network\Response;
  7. use Monolog\Logger;
  8. use Monolog\Handler\StreamHandler;
  9. class Resumable
  10. {
  11. public $debug = false;
  12. public $tempFolder = 'tmp';
  13. public $uploadFolder = 'test/files/uploads';
  14. // for testing
  15. public $deleteTmpFolder = true;
  16. protected $request;
  17. protected $response;
  18. protected $params;
  19. protected $chunkFile;
  20. protected $log;
  21. protected $filename;
  22. protected $filepath;
  23. protected $extension;
  24. protected $originalFilename;
  25. protected $isUploadComplete = false;
  26. protected $resumableOption = [
  27. 'identifier' => 'identifier',
  28. 'filename' => 'filename',
  29. 'chunkNumber' => 'chunkNumber',
  30. 'chunkSize' => 'chunkSize',
  31. 'totalSize' => 'totalSize'
  32. ];
  33. const WITHOUT_EXTENSION = true;
  34. public function __construct(Request $request, Response $response)
  35. {
  36. $this->request = $request;
  37. $this->response = $response;
  38. $this->log = new Logger('debug');
  39. $this->log->pushHandler(new StreamHandler('debug.log', Logger::DEBUG));
  40. $this->preProcess();
  41. }
  42. public function setResumableOption(array $resumableOption)
  43. {
  44. $this->resumableOption = array_merge($this->resumableOption, $resumableOption);
  45. }
  46. // sets original filename and extenstion, blah blah
  47. public function preProcess()
  48. {
  49. if (!empty($this->resumableParams())) {
  50. if (!empty($this->request->file())) {
  51. $this->extension = $this->findExtension($this->resumableParam('filename'));
  52. $this->originalFilename = $this->resumableParam('filename');
  53. }
  54. }
  55. }
  56. public function process()
  57. {
  58. if (!empty($this->resumableParams())) {
  59. if (!empty($this->request->file())) {
  60. $this->handleChunk();
  61. } else {
  62. $this->handleTestChunk();
  63. }
  64. }
  65. }
  66. /**
  67. * Get isUploadComplete
  68. *
  69. * @return boolean
  70. */
  71. public function isUploadComplete()
  72. {
  73. return $this->isUploadComplete;
  74. }
  75. /**
  76. * Set final filename.
  77. *
  78. * @param string Final filename
  79. */
  80. public function setFilename($filename)
  81. {
  82. $this->filename = $filename;
  83. return $this;
  84. }
  85. /**
  86. * Get final filename.
  87. *
  88. * @return string Final filename
  89. */
  90. public function getFilename()
  91. {
  92. return $this->filename;
  93. }
  94. /**
  95. * Get final filename.
  96. *
  97. * @return string Final filename
  98. */
  99. public function getOriginalFilename($withoutExtension = false)
  100. {
  101. if ($withoutExtension === static::WITHOUT_EXTENSION) {
  102. return $this->removeExtension($this->originalFilename);
  103. }
  104. return $this->originalFilename;
  105. }
  106. /**
  107. * Get final filapath.
  108. *
  109. * @return string Final filename
  110. */
  111. public function getFilepath()
  112. {
  113. return $this->filepath;
  114. }
  115. /**
  116. * Get final extension.
  117. *
  118. * @return string Final extension name
  119. */
  120. public function getExtension()
  121. {
  122. return $this->extension;
  123. }
  124. /**
  125. * Makes sure the orginal extension never gets overriden by user defined filename.
  126. *
  127. * @param string User defined filename
  128. * @param string Original filename
  129. * @return string Filename that always has an extension from the original file
  130. */
  131. private function createSafeFilename($filename, $originalFilename)
  132. {
  133. $filename = $this->removeExtension($filename);
  134. $extension = $this->findExtension($originalFilename);
  135. return sprintf('%s.%s', $filename, $extension);
  136. }
  137. public function handleTestChunk()
  138. {
  139. $identifier = $this->resumableParam($this->resumableOption['identifier']);
  140. $filename = $this->resumableParam($this->resumableOption['filename']);
  141. $chunkNumber = $this->resumableParam($this->resumableOption['chunkNumber']);
  142. if (!$this->isChunkUploaded($identifier, $filename, $chunkNumber)) {
  143. return $this->response->header(404);
  144. }
  145. return $this->response->header(200);
  146. }
  147. public function handleChunk()
  148. {
  149. $file = $this->request->file();
  150. $identifier = $this->resumableParam($this->resumableOption['identifier']);
  151. $filename = $this->resumableParam($this->resumableOption['filename']);
  152. $chunkNumber = $this->resumableParam($this->resumableOption['chunkNumber']);
  153. $chunkSize = $this->resumableParam($this->resumableOption['chunkSize']);
  154. $totalSize = $this->resumableParam($this->resumableOption['totalSize']);
  155. if (!$this->isChunkUploaded($identifier, $filename, $chunkNumber)) {
  156. $chunkFile = $this->tmpChunkDir($identifier) . DIRECTORY_SEPARATOR . $this->tmpChunkFilename($filename, $chunkNumber);
  157. $this->moveUploadedFile($file['tmp_name'], $chunkFile);
  158. }
  159. if ($this->isFileUploadComplete($filename, $identifier, $chunkSize, $totalSize)) {
  160. $this->isUploadComplete = true;
  161. $this->createFileAndDeleteTmp($identifier, $filename);
  162. }
  163. return $this->response->header(200);
  164. }
  165. /**
  166. * Create the final file from chunks
  167. */
  168. private function createFileAndDeleteTmp($identifier, $filename)
  169. {
  170. $tmpFolder = new Folder($this->tmpChunkDir($identifier));
  171. $chunkFiles = $tmpFolder->read(true, true, true)[1];
  172. // if the user has set a custom filename
  173. if (null !== $this->filename) {
  174. $finalFilename = $this->createSafeFilename($this->filename, $filename);
  175. } else {
  176. $finalFilename = $filename;
  177. }
  178. // replace filename reference by the final file
  179. $this->filepath = $this->uploadFolder . DIRECTORY_SEPARATOR . $finalFilename;
  180. $this->extension = $this->findExtension($this->filepath);
  181. if ($this->createFileFromChunks($chunkFiles, $this->filepath) && $this->deleteTmpFolder) {
  182. $tmpFolder->delete();
  183. $this->uploadComplete = true;
  184. }
  185. }
  186. private function resumableParam($shortName)
  187. {
  188. $resumableParams = $this->resumableParams();
  189. if (!isset($resumableParams['resumable' . ucfirst($shortName)])) {
  190. return null;
  191. }
  192. return $resumableParams['resumable' . ucfirst($shortName)];
  193. }
  194. public function resumableParams()
  195. {
  196. if ($this->request->is('get')) {
  197. return $this->request->data('get');
  198. }
  199. if ($this->request->is('post')) {
  200. return $this->request->data('post');
  201. }
  202. }
  203. public function isFileUploadComplete($filename, $identifier, $chunkSize, $totalSize)
  204. {
  205. if ($chunkSize <= 0) {
  206. return false;
  207. }
  208. $numOfChunks = intval($totalSize / $chunkSize) + ($totalSize % $chunkSize == 0 ? 0 : 1);
  209. for ($i = 1; $i < $numOfChunks; $i++) {
  210. if (!$this->isChunkUploaded($identifier, $filename, $i)) {
  211. return false;
  212. }
  213. }
  214. return true;
  215. }
  216. public function isChunkUploaded($identifier, $filename, $chunkNumber)
  217. {
  218. $file = new File($this->tmpChunkDir($identifier) . DIRECTORY_SEPARATOR . $this->tmpChunkFilename($filename, $chunkNumber));
  219. return $file->exists();
  220. }
  221. public function tmpChunkDir($identifier)
  222. {
  223. $tmpChunkDir = $this->tempFolder . DIRECTORY_SEPARATOR . $identifier;
  224. if (!file_exists($tmpChunkDir)) {
  225. mkdir($tmpChunkDir);
  226. }
  227. return $tmpChunkDir;
  228. }
  229. public function tmpChunkFilename($filename, $chunkNumber)
  230. {
  231. return $filename . '.part' . $chunkNumber;
  232. }
  233. public function createFileFromChunks($chunkFiles, $destFile)
  234. {
  235. $this->log('Beginning of create files from chunks');
  236. natsort($chunkFiles);
  237. $destFile = new File($destFile, true);
  238. foreach ($chunkFiles as $chunkFile) {
  239. $file = new File($chunkFile);
  240. $destFile->append($file->read());
  241. $this->log('Append ', ['chunk file' => $chunkFile]);
  242. }
  243. $this->log('End of create files from chunks');
  244. return $destFile->exists();
  245. }
  246. public function moveUploadedFile($file, $destFile)
  247. {
  248. $file = new File($file);
  249. if ($file->exists()) {
  250. return $file->copy($destFile);
  251. }
  252. return false;
  253. }
  254. public function setRequest($request)
  255. {
  256. $this->request = $request;
  257. }
  258. public function setResponse($response)
  259. {
  260. $this->response = $response;
  261. }
  262. private function log($msg, $ctx = array())
  263. {
  264. if ($this->debug) {
  265. $this->log->addDebug($msg, $ctx);
  266. }
  267. }
  268. private function findExtension($filename)
  269. {
  270. $parts = explode('.', basename($filename));
  271. return end($parts);
  272. }
  273. private function removeExtension($filename)
  274. {
  275. $parts = explode('.', basename($filename));
  276. $ext = end($parts); // get extension
  277. // remove extension from filename if any
  278. return str_replace(sprintf('.%s', $ext), '', $filename);
  279. }
  280. }