Repo for the search and displace core module including the interface to select files and search and displace operations to run on them. https://searchanddisplace.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

75 lines
2.4 KiB

2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
  1. <?php
  2. namespace App\SearchDisplace\Convertor;
  3. use Symfony\Component\Process\Process;
  4. use Symfony\Component\Process\Exception\ProcessFailedException;
  5. use Illuminate\Support\Facades\Log;
  6. use Illuminate\Support\Facades\Storage;
  7. /**
  8. * Convert documents from formats supported by Libre Office
  9. */
  10. class Convertor {
  11. /**
  12. * @param $to desired file format
  13. * @param $document absolute file path
  14. * @param $tmp - if true file will be saved to tmp directory for download
  15. *
  16. * @return string $path to converted file
  17. */
  18. public static function convert($to, $document, $tmp = false)
  19. {
  20. $path = pathinfo($document);
  21. $extension = $path['extension'];
  22. $dir = $path['dirname'];
  23. $original = $dir . '/' . $path['basename'];
  24. if(!$tmp) {
  25. $folder = $dir . '/';
  26. } else {
  27. $folder = storage_path('app/tmp/');
  28. }
  29. $env = [
  30. 'HOME' => storage_path('app/' . env('LIBREOFFICE_CONFIG_PATH', 'tmp/libreoffice')),
  31. ];
  32. if ($extension == 'odt') {
  33. $to = $to . ':"${:FILTER}"';
  34. $env['FILTER'] = 'OpenDocument Text Flat XML';
  35. }
  36. Log::info('Running `soffice` to convert "' . $original . '" to "' . $to . '". Output folder: "' . $folder . '"');
  37. Log::info(
  38. 'COMMAND: ' .
  39. 'soffice ' .
  40. '--convert-to ' .
  41. $to . ' ' .
  42. $original . ' ' .
  43. '--outdir ' .
  44. $folder
  45. );
  46. # We will run the process from a shell command line, which allows us to add parameters
  47. # The "OpenDocument Text Flat XML" parameter contains whitespaces, so we will need to add that as
  48. # a env variable parameter, otherwise the Process class will escape it and it will not work properly.
  49. $process = Process::fromShellCommandline(
  50. "soffice --convert-to $to $original --outdir $folder",
  51. null, //base_path(),
  52. $env
  53. );
  54. $process->run(function ($type, $buffer) {
  55. if (Process::ERR === $type) {
  56. Log::info("CONVERT ERROR: " . $buffer);
  57. }
  58. }, $env);
  59. if (!$process->isSuccessful()) {
  60. throw new ProcessFailedException($process);
  61. }
  62. Storage::deleteDirectory(env('LIBREOFFICE_CONFIG_PATH', 'app/tmp/libreoffice'));
  63. return $path['filename'] . '.' . $to;
  64. }
  65. }