Flate.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. /**
  3. * This file is part of FPDI
  4. *
  5. * @package Fpdi
  6. * @copyright Copyright (c) 2020 Setasign GmbH & Co. KG (https://www.setasign.com)
  7. * @license http://opensource.org/licenses/mit-license The MIT License
  8. */
  9. namespace Fpdi\PdfParser\Filter;
  10. /**
  11. * Class for handling zlib/deflate encoded data
  12. */
  13. class Flate implements FilterInterface
  14. {
  15. /**
  16. * Checks whether the zlib extension is loaded.
  17. *
  18. * Used for testing purpose.
  19. *
  20. * @return boolean
  21. * @internal
  22. */
  23. protected function extensionLoaded()
  24. {
  25. return \extension_loaded('zlib');
  26. }
  27. /**
  28. * Decodes a flate compressed string.
  29. *
  30. * @param string|false $data The input string
  31. * @return string
  32. * @throws FlateException
  33. */
  34. public function decode($data)
  35. {
  36. if ($this->extensionLoaded()) {
  37. $oData = $data;
  38. $data = (($data !== '') ? @\gzuncompress($data) : '');
  39. if ($data === false) {
  40. // let's try if the checksum is CRC32
  41. $fh = fopen('php://temp', 'w+b');
  42. fwrite($fh, "\x1f\x8b\x08\x00\x00\x00\x00\x00" . $oData);
  43. stream_filter_append($fh, 'zlib.inflate', STREAM_FILTER_READ, ['window' => 30]);
  44. fseek($fh, 0);
  45. $data = @stream_get_contents($fh);
  46. fclose($fh);
  47. if ($data) {
  48. return $data;
  49. }
  50. // Try this fallback
  51. $tries = 0;
  52. $oDataLen = strlen($oData);
  53. while ($tries < 6 && ($data === false || (strlen($data) < ($oDataLen - $tries - 1)))) {
  54. $data = @(gzinflate(substr($oData, $tries)));
  55. $tries++;
  56. }
  57. // let's use this fallback only if the $data is longer than the original data
  58. if (strlen($data) > ($oDataLen - $tries - 1)) {
  59. return $data;
  60. }
  61. if (!$data) {
  62. throw new FlateException(
  63. 'Error while decompressing stream.',
  64. FlateException::DECOMPRESS_ERROR
  65. );
  66. }
  67. }
  68. } else {
  69. throw new FlateException(
  70. 'To handle FlateDecode filter, enable zlib support in PHP.',
  71. FlateException::NO_ZLIB
  72. );
  73. }
  74. return $data;
  75. }
  76. }