ValidateLoadArchivesController.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  1. <?php
  2. namespace App\Http\Controllers;
  3. use Illuminate\Http\Request;
  4. use Illuminate\Support\Facades\Validator;
  5. use Illuminate\Support\Facades\DB;
  6. use Illuminate\Support\Facades\Log;
  7. use PhpOffice\PhpSpreadsheet\IOFactory;
  8. use ZipArchive;
  9. /**
  10. * Controller for validating Excel and ZIP files for equipment documentation loading
  11. * Validates Excel headers structure and compares file listings with ZIP contents
  12. */
  13. class ValidateLoadArchivesController extends Controller
  14. {
  15. private $responseController;
  16. private $encryptionController;
  17. private $documentManagementController;
  18. private $functionsController;
  19. // Expected headers in row 7 of Excel file with their corresponding column letters
  20. private $expectedHeaders = [
  21. ['letter' => 'D', 'category' => 'CÓDIGO DE EQUIPO'],
  22. ['letter' => 'H', 'category' => 'FICHA DE SEGURIDAD DE PRODUCTOS QUÍMICOS'],
  23. ['letter' => 'J', 'category' => 'FICHA TÉCNICA'],
  24. ['letter' => 'L', 'category' => 'FOTOGRAFÍAS - DIAGRAMAS'],
  25. ['letter' => 'N', 'category' => 'DATOS DEL PROVEEDOR'],
  26. ['letter' => 'P', 'category' => 'MANUALES DE OPERACIÓN'],
  27. ['letter' => 'R', 'category' => 'MANUALES DE MANTENIMIENTO PREVENTIVO'],
  28. ['letter' => 'T', 'category' => 'MANUALES DE MANTENIMIENTO CORRECTIVO'],
  29. ['letter' => 'V', 'category' => 'DOCUMENTOS ADICIONALES']
  30. ];
  31. // Mapping of file extensions to their types for validation
  32. private $extensionTypes = [
  33. // Archivos de almacenamiento
  34. 'zip' => 'STORAGE', 'rar' => 'STORAGE', 'tar' => 'STORAGE', '7z' => 'STORAGE',
  35. // Formatos de audio
  36. 'mp3' => 'AUDIO', 'mpeg' => 'AUDIO', 'wav' => 'AUDIO', 'ogg' => 'AUDIO', 'opus' => 'AUDIO',
  37. // Archivos de imagen
  38. 'jpeg' => 'IMG', 'jpg' => 'IMG', 'png' => 'IMG', 'gif' => 'IMG', 'bmp' => 'IMG', 'tiff' => 'IMG', 'svg' => 'IMG',
  39. // Archivos de texto
  40. 'txt' => 'TEXT',
  41. // Archivos de video
  42. 'webm' => 'VIDEO', 'mpeg4' => 'VIDEO', 'mp4' => 'VIDEO', '3gpp' => 'VIDEO', 'mov' => 'VIDEO', 'avi' => 'VIDEO', 'wmv' => 'VIDEO', 'flv' => 'VIDEO',
  43. // Planos de Auto CAD
  44. 'dwg' => 'CAD', 'dxf' => 'CAD',
  45. // Modelos de 3D Studio
  46. '3ds' => '3D',
  47. // Dibujos de Illustrator
  48. 'ai' => 'ILLUSTRATOR',
  49. // Imágenes de Photoshop
  50. 'psd' => 'PHOTOSHOP',
  51. // Formato de documento portátil
  52. 'pdf' => 'PDF',
  53. // Hoja de cálculo en Excel
  54. 'xls' => 'EXCEL', 'xlsx' => 'EXCEL',
  55. // Presentaciones de PowerPoint
  56. 'ppt' => 'POWERPOINT', 'pptx' => 'POWERPOINT',
  57. // Documentos de texto de Word
  58. 'doc' => 'WORD', 'docx' => 'WORD',
  59. // Dibujos de Visio
  60. 'vsd' => 'VISIO', 'vsdx' => 'VISIO'
  61. ];
  62. public function __construct()
  63. {
  64. $this->responseController = new ResponseController();
  65. $this->encryptionController = new EncryptionController();
  66. $this->documentManagementController = new DocumentManagementController();
  67. $this->functionsController = new FunctionsController();
  68. }
  69. /**
  70. * Main validation endpoint that validates both Excel and ZIP files
  71. * Checks Excel headers, ZIP integrity, file listings, and compares them
  72. */
  73. public function validateFiles(Request $request)
  74. {
  75. ini_set('memory_limit', '-1');
  76. Log::info('ValidateFiles: Iniciando validación de archivos');
  77. // Validate request inputs
  78. $validator = Validator::make($request->all(), [
  79. 'id_user' => 'required|string',
  80. 'linea' => 'required|integer',
  81. 'excel_file' => 'required|file|mimes:xlsx,xls',
  82. 'zip_file' => 'required|file|mimes:zip'
  83. ]);
  84. if ($validator->fails()) {
  85. return $this->responseController->makeResponse(
  86. true,
  87. 'Se encontraron uno o más errores.',
  88. $this->responseController->makeErrors($validator->errors()->messages()),
  89. 400
  90. );
  91. }
  92. $idUser = '0000000001';
  93. // $idUser = $this->encryptionController->decrypt($request->input('id_user'));
  94. // if(!$idUser){
  95. // return $this->responseController->makeResponse(true, "El id del usuario que realizó la petición no fue encriptado correctamente", [], 400);
  96. // }
  97. // Validate Excel file headers structure
  98. $excelValidation = $this->validateExcelHeaders($request->file('excel_file'));
  99. if ($excelValidation['error']) {
  100. return $this->responseController->makeResponse(true, $excelValidation['message'], [], 400);
  101. }
  102. Log::info('ValidateFiles: Headers Excel validados correctamente');
  103. // Validate ZIP file integrity
  104. $zipValidation = $this->validateZipFile($request->file('zip_file'));
  105. if ($zipValidation['error']) {
  106. return $this->responseController->makeResponse(true, $zipValidation['message'], [], 400);
  107. }
  108. Log::info('ValidateFiles: Archivo ZIP validado correctamente');
  109. // Extract and validate file listings from Excel
  110. $filesValidation = $this->extractAndValidateFiles($request->file('excel_file'));
  111. if ($filesValidation['error']) {
  112. return $this->responseController->makeResponse(true, $filesValidation['message'], [], 400);
  113. }
  114. Log::info('ValidateFiles: Archivos extraídos del Excel', ['count' => count($filesValidation['files'])]);
  115. // Compare Excel file listings with ZIP contents
  116. $comparison = $this->compareExcelWithZip($filesValidation['files'], $request->file('zip_file'));
  117. // Check for file size validation errors
  118. if (isset($comparison['error'])) {
  119. return $this->responseController->makeResponse(true, $comparison['error'], [], 400);
  120. }
  121. Log::info('ValidateFiles: Comparación Excel-ZIP completada', ['valid' => $comparison['valid']]);
  122. // Upload temp files if validation is successful
  123. if ($comparison['valid']) {
  124. $tempFiles = $this->uploadTempFiles($request);
  125. if ($tempFiles['error']) {
  126. Log::error('ValidateFiles: Error subiendo archivos temporales', ['message' => $tempFiles['message']]);
  127. return $this->responseController->makeResponse(true, $tempFiles['message'], [], 400);
  128. }
  129. Log::info('ValidateFiles: Archivos temporales subidos correctamente');
  130. // Extract and save individual files as temp
  131. $individualTempFiles = $this->extractAndSaveIndividualFilesAsTemp($request->file('zip_file'), $request->input('linea'), $idUser);
  132. if ($individualTempFiles === false) {
  133. Log::error('ValidateFiles: Error procesando archivos individuales');
  134. return $this->responseController->makeResponse(true, 'Error procesando archivos individuales', [], 400);
  135. }
  136. Log::info('ValidateFiles: Archivos individuales procesados', ['count' => count($individualTempFiles)]);
  137. $comparison['temp_files'] = $tempFiles['files'];
  138. $comparison['individual_temp_files'] = $individualTempFiles;
  139. }
  140. Log::info('ValidateFiles: Validación completada exitosamente');
  141. return $this->responseController->makeResponse(false, 'Validación completada.', $comparison);
  142. }
  143. /**
  144. * Validates that Excel file has the correct headers in row 7
  145. * Each column must match the expected category name exactly
  146. */
  147. private function validateExcelHeaders($file)
  148. {
  149. try {
  150. $spreadsheet = IOFactory::load($file->getPathname());
  151. $worksheet = $spreadsheet->getActiveSheet();
  152. // Check each expected header in row 7
  153. foreach ($this->expectedHeaders as $header) {
  154. $cellValue = $worksheet->getCell($header['letter'] . '7')->getValue();
  155. if (trim($cellValue) !== $header['category']) {
  156. return [
  157. 'error' => true,
  158. 'message' => "El encabezado en la columna {$header['letter']} no coincide. Se esperaba: '{$header['category']}', se encontró: '{$cellValue}'"
  159. ];
  160. }
  161. }
  162. Log::info('ValidateExcelHeaders: Todos los headers validados correctamente');
  163. return ['error' => false];
  164. } catch (\Exception $e) {
  165. return ['error' => true, 'message' => 'Error al procesar el archivo Excel: ' . $e->getMessage()];
  166. }
  167. }
  168. /**
  169. * Validates ZIP file integrity and ensures it's not empty
  170. */
  171. private function validateZipFile($file)
  172. {
  173. $zip = new ZipArchive();
  174. $result = $zip->open($file->getPathname());
  175. if ($result !== TRUE) {
  176. return ['error' => true, 'message' => 'No se pudo abrir el archivo ZIP.'];
  177. }
  178. if ($zip->numFiles === 0) {
  179. $zip->close();
  180. return ['error' => true, 'message' => 'El archivo ZIP está vacío.'];
  181. }
  182. Log::info('ValidateZipFile: ZIP válido', ['num_files' => $zip->numFiles]);
  183. $zip->close();
  184. return ['error' => false];
  185. }
  186. /**
  187. * Extracts file listings from Excel starting from row 8
  188. * Validates file extensions and creates structured file list
  189. * Only processes rows with equipment code (column D)
  190. */
  191. private function extractAndValidateFiles($file)
  192. {
  193. try {
  194. $spreadsheet = IOFactory::load($file->getPathname());
  195. $worksheet = $spreadsheet->getActiveSheet();
  196. $highestRow = $worksheet->getHighestRow();
  197. $files = [];
  198. Log::info('ExtractAndValidateFiles: Iniciando extracción', ['total_rows' => $highestRow]);
  199. // Process each row starting from row 8 (data rows)
  200. for ($row = 8; $row <= $highestRow; $row++) {
  201. $equipmentCode = trim($worksheet->getCell('D' . $row)->getValue());
  202. if (empty($equipmentCode)) continue; // Skip rows without equipment code
  203. $hasFiles = false;
  204. $rowFiles = [];
  205. // Check each file category column (excluding equipment code column D)
  206. foreach ($this->expectedHeaders as $header) {
  207. if ($header['letter'] === 'D') continue;
  208. $cellValue = trim($worksheet->getCell($header['letter'] . $row)->getValue());
  209. if (empty($cellValue)) continue;
  210. // Handle multiple files separated by commas
  211. $fileNames = explode(',', $cellValue);
  212. foreach ($fileNames as $fileName) {
  213. $fileName = trim($fileName);
  214. if (empty($fileName)) continue;
  215. // Validate file extension
  216. $extension = $file->extension();
  217. if (!isset($this->extensionTypes[$extension])) {
  218. return [
  219. 'error' => true,
  220. 'message' => "Extensión inválida '{$extension}' en archivo '{$fileName}' para equipo '{$equipmentCode}'"
  221. ];
  222. }
  223. $rowFiles[] = [
  224. 'equipment_code' => $equipmentCode,
  225. 'file_name' => $fileName,
  226. 'type' => $this->getFileType($extension)
  227. ];
  228. $hasFiles = true;
  229. }
  230. }
  231. if ($hasFiles) {
  232. $files = array_merge($files, $rowFiles);
  233. }
  234. }
  235. Log::info('ExtractAndValidateFiles: Extracción completada', ['files_found' => count($files)]);
  236. return ['error' => false, 'files' => $files];
  237. } catch (\Exception $e) {
  238. Log::error('ExtractAndValidateFiles: Excepción', ['error' => $e->getMessage()]);
  239. return ['error' => true, 'message' => 'Error al extraer archivos del Excel: ' . $e->getMessage()];
  240. }
  241. }
  242. /**
  243. * Compares file listings from Excel with actual files in ZIP
  244. * Returns validation status and lists of missing/extra files
  245. */
  246. private function compareExcelWithZip($excelFiles, $zipFile)
  247. {
  248. $zip = new ZipArchive();
  249. $zip->open($zipFile->getPathname());
  250. Log::info('CompareExcelWithZip: Iniciando comparación');
  251. // Extract all file names and sizes from ZIP
  252. $zipFiles = [];
  253. $zipFileSizes = [];
  254. for ($i = 0; $i < $zip->numFiles; $i++) {
  255. $fullPath = $zip->getNameIndex($i);
  256. // Skip directories (entries ending with /)
  257. if (substr($fullPath, -1) === '/') {
  258. continue;
  259. }
  260. // Extract filename and size
  261. $fileName = basename($fullPath);
  262. if (!empty($fileName)) {
  263. $zipFiles[] = $fileName;
  264. $zipFileSizes[$fileName] = $zip->statIndex($i)['size'];
  265. }
  266. }
  267. $zip->close();
  268. // Validate file sizes using FunctionsController
  269. foreach ($zipFileSizes as $fileName => $size) {
  270. $extension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
  271. if (!$this->functionsController->checkFileSize($extension, $size)) {
  272. $sizeMB = round($size / (1024 * 1024), 2);
  273. return [
  274. 'valid' => false,
  275. 'error' => "El archivo '{$fileName}' excede el límite de tamaño. Tamaño: {$sizeMB}MB"
  276. ];
  277. }
  278. }
  279. // Get file names from Excel listings
  280. $excelFileNames = array_column($excelFiles, 'file_name');
  281. // Find discrepancies between Excel and ZIP
  282. $missingInZip = array_diff($excelFileNames, $zipFiles);
  283. $extraInZip = array_diff($zipFiles, $excelFileNames);
  284. $isValid = empty($missingInZip) && empty($extraInZip);
  285. Log::info('CompareExcelWithZip: Comparación completada', [
  286. 'valid' => $isValid,
  287. 'missing_count' => count($missingInZip),
  288. 'extra_count' => count($extraInZip)
  289. ]);
  290. return [
  291. 'valid' => $isValid,
  292. 'missing_in_zip' => array_values($missingInZip),
  293. 'extra_in_zip' => array_values($extraInZip)
  294. ];
  295. }
  296. /**
  297. * Process Functions start here
  298. */
  299. /**
  300. * Process endpoint that moves temp files to final storage
  301. */
  302. public function processLoadArchives(Request $request)
  303. {
  304. $validator = Validator::make($request->all(), [
  305. 'id_user' => 'required|string',
  306. 'linea' => 'required|integer',
  307. 'temp_files' => 'required|array',
  308. 'temp_files.excel' => 'required|string',
  309. 'temp_files.zip' => 'required|string',
  310. 'individual_temp_files' => 'required|array'
  311. ]);
  312. if ($validator->fails()) {
  313. return $this->responseController->makeResponse(
  314. true,
  315. 'Se encontraron uno o más errores.',
  316. $this->responseController->makeErrors($validator->errors()->messages()),
  317. 400
  318. );
  319. }
  320. $form = $request->all();
  321. $idUser = '0000000001';
  322. // $idUser = $this->encryptionController->decrypt($form['id_user']);
  323. // if (!$idUser) {
  324. // return $this->responseController->makeResponse(true, 'ID de usuario inválido.', [], 400);
  325. // }
  326. $finalFiles = [];
  327. try {
  328. // Move Excel to final
  329. $excelFinal = $this->moveToFinal($form['temp_files']['excel'], $form['linea'], $idUser);
  330. if (!$excelFinal) {
  331. return $this->responseController->makeResponse(true, 'Error procesando Excel', [], 400);
  332. }
  333. $finalFiles['excel'] = $excelFinal;
  334. // Move ZIP to final
  335. $zipFinal = $this->moveToFinal($form['temp_files']['zip'], $form['linea'], $idUser);
  336. if (!$zipFinal) {
  337. return $this->responseController->makeResponse(true, 'Error procesando ZIP', [], 400);
  338. }
  339. $finalFiles['zip'] = $zipFinal;
  340. // Move individual temp files to final storage
  341. $individualFiles = [];
  342. foreach ($form['individual_temp_files'] as $tempFile) {
  343. $finalFileId = $this->moveToFinal($tempFile['temp_id'], $form['linea'], $idUser);
  344. if ($finalFileId) {
  345. $individualFiles[] = [
  346. 'original_name' => $tempFile['original_name'],
  347. 'final_id' => $finalFileId
  348. ];
  349. }
  350. }
  351. $finalFiles['individual_files'] = $individualFiles;
  352. return $this->responseController->makeResponse(false, 'Archivos procesados exitosamente.', $finalFiles);
  353. } catch (\Exception $e) {
  354. return $this->responseController->makeResponse(true, 'Error interno: ' . $e->getMessage(), [], 500);
  355. }
  356. }
  357. /**
  358. * Uploads Excel and ZIP files as temporary files using DocumentManagementController
  359. */
  360. private function uploadTempFiles(Request $request)
  361. {
  362. try {
  363. Log::info('UploadTempFiles: Iniciando subida de archivos temporales');
  364. $tempFiles = [];
  365. // Upload Excel file
  366. $excelRequest = new Request();
  367. $excelRequest->files->set('file', $request->file('excel_file'));
  368. $excelRequest->merge([
  369. 'id_user' => $request->input('id_user'),
  370. 'linea' => $request->input('linea')
  371. ]);
  372. $excelResponse = $this->documentManagementController->uploadTempFile($excelRequest);
  373. $excelData = json_decode($excelResponse->getContent());
  374. if ($excelData->error) {
  375. $errorMsg = isset($excelData->message) ? $excelData->message : 'Error desconocido subiendo Excel';
  376. Log::error('UploadTempFiles: Error subiendo Excel', ['message' => $errorMsg]);
  377. return ['error' => true, 'message' => 'Error subiendo Excel: ' . $errorMsg];
  378. }
  379. $tempFiles['excel'] = $excelData->response->idArchivo;
  380. // Upload ZIP file
  381. $zipRequest = new Request();
  382. $zipRequest->files->set('file', $request->file('zip_file'));
  383. $zipRequest->merge([
  384. 'id_user' => $request->input('id_user'),
  385. 'linea' => $request->input('linea')
  386. ]);
  387. $zipResponse = $this->documentManagementController->uploadTempFile($zipRequest);
  388. $zipData = json_decode($zipResponse->getContent());
  389. if ($zipData->error) {
  390. $errorMsg = isset($zipData->message) ? $zipData->message : 'Error desconocido subiendo ZIP';
  391. Log::error('UploadTempFiles: Error subiendo ZIP', ['message' => $errorMsg]);
  392. return ['error' => true, 'message' => 'Error subiendo ZIP: ' . $errorMsg];
  393. }
  394. $tempFiles['zip'] = $zipData->response->idArchivo;
  395. Log::info('UploadTempFiles: Archivos temporales subidos exitosamente', $tempFiles);
  396. return ['error' => false, 'files' => $tempFiles];
  397. } catch (\Exception $e) {
  398. Log::error('UploadTempFiles: Excepción', ['error' => $e->getMessage()]);
  399. return ['error' => true, 'message' => 'Error en uploadTempFiles: ' . $e->getMessage()];
  400. }
  401. }
  402. /**
  403. * Moves a temporary file to final storage using DocumentManagementController
  404. */
  405. private function moveToFinal($tempId, $line, $idUser)
  406. {
  407. try {
  408. $tempIdDec = $this->encryptionController->decrypt($tempId);
  409. if (!$tempIdDec) {
  410. return false;
  411. }
  412. $tempFile = DB::table('S002V01TARTE')->where('ARTE_IDAR', $tempIdDec)->first();
  413. if (!$tempFile) {
  414. return false;
  415. }
  416. $result = $this->documentManagementController->moveFinalFile($line, 'ADSI', 'LA', $tempFile, $idUser);
  417. return $result[0] ? $result[1] : false;
  418. } catch (\Exception $e) {
  419. return false;
  420. }
  421. }
  422. /**
  423. * Extracts individual files from ZIP and saves them as temporary files
  424. * Files are extracted to first level to avoid long paths and improve performance
  425. */
  426. private function extractAndSaveIndividualFilesAsTemp($zipFile, $line, $idUser)
  427. {
  428. try {
  429. $zip = new ZipArchive();
  430. if ($zip->open($zipFile->getPathname()) !== TRUE) {
  431. return false;
  432. }
  433. $tempFiles = [];
  434. $tempDir = storage_path('app/tempFiles/extracted_' . time());
  435. mkdir($tempDir, 0755, true);
  436. for ($i = 0; $i < $zip->numFiles; $i++) {
  437. $fullPath = $zip->getNameIndex($i);
  438. // Skip directories
  439. if (substr($fullPath, -1) === '/') {
  440. continue;
  441. }
  442. $fileName = basename($fullPath);
  443. if (empty($fileName)) continue;
  444. // Extract file directly to first level using file content
  445. $fileContent = $zip->getFromIndex($i);
  446. if ($fileContent !== false) {
  447. $finalExtractPath = $tempDir . '/' . $fileName;
  448. // Write file content directly to avoid directory structure
  449. if (file_put_contents($finalExtractPath, $fileContent) !== false) {
  450. // Upload as temp file
  451. $tempFileId = $this->uploadExtractedFileAsTemp($finalExtractPath, $fileName, $line, $idUser);
  452. if ($tempFileId) {
  453. $tempFiles[] = [
  454. 'original_name' => $fileName,
  455. 'temp_id' => $tempFileId
  456. ];
  457. }
  458. unlink($finalExtractPath);
  459. }
  460. }
  461. }
  462. $zip->close();
  463. $this->removeDirectory($tempDir);
  464. return $tempFiles;
  465. } catch (\Exception $e) {
  466. return false;
  467. }
  468. }
  469. /**
  470. * Uploads an extracted file as temporary file
  471. */
  472. private function uploadExtractedFileAsTemp($filePath, $fileName, $line, $idUser)
  473. {
  474. try {
  475. $extension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
  476. $mimeType = $this->getMimeType($extension);
  477. // Create a temporary uploaded file object
  478. $tempFile = new \Illuminate\Http\UploadedFile(
  479. $filePath,
  480. $fileName,
  481. $mimeType,
  482. null,
  483. true
  484. );
  485. $request = new Request();
  486. $request->files->set('file', $tempFile);
  487. $request->merge([
  488. 'id_user' => $this->encryptionController->encrypt($idUser),
  489. 'linea' => $line
  490. ]);
  491. $response = $this->documentManagementController->uploadTempFile($request);
  492. $data = json_decode($response->getContent());
  493. return $data->error ? false : $data->response->idArchivo;
  494. } catch (\Exception $e) {
  495. return false;
  496. }
  497. }
  498. /**
  499. * Gets MIME type for file extension
  500. */
  501. private function getMimeType($extension)
  502. {
  503. $mimeTypes = [
  504. 'pdf' => 'application/pdf',
  505. 'doc' => 'application/msword',
  506. 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  507. 'xls' => 'application/vnd.ms-excel',
  508. 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  509. 'ppt' => 'application/vnd.ms-powerpoint',
  510. 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
  511. 'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg',
  512. 'png' => 'image/png', 'gif' => 'image/gif', 'bmp' => 'image/bmp',
  513. 'txt' => 'text/plain', 'dwg' => 'application/acad', 'dxf' => 'application/dxf'
  514. ];
  515. return $mimeTypes[$extension] ?? 'application/octet-stream';
  516. }
  517. /**
  518. * Recursively removes a directory and its contents
  519. */
  520. private function removeDirectory($dir)
  521. {
  522. if (!is_dir($dir)) return;
  523. $files = array_diff(scandir($dir), ['.', '..']);
  524. foreach ($files as $file) {
  525. $path = $dir . '/' . $file;
  526. is_dir($path) ? $this->removeDirectory($path) : unlink($path);
  527. }
  528. rmdir($dir);
  529. }
  530. /**
  531. * Gets file type based on extension
  532. */
  533. private function getFileType($extension){
  534. $typeMap = [
  535. 'zip' => 'STORAGE', 'rar' => 'STORAGE', 'tar' => 'STORAGE', '7z' => 'STORAGE',
  536. 'mp3' => 'AUDIO', 'mpeg' => 'AUDIO', 'wav' => 'AUDIO', 'ogg' => 'AUDIO', 'opus' => 'AUDIO',
  537. 'jpeg' => 'IMG', 'jpg' => 'IMG', 'png' => 'IMG', 'gif' => 'IMG', 'bmp' => 'IMG', 'tiff' => 'IMG', 'svg' => 'IMG',
  538. 'txt' => 'TEXT',
  539. 'webm' => 'VIDEO', 'mpeg4' => 'VIDEO', 'mp4' => 'VIDEO', '3gpp' => 'VIDEO', 'mov' => 'VIDEO', 'avi' => 'VIDEO', 'wmv' => 'VIDEO', 'flv' => 'VIDEO',
  540. 'dwg' => 'CAD', 'dxf' => 'CAD', '3ds' => '3D', 'ai' => 'ILLUSTRATOR', 'psd' => 'PHOTOSHOP',
  541. 'pdf' => 'PDF', 'xls' => 'EXCEL', 'xlsx' => 'EXCEL', 'ppt' => 'POWERPOINT', 'pptx' => 'POWERPOINT',
  542. 'doc' => 'WORD', 'docx' => 'WORD', 'vsd' => 'VISIO', 'vsdx' => 'VISIO'
  543. ];
  544. return $typeMap[$extension] ?? 'UNKNOWN';
  545. }
  546. }