class-qdr-tss-file-manager.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. <?php
  2. /**
  3. * File operations for the plugin.
  4. *
  5. * This class handles all file operations, including creating directories,
  6. * uploading files, chunked uploads, and deleting files.
  7. *
  8. * @package QDR_Temporary_Shared_Storage
  9. * @since 1.0.0
  10. */
  11. class QDR_TSS_File_Manager {
  12. /**
  13. * The single instance of the class.
  14. *
  15. * @var QDR_TSS_File_Manager
  16. * @since 1.0.0
  17. */
  18. protected static $_instance = null;
  19. /**
  20. * Main QDR_TSS_File_Manager Instance.
  21. *
  22. * Ensures only one instance of QDR_TSS_File_Manager is loaded or can be loaded.
  23. *
  24. * @since 1.0.0
  25. * @static
  26. * @return QDR_TSS_File_Manager - Main instance.
  27. */
  28. public static function instance() {
  29. if (is_null(self::$_instance)) {
  30. self::$_instance = new self();
  31. }
  32. return self::$_instance;
  33. }
  34. /**
  35. * QDR_TSS_File_Manager Constructor.
  36. */
  37. public function __construct() {
  38. // Initialize file system if needed
  39. $this->init_file_system();
  40. }
  41. /**
  42. * Generate a unique file ID.
  43. *
  44. * @since 1.0.0
  45. * @return string A unique alphanumeric hash
  46. */
  47. public function generate_fileid() {
  48. // Current timestamp + random string
  49. $timestamp = time();
  50. $random = bin2hex(random_bytes(10)); // 20 chars
  51. $unique = uniqid('', true); // ~23 chars
  52. // Create hash from combined values
  53. $hash = md5($timestamp . $random . $unique);
  54. // Return first 40 chars of the hash + timestamp hex (should be under 50 chars total)
  55. return substr($hash, 0, 40) . dechex($timestamp);
  56. }
  57. /**
  58. * Initialize file system directories.
  59. *
  60. * @since 1.0.0
  61. * @return bool True on success, false on failure.
  62. */
  63. public function init_file_system() {
  64. // Create base upload directory if it doesn't exist
  65. if (!file_exists(QDR_TSS_UPLOADS_DIR)) {
  66. if (!wp_mkdir_p(QDR_TSS_UPLOADS_DIR)) {
  67. return false;
  68. }
  69. // Create .htaccess file to protect direct access
  70. $htaccess_content = "# Disable directory browsing\nOptions -Indexes\n\n# Deny direct access to all files\n<FilesMatch \".*\">\nOrder Allow,Deny\nDeny from all\n</FilesMatch>";
  71. file_put_contents(QDR_TSS_UPLOADS_DIR . '.htaccess', $htaccess_content);
  72. }
  73. // Create temporary directory for chunked uploads
  74. if (!file_exists(QDR_TSS_UPLOADS_DIR . 'tmp/')) {
  75. if (!wp_mkdir_p(QDR_TSS_UPLOADS_DIR . 'tmp/')) {
  76. return false;
  77. }
  78. }
  79. return true;
  80. }
  81. /**
  82. * Create a dated directory for storing files.
  83. *
  84. * @since 1.0.0
  85. * @param string $date Optional. Date string in Y-m-d format. Default is current date.
  86. * @return string|false Path to the directory or false on failure.
  87. */
  88. public function create_dated_directory($date = '') {
  89. if (empty($date)) {
  90. $date = date('Y/m/d');
  91. }
  92. $directory = QDR_TSS_UPLOADS_DIR . $date;
  93. if (!file_exists($directory)) {
  94. if (!wp_mkdir_p($directory)) {
  95. return false;
  96. }
  97. }
  98. return $directory;
  99. }
  100. /**
  101. * Initialize a chunked upload.
  102. *
  103. * @since 1.0.0
  104. * @return string|false The upload ID or false on failure.
  105. */
  106. public function init_chunked_upload() {
  107. $upload_id = uniqid();
  108. $upload_dir = QDR_TSS_UPLOADS_DIR . 'tmp/' . $upload_id;
  109. if (!wp_mkdir_p($upload_dir)) {
  110. return false;
  111. }
  112. return $upload_id;
  113. }
  114. /**
  115. * Store a chunk of a file.
  116. *
  117. * @since 1.0.0
  118. * @param string $upload_id The upload ID.
  119. * @param int $chunk_index The chunk index.
  120. * @param array $file The chunk file data from $_FILES.
  121. * @return bool True on success, false on failure.
  122. */
  123. public function store_chunk($upload_id, $chunk_index, $file) {
  124. $upload_dir = QDR_TSS_UPLOADS_DIR . 'tmp/' . $upload_id;
  125. // Check if the upload directory exists
  126. if (!file_exists($upload_dir)) {
  127. return false;
  128. }
  129. // Check if file was uploaded successfully
  130. if (!isset($file['tmp_name']) || !is_uploaded_file($file['tmp_name'])) {
  131. return false;
  132. }
  133. // Move uploaded chunk to temporary directory
  134. $chunk_path = $upload_dir . '/' . $chunk_index;
  135. return move_uploaded_file($file['tmp_name'], $chunk_path);
  136. }
  137. /**
  138. * Check if all chunks are present.
  139. *
  140. * @since 1.0.0
  141. * @param string $upload_id The upload ID.
  142. * @param int $total_chunks The total number of chunks.
  143. * @return bool True if all chunks are present, false otherwise.
  144. */
  145. public function check_all_chunks($upload_id, $total_chunks) {
  146. $upload_dir = QDR_TSS_UPLOADS_DIR . 'tmp/' . $upload_id;
  147. // Check if the upload directory exists
  148. if (!file_exists($upload_dir)) {
  149. return false;
  150. }
  151. // Check that all chunks are present
  152. for ($i = 0; $i < $total_chunks; $i++) {
  153. if (!file_exists($upload_dir . '/' . $i)) {
  154. return false;
  155. }
  156. }
  157. return true;
  158. }
  159. /**
  160. * Finalize a chunked upload.
  161. *
  162. * @since 1.0.0
  163. * @param string $upload_id The upload ID.
  164. * @param int $total_chunks The total number of chunks.
  165. * @param string $original_filename The original file name.
  166. * @return array|false {
  167. * @type string $file_path The path to the combined file.
  168. * @type int $file_size The size of the combined file.
  169. * } or false on failure.
  170. */
  171. public function finalize_chunked_upload($upload_id, $total_chunks, $original_filename) {
  172. $upload_dir = QDR_TSS_UPLOADS_DIR . 'tmp/' . $upload_id;
  173. // Check if the upload directory exists
  174. if (!file_exists($upload_dir)) {
  175. return false;
  176. }
  177. // Check that all chunks are present
  178. if (!$this->check_all_chunks($upload_id, $total_chunks)) {
  179. return false;
  180. }
  181. // Create final file directory
  182. $file_dir = $this->create_dated_directory();
  183. if (!$file_dir) {
  184. return false;
  185. }
  186. // Sanitize file name
  187. $original_filename = sanitize_file_name($original_filename);
  188. $file_name = md5($original_filename . time()) . '-' . $original_filename;
  189. $file_path = $file_dir . '/' . $file_name;
  190. // Combine chunks
  191. if (!$this->combine_chunks($upload_dir, $total_chunks, $file_path)) {
  192. return false;
  193. }
  194. // Clean up temporary directory
  195. $this->cleanup_chunks($upload_dir);
  196. // Get file size
  197. $file_size = filesize($file_path);
  198. return array(
  199. 'file_path' => str_replace(QDR_TSS_UPLOADS_DIR, '', $file_path),
  200. 'file_size' => $file_size
  201. );
  202. }
  203. /**
  204. * Combine chunks into a single file.
  205. *
  206. * @since 1.0.0
  207. * @access private
  208. * @param string $upload_dir The upload directory.
  209. * @param int $total_chunks The total number of chunks.
  210. * @param string $file_path The path to the combined file.
  211. * @return bool True on success, false on failure.
  212. */
  213. private function combine_chunks($upload_dir, $total_chunks, $file_path) {
  214. // Create final file
  215. $final_file = fopen($file_path, 'wb');
  216. if (!$final_file) {
  217. return false;
  218. }
  219. // Combine chunks
  220. for ($i = 0; $i < $total_chunks; $i++) {
  221. $chunk_path = $upload_dir . '/' . $i;
  222. $chunk = fopen($chunk_path, 'rb');
  223. if (!$chunk) {
  224. fclose($final_file);
  225. unlink($file_path);
  226. return false;
  227. }
  228. stream_copy_to_stream($chunk, $final_file);
  229. fclose($chunk);
  230. }
  231. fclose($final_file);
  232. return true;
  233. }
  234. /**
  235. * Clean up chunks after successful upload.
  236. *
  237. * @since 1.0.0
  238. * @access private
  239. * @param string $upload_dir The upload directory.
  240. * @return bool True on success, false on failure.
  241. */
  242. private function cleanup_chunks($upload_dir) {
  243. // Delete all chunk files
  244. $files = glob($upload_dir . '/*');
  245. foreach ($files as $file) {
  246. if (is_file($file)) {
  247. unlink($file);
  248. }
  249. }
  250. // Delete upload directory
  251. return rmdir($upload_dir);
  252. }
  253. /**
  254. * Delete a file.
  255. *
  256. * @since 1.0.0
  257. * @param string $file_path The file path relative to the upload directory.
  258. * @return bool True on success, false on failure.
  259. */
  260. public function delete_file($file_path) {
  261. $full_path = QDR_TSS_UPLOADS_DIR . $file_path;
  262. if (file_exists($full_path)) {
  263. return unlink($full_path);
  264. }
  265. return false;
  266. }
  267. /**
  268. * Get file size.
  269. *
  270. * @since 1.0.0
  271. * @param string $file_path The file path relative to the upload directory.
  272. * @return int|false The file size in bytes or false if file doesn't exist.
  273. */
  274. public function get_file_size($file_path) {
  275. $full_path = QDR_TSS_UPLOADS_DIR . $file_path;
  276. if (file_exists($full_path)) {
  277. return filesize($full_path);
  278. }
  279. return false;
  280. }
  281. /**
  282. * Clean up empty directories.
  283. *
  284. * @since 1.0.0
  285. * @param string $directory The directory to clean.
  286. * @return void
  287. */
  288. public function cleanup_empty_directories($directory = '') {
  289. if (empty($directory)) {
  290. $directory = QDR_TSS_UPLOADS_DIR;
  291. }
  292. // Skip special directories
  293. if (basename($directory) === 'tmp') {
  294. return;
  295. }
  296. // Skip if not a directory
  297. if (!is_dir($directory)) {
  298. return;
  299. }
  300. // Get all files and directories
  301. $files = scandir($directory);
  302. $files = array_diff($files, array('.', '..', '.htaccess'));
  303. // Process subdirectories first
  304. foreach ($files as $file) {
  305. $path = $directory . '/' . $file;
  306. if (is_dir($path)) {
  307. $this->cleanup_empty_directories($path);
  308. }
  309. }
  310. // Check if directory is empty now
  311. $remaining_files = scandir($directory);
  312. $remaining_files = array_diff($remaining_files, array('.', '..', '.htaccess'));
  313. // Remove directory if empty
  314. if (empty($remaining_files)) {
  315. @rmdir($directory);
  316. }
  317. }
  318. }