vendor/knplabs/knp-snappy/src/Knp/Snappy/AbstractGenerator.php line 196

Open in your IDE?
  1. <?php
  2. namespace Knp\Snappy;
  3. use Knp\Snappy\Exception\FileAlreadyExistsException;
  4. use Psr\Log\LoggerAwareInterface;
  5. use Psr\Log\LoggerAwareTrait;
  6. use Symfony\Component\Process\Process;
  7. use Exception;
  8. use LogicException;
  9. use RuntimeException;
  10. use InvalidArgumentException;
  11. /**
  12. * Base generator class for medias.
  13. *
  14. * @author Matthieu Bontemps <[email protected]>
  15. * @author Antoine Hérault <[email protected]>
  16. */
  17. abstract class AbstractGenerator implements GeneratorInterface, LoggerAwareInterface
  18. {
  19. use LoggerAwareTrait;
  20. protected const ALLOWED_PROTOCOLS = ['file'];
  21. protected const WINDOWS_LOCAL_FILENAME_REGEX = '/^[a-z]:(?:[\\\\\/]?(?:[\w\s!#()-]+|[\.]{1,2})+)*[\\\\\/]?/i';
  22. /**
  23. * @var array
  24. */
  25. public $temporaryFiles = [];
  26. /**
  27. * @var string
  28. */
  29. protected $temporaryFolder;
  30. /**
  31. * @var null|string
  32. */
  33. private $binary;
  34. /**
  35. * @var array
  36. */
  37. private $options = [];
  38. /**
  39. * @var null|array
  40. */
  41. private $env;
  42. /**
  43. * @var null|int
  44. */
  45. private $timeout;
  46. /**
  47. * @var string
  48. */
  49. private $defaultExtension;
  50. /**
  51. * @param null|string $binary
  52. * @param array $options
  53. * @param null|array $env
  54. */
  55. public function __construct($binary, array $options = [], array|null $env = null)
  56. {
  57. $this->configure();
  58. $this->setBinary($binary);
  59. $this->setOptions($options);
  60. $this->env = empty($env) ? null : $env;
  61. \register_shutdown_function($this->removeTemporaryFiles(...));
  62. }
  63. public function __destruct()
  64. {
  65. $this->removeTemporaryFiles();
  66. }
  67. /**
  68. * Sets the default extension.
  69. * Useful when letting Snappy deal with file creation.
  70. *
  71. * @param string $defaultExtension
  72. *
  73. * @return $this
  74. */
  75. public function setDefaultExtension($defaultExtension)
  76. {
  77. $this->defaultExtension = $defaultExtension;
  78. return $this;
  79. }
  80. /**
  81. * Gets the default extension.
  82. *
  83. * @return string
  84. */
  85. public function getDefaultExtension(): string
  86. {
  87. return $this->defaultExtension;
  88. }
  89. /**
  90. * Sets an option. Be aware that option values are NOT validated and that
  91. * it is your responsibility to validate user inputs.
  92. *
  93. * @param string $name The option to set
  94. * @param mixed $value The value (NULL to unset)
  95. *
  96. * @throws InvalidArgumentException
  97. *
  98. * @return $this
  99. */
  100. public function setOption($name, $value)
  101. {
  102. if (!\array_key_exists($name, $this->options)) {
  103. throw new InvalidArgumentException(\sprintf('The option \'%s\' does not exist.', $name));
  104. }
  105. $this->options[$name] = $value;
  106. if (null !== $this->logger) {
  107. $this->logger->debug(\sprintf('Set option "%s".', $name), ['value' => $value]);
  108. }
  109. return $this;
  110. }
  111. /**
  112. * Sets the timeout.
  113. *
  114. * @param null|int $timeout The timeout to set
  115. *
  116. * @return $this
  117. */
  118. public function setTimeout($timeout)
  119. {
  120. $this->timeout = $timeout;
  121. return $this;
  122. }
  123. /**
  124. * Sets an array of options.
  125. *
  126. * @param array $options An associative array of options as name/value
  127. *
  128. * @return $this
  129. */
  130. public function setOptions(array $options)
  131. {
  132. foreach ($options as $name => $value) {
  133. $this->setOption($name, $value);
  134. }
  135. return $this;
  136. }
  137. /**
  138. * Returns all the options.
  139. *
  140. * @return array
  141. */
  142. public function getOptions()
  143. {
  144. return $this->options;
  145. }
  146. /**
  147. * {@inheritdoc}
  148. */
  149. public function generate($input, $output, array $options = [], $overwrite = false)
  150. {
  151. $this->prepareOutput($output, $overwrite);
  152. $command = $this->getCommand($input, $output, $options);
  153. $inputFiles = \is_array($input) ? \implode('", "', $input) : $input;
  154. if (null !== $this->logger) {
  155. $this->logger->info(\sprintf('Generate from file(s) "%s" to file "%s".', $inputFiles, $output), [
  156. 'command' => $command,
  157. 'env' => $this->env,
  158. 'timeout' => $this->timeout,
  159. ]);
  160. }
  161. try {
  162. list($status, $stdout, $stderr) = $this->executeCommand($command);
  163. $this->checkProcessStatus($status, $stdout, $stderr, $command);
  164. $this->checkOutput($output, $command);
  165. } catch (Exception $e) {
  166. if (null !== $this->logger) {
  167. $this->logger->error(\sprintf('An error happened while generating "%s".', $output), [
  168. 'command' => $command,
  169. 'status' => $status ?? null,
  170. 'stdout' => $stdout ?? null,
  171. 'stderr' => $stderr ?? null,
  172. ]);
  173. }
  174. throw $e;
  175. }
  176. if (null !== $this->logger) {
  177. $this->logger->info(\sprintf('File "%s" has been successfully generated.', $output), [
  178. 'command' => $command,
  179. 'stdout' => $stdout,
  180. 'stderr' => $stderr,
  181. ]);
  182. }
  183. }
  184. /**
  185. * {@inheritdoc}
  186. */
  187. public function generateFromHtml($html, $output, array $options = [], $overwrite = false)
  188. {
  189. $fileNames = [];
  190. if (\is_array($html)) {
  191. foreach ($html as $htmlInput) {
  192. $fileNames[] = $this->createTemporaryFile($htmlInput, 'html');
  193. }
  194. } else {
  195. $fileNames[] = $this->createTemporaryFile($html, 'html');
  196. }
  197. $this->generate($fileNames, $output, $options, $overwrite);
  198. }
  199. /**
  200. * {@inheritdoc}
  201. */
  202. public function getOutput($input, array $options = [])
  203. {
  204. $filename = $this->createTemporaryFile(null, $this->getDefaultExtension());
  205. $this->generate($input, $filename, $options);
  206. return $this->getFileContents($filename);
  207. }
  208. /**
  209. * {@inheritdoc}
  210. */
  211. public function getOutputFromHtml($html, array $options = [])
  212. {
  213. $fileNames = [];
  214. if (\is_array($html)) {
  215. foreach ($html as $htmlInput) {
  216. $fileNames[] = $this->createTemporaryFile($htmlInput, 'html');
  217. }
  218. } else {
  219. $fileNames[] = $this->createTemporaryFile($html, 'html');
  220. }
  221. return $this->getOutput($fileNames, $options);
  222. }
  223. /**
  224. * Defines the binary.
  225. *
  226. * @param null|string $binary The path/name of the binary
  227. *
  228. * @return $this
  229. */
  230. public function setBinary($binary)
  231. {
  232. $this->binary = $binary;
  233. return $this;
  234. }
  235. /**
  236. * Returns the binary.
  237. *
  238. * @return null|string
  239. */
  240. public function getBinary()
  241. {
  242. return $this->binary;
  243. }
  244. /**
  245. * Returns the command for the given input and output files.
  246. *
  247. * @param array|string $input The input file
  248. * @param string $output The ouput file
  249. * @param array $options An optional array of options that will be used
  250. * only for this command
  251. *
  252. * @return string
  253. */
  254. public function getCommand($input, $output, array $options = [])
  255. {
  256. if (null === $this->binary) {
  257. throw new LogicException('You must define a binary prior to conversion.');
  258. }
  259. $options = $this->mergeOptions($options);
  260. return $this->buildCommand($this->binary, $input, $output, $options);
  261. }
  262. /**
  263. * Removes all temporary files.
  264. *
  265. * @return void
  266. */
  267. public function removeTemporaryFiles()
  268. {
  269. foreach ($this->temporaryFiles as $file) {
  270. $filePath = \realpath($file);
  271. $temporaryFolderPath = \realpath($this->getTemporaryFolder());
  272. if (
  273. !$filePath
  274. || !$temporaryFolderPath
  275. || !\str_starts_with($filePath, $temporaryFolderPath)
  276. ) {
  277. continue;
  278. }
  279. $this->unlink($file);
  280. }
  281. }
  282. /**
  283. * Get TemporaryFolder.
  284. *
  285. * @return string
  286. */
  287. public function getTemporaryFolder()
  288. {
  289. if ($this->temporaryFolder === null) {
  290. $this->temporaryFolder = \sys_get_temp_dir();
  291. }
  292. return $this->temporaryFolder;
  293. }
  294. /**
  295. * Set temporaryFolder.
  296. *
  297. * @param string $temporaryFolder
  298. *
  299. * @return $this
  300. */
  301. public function setTemporaryFolder($temporaryFolder)
  302. {
  303. $this->temporaryFolder = $temporaryFolder;
  304. return $this;
  305. }
  306. /**
  307. * Reset all options to their initial values.
  308. *
  309. * @return void
  310. */
  311. public function resetOptions()
  312. {
  313. $this->options = [];
  314. $this->configure();
  315. }
  316. /**
  317. * This method must configure the media options.
  318. *
  319. * @return void
  320. *
  321. * @see AbstractGenerator::addOption()
  322. */
  323. abstract protected function configure();
  324. /**
  325. * Adds an option.
  326. *
  327. * @param string $name The name
  328. * @param mixed $default An optional default value
  329. *
  330. * @throws InvalidArgumentException
  331. *
  332. * @return $this
  333. */
  334. protected function addOption($name, $default = null)
  335. {
  336. if (\array_key_exists($name, $this->options)) {
  337. throw new InvalidArgumentException(\sprintf('The option \'%s\' already exists.', $name));
  338. }
  339. $this->options[$name] = $default;
  340. return $this;
  341. }
  342. /**
  343. * Adds an array of options.
  344. *
  345. * @param array $options
  346. *
  347. * @return $this
  348. */
  349. protected function addOptions(array $options)
  350. {
  351. foreach ($options as $name => $default) {
  352. $this->addOption($name, $default);
  353. }
  354. return $this;
  355. }
  356. /**
  357. * Merges the given array of options to the instance options and returns
  358. * the result options array. It does NOT change the instance options.
  359. *
  360. * @param array $options
  361. *
  362. * @throws InvalidArgumentException
  363. *
  364. * @return array
  365. */
  366. protected function mergeOptions(array $options)
  367. {
  368. $mergedOptions = $this->options;
  369. foreach ($options as $name => $value) {
  370. if (!\array_key_exists($name, $mergedOptions)) {
  371. throw new InvalidArgumentException(\sprintf('The option \'%s\' does not exist.', $name));
  372. }
  373. $mergedOptions[$name] = $value;
  374. }
  375. return $mergedOptions;
  376. }
  377. /**
  378. * Checks the specified output.
  379. *
  380. * @param string $output The output filename
  381. * @param string $command The generation command
  382. *
  383. * @throws RuntimeException if the output file generation failed
  384. *
  385. * @return void
  386. */
  387. protected function checkOutput($output, $command)
  388. {
  389. // the output file must exist
  390. if (!$this->fileExists($output)) {
  391. throw new RuntimeException(\sprintf('The file \'%s\' was not created (command: %s).', $output, $command));
  392. }
  393. // the output file must not be empty
  394. if (0 === $this->filesize($output)) {
  395. throw new RuntimeException(\sprintf('The file \'%s\' was created but is empty (command: %s).', $output, $command));
  396. }
  397. }
  398. /**
  399. * Checks the process return status.
  400. *
  401. * @param int $status The exit status code
  402. * @param string $stdout The stdout content
  403. * @param string $stderr The stderr content
  404. * @param string $command The run command
  405. *
  406. * @throws RuntimeException if the output file generation failed
  407. *
  408. * @return void
  409. */
  410. protected function checkProcessStatus($status, $stdout, $stderr, $command)
  411. {
  412. if (0 !== $status && '' !== $stderr) {
  413. throw new RuntimeException(\sprintf('The exit status code \'%s\' says something went wrong:' . "\n" . 'stderr: "%s"' . "\n" . 'stdout: "%s"' . "\n" . 'command: %s.', $status, $stderr, $stdout, $command), $status);
  414. }
  415. }
  416. /**
  417. * Creates a temporary file.
  418. * The file is not created if the $content argument is null.
  419. *
  420. * @param null|string $content Optional content for the temporary file
  421. * @param null|string $extension An optional extension for the filename
  422. *
  423. * @return string The filename
  424. */
  425. protected function createTemporaryFile($content = null, $extension = null)
  426. {
  427. $dir = \rtrim($this->getTemporaryFolder(), \DIRECTORY_SEPARATOR);
  428. if (!\is_dir($dir)) {
  429. if (false === @\mkdir($dir, 0777, true) && !\is_dir($dir)) {
  430. throw new RuntimeException(\sprintf("Unable to create directory: %s\n", $dir));
  431. }
  432. } elseif (!\is_writable($dir)) {
  433. throw new RuntimeException(\sprintf("Unable to write in directory: %s\n", $dir));
  434. }
  435. $filename = $dir . \DIRECTORY_SEPARATOR . \uniqid('knp_snappy', true);
  436. if (null !== $extension) {
  437. $filename .= '.' . $extension;
  438. }
  439. if (null !== $content) {
  440. \file_put_contents($filename, $content);
  441. $this->temporaryFiles[] = $filename;
  442. }
  443. return $filename;
  444. }
  445. /**
  446. * Builds the command string.
  447. *
  448. * @param string $binary The binary path/name
  449. * @param array|string $input Url(s) or file location(s) of the page(s) to process
  450. * @param string $output File location to the image-to-be
  451. * @param array $options An array of options
  452. *
  453. * @return string
  454. */
  455. protected function buildCommand($binary, $input, $output, array $options = [])
  456. {
  457. $command = $this->getEscapedBinary($binary);
  458. foreach ($options as $key => $option) {
  459. if (null !== $option && false !== $option) {
  460. if (true === $option) {
  461. // Dont't put '--' if option is 'toc'.
  462. if ($key === 'toc') {
  463. $command .= ' ' . $key;
  464. } else {
  465. $command .= ' --' . $key;
  466. }
  467. } elseif (\is_array($option)) {
  468. if ($this->isAssociativeArray($option)) {
  469. foreach ($option as $k => $v) {
  470. $command .= ' --' . $key . ' ' . \escapeshellarg($k) . ' ' . \escapeshellarg($v);
  471. }
  472. } else {
  473. foreach ($option as $v) {
  474. $command .= ' --' . $key . ' ' . \escapeshellarg($v);
  475. }
  476. }
  477. } else {
  478. // Dont't add '--' if option is "cover" or "toc".
  479. if (\in_array($key, ['toc', 'cover'])) {
  480. $command .= ' ' . $key . ' ' . \escapeshellarg($option);
  481. } elseif (\in_array($key, ['image-dpi', 'image-quality'])) {
  482. $command .= ' --' . $key . ' ' . (int) $option;
  483. } else {
  484. $command .= ' --' . $key . ' ' . \escapeshellarg($option);
  485. }
  486. }
  487. }
  488. }
  489. if (\is_array($input)) {
  490. foreach ($input as $i) {
  491. $command .= ' ' . \escapeshellarg($i) . ' ';
  492. }
  493. $command .= \escapeshellarg($output);
  494. } else {
  495. $command .= ' ' . \escapeshellarg($input) . ' ' . \escapeshellarg($output);
  496. }
  497. return $command;
  498. }
  499. /**
  500. * Return true if the array is an associative array
  501. * and not an indexed array.
  502. *
  503. * @param array $array
  504. *
  505. * @return bool
  506. */
  507. protected function isAssociativeArray(array $array)
  508. {
  509. return (bool) \count(\array_filter(\array_keys($array), 'is_string'));
  510. }
  511. /**
  512. * Executes the given command via shell and returns the complete output as
  513. * a string.
  514. *
  515. * @param string $command
  516. *
  517. * @return array [status, stdout, stderr]
  518. */
  519. protected function executeCommand($command)
  520. {
  521. $process = Process::fromShellCommandline($command, null, $this->env);
  522. if (null !== $this->timeout) {
  523. $process->setTimeout($this->timeout);
  524. }
  525. $process->run();
  526. return [
  527. $process->getExitCode(),
  528. $process->getOutput(),
  529. $process->getErrorOutput(),
  530. ];
  531. }
  532. /**
  533. * Prepares the specified output.
  534. *
  535. * @param string $filename The output filename
  536. * @param bool $overwrite Whether to overwrite the file if it already
  537. * exist
  538. *
  539. * @throws FileAlreadyExistsException
  540. * @throws RuntimeException
  541. * @throws InvalidArgumentException
  542. *
  543. * @return void
  544. */
  545. protected function prepareOutput($filename, $overwrite)
  546. {
  547. if (!$this->isProtocolAllowed($filename)) {
  548. throw new InvalidArgumentException(\sprintf('The output file scheme is not supported. Expected one of [\'%s\'].', \implode('\', \'', self::ALLOWED_PROTOCOLS)));
  549. }
  550. $directory = \dirname($filename);
  551. if ($this->fileExists($filename)) {
  552. if (!$this->isFile($filename)) {
  553. throw new InvalidArgumentException(\sprintf('The output file \'%s\' already exists and it is a %s.', $filename, $this->isDir($filename) ? 'directory' : 'link'));
  554. }
  555. if (false === $overwrite) {
  556. throw new FileAlreadyExistsException(\sprintf('The output file \'%s\' already exists.', $filename));
  557. }
  558. if (!$this->unlink($filename)) {
  559. throw new RuntimeException(\sprintf('Could not delete already existing output file \'%s\'.', $filename));
  560. }
  561. } elseif (!$this->isDir($directory) && !$this->mkdir($directory)) {
  562. throw new RuntimeException(\sprintf('The output file\'s directory \'%s\' could not be created.', $directory));
  563. }
  564. }
  565. /**
  566. * Verifies if the given filename has a supported protocol.
  567. *
  568. * @param string $filename
  569. *
  570. * @throws InvalidArgumentException
  571. *
  572. * @return bool
  573. */
  574. protected function isProtocolAllowed($filename)
  575. {
  576. if (false === $parsedFilename = \parse_url($filename)) {
  577. throw new InvalidArgumentException('The filename is not valid.');
  578. }
  579. $protocol = isset($parsedFilename['scheme']) ? \mb_strtolower($parsedFilename['scheme']) : 'file';
  580. if (
  581. \PHP_OS_FAMILY === 'Windows'
  582. && \strlen($protocol) === 1
  583. && \preg_match(self::WINDOWS_LOCAL_FILENAME_REGEX, $filename)
  584. ) {
  585. $protocol = 'file';
  586. }
  587. return \in_array($protocol, self::ALLOWED_PROTOCOLS, true);
  588. }
  589. /**
  590. * Wrapper for the "file_get_contents" function.
  591. *
  592. * @param string $filename
  593. *
  594. * @return string
  595. */
  596. protected function getFileContents($filename)
  597. {
  598. $fileContent = \file_get_contents($filename);
  599. if (false === $fileContent) {
  600. throw new RuntimeException(\sprintf('Could not read file \'%s\' content.', $filename));
  601. }
  602. return $fileContent;
  603. }
  604. /**
  605. * Wrapper for the "file_exists" function.
  606. *
  607. * @param string $filename
  608. *
  609. * @return bool
  610. */
  611. protected function fileExists($filename)
  612. {
  613. return \file_exists($filename);
  614. }
  615. /**
  616. * Wrapper for the "is_file" method.
  617. *
  618. * @param string $filename
  619. *
  620. * @return bool
  621. */
  622. protected function isFile($filename)
  623. {
  624. return \strlen($filename) <= \PHP_MAXPATHLEN && \is_file($filename);
  625. }
  626. /**
  627. * Wrapper for the "filesize" function.
  628. *
  629. * @param string $filename
  630. *
  631. * @return int
  632. */
  633. protected function filesize($filename)
  634. {
  635. $filesize = \filesize($filename);
  636. if (false === $filesize) {
  637. throw new RuntimeException(\sprintf('Could not read file \'%s\' size.', $filename));
  638. }
  639. return $filesize;
  640. }
  641. /**
  642. * Wrapper for the "unlink" function.
  643. *
  644. * @param string $filename
  645. *
  646. * @return bool
  647. */
  648. protected function unlink($filename)
  649. {
  650. return $this->fileExists($filename) ? \unlink($filename) : false;
  651. }
  652. /**
  653. * Wrapper for the "is_dir" function.
  654. *
  655. * @param string $filename
  656. *
  657. * @return bool
  658. */
  659. protected function isDir($filename)
  660. {
  661. return \is_dir($filename);
  662. }
  663. /**
  664. * Wrapper for the mkdir function.
  665. *
  666. * @param string $pathname
  667. *
  668. * @return bool
  669. */
  670. protected function mkdir($pathname)
  671. {
  672. return \mkdir($pathname, 0777, true);
  673. }
  674. protected function getEscapedBinary(string $binary): string
  675. {
  676. if (!\is_executable($binary)) {
  677. throw new RuntimeException("The binary '{$binary}' is not executable.");
  678. }
  679. return \escapeshellarg($binary);
  680. }
  681. }