This commit is contained in:
F4ilji
2026-03-20 22:26:10 +05:00
parent a3948c872e
commit c80a52ab86
@@ -19,88 +19,68 @@ class ConvertDocToDocxTask
{ {
Log::info('[ConvertDocToDocxTask] Начало конвертации', [ Log::info('[ConvertDocToDocxTask] Начало конвертации', [
'file' => $file->getClientOriginalName(), 'file' => $file->getClientOriginalName(),
'size' => $file->getSize(),
'extension' => $file->getClientOriginalExtension(), 'extension' => $file->getClientOriginalExtension(),
]); ]);
// Проверяем расширение
if (strtolower($file->getClientOriginalExtension()) !== 'doc') { if (strtolower($file->getClientOriginalExtension()) !== 'doc') {
Log::warning('[ConvertDocToDocxTask] Неверное расширение', [ Log::warning('[ConvertDocToDocxTask] Неверное расширение', ['extension' => $file->getClientOriginalExtension()]);
'extension' => $file->getClientOriginalExtension(),
]);
return null; return null;
} }
// Сохраняем исходный файл во временную директорию // Сохраняем исходный файл
$originalPath = $file->storeAs('temp/conversion', 'original_' . time() . '_' . Str::random(10) . '.doc', 'local'); $originalPath = $file->storeAs('temp/conversion', 'original_' . time() . '_' . Str::random(10) . '.doc', 'local');
$absoluteOriginalPath = Storage::disk('local')->path($originalPath); $absoluteOriginalPath = Storage::disk('local')->path($originalPath);
Log::info('[ConvertDocToDocxTask] Файл сохранен', [
'original_path' => $originalPath,
'absolute_path' => $absoluteOriginalPath,
'file_exists' => file_exists($absoluteOriginalPath),
]);
// Проверяем существование файла
if (!file_exists($absoluteOriginalPath)) { if (!file_exists($absoluteOriginalPath)) {
Log::error('[ConvertDocToDocxTask] Файл не сохранен', [ Log::error('[ConvertDocToDocxTask] Файл не сохранен', ['path' => $absoluteOriginalPath]);
'path' => $absoluteOriginalPath,
]);
return null; return null;
} }
// Директория для вывода
$outputDir = dirname($absoluteOriginalPath); $outputDir = dirname($absoluteOriginalPath);
// Конвертируем через LibreOffice // Создаем уникальный путь для профиля LibreOffice в /tmp, чтобы избежать ошибок прав в /var/www
$userProfileDir = '/tmp/libreoffice_profile_' . uniqid();
// Формируем команду с изоляцией профиля и установкой HOME
// -env:UserInstallation указывает LibreOffice использовать временную папку вместо системной .cache
$command = sprintf( $command = sprintf(
'libreoffice --headless --convert-to docx --outdir %s %s 2>&1', 'export HOME=/tmp && libreoffice -env:UserInstallation=file://%s --headless --convert-to docx --outdir %s %s 2>&1',
escapeshellarg($userProfileDir),
escapeshellarg($outputDir), escapeshellarg($outputDir),
escapeshellarg($absoluteOriginalPath) escapeshellarg($absoluteOriginalPath)
); );
Log::info('[ConvertDocToDocxTask] Выполнение команды', [ Log::info('[ConvertDocToDocxTask] Выполнение команды', ['command' => $command]);
'command' => $command,
]);
$output = shell_exec($command); $output = shell_exec($command);
Log::info('[ConvertDocToDocxTask] Результат конвертации', [ // Ожидаемый путь результата
'output' => $output,
]);
// Ищем конвертированный файл
$docxPath = preg_replace('/\.doc$/i', '.docx', $absoluteOriginalPath); $docxPath = preg_replace('/\.doc$/i', '.docx', $absoluteOriginalPath);
Log::info('[ConvertDocToDocxTask] Проверка результата', [ // Удаляем временный профиль LibreOffice сразу после выполнения
'expected_path' => $docxPath, if (is_dir($userProfileDir)) {
'file_exists' => file_exists($docxPath), shell_exec('rm -rf ' . escapeshellarg($userProfileDir));
]); }
if (!file_exists($docxPath)) { if (!file_exists($docxPath)) {
// Логируем ошибку
Log::error('[ConvertDocToDocxTask] Конвертация не удалась', [ Log::error('[ConvertDocToDocxTask] Конвертация не удалась', [
'file' => $file->getClientOriginalName(), 'file' => $file->getClientOriginalName(),
'output' => $output, 'output' => $output,
'expected_path' => $docxPath, 'expected_path' => $docxPath,
]); ]);
// Удаляем исходный файл
Storage::disk('local')->delete($originalPath); Storage::disk('local')->delete($originalPath);
return null; return null;
} }
// Удаляем исходный .doc файл // Удаляем исходный .doc
Storage::disk('local')->delete($originalPath); Storage::disk('local')->delete($originalPath);
// Возвращаем относительный путь к .docx файлу
$relativeDocxPath = preg_replace('/\.doc$/i', '.docx', $originalPath); $relativeDocxPath = preg_replace('/\.doc$/i', '.docx', $originalPath);
Log::info('[ConvertDocToDocxTask] Конвертация успешна', [ Log::info('[ConvertDocToDocxTask] Конвертация успешна', ['result_path' => $relativeDocxPath]);
'result_path' => $relativeDocxPath,
]);
return $relativeDocxPath; return $relativeDocxPath;
} }
} }