FileUtils.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. require_once 'exceptions/IOException.php';
  3. /**
  4. * Class FileUtils
  5. *
  6. * Utility class for file manipulation.
  7. */
  8. class FileUtils
  9. {
  10. /**
  11. * @var string
  12. */
  13. protected static $phpPrefix = '<?php /* ';
  14. /**
  15. * @var string
  16. */
  17. protected static $phpSuffix = ' */ ?>';
  18. /**
  19. * Write data into a file (Shaarli database format).
  20. * The data is stored in a PHP file, as a comment, in compressed base64 format.
  21. *
  22. * The file will be created if it doesn't exist.
  23. *
  24. * @param string $file File path.
  25. * @param mixed $content Content to write.
  26. *
  27. * @return int|bool Number of bytes written or false if it fails.
  28. *
  29. * @throws IOException The destination file can't be written.
  30. */
  31. public static function writeFlatDB($file, $content)
  32. {
  33. if (is_file($file) && !is_writeable($file)) {
  34. // The datastore exists but is not writeable
  35. throw new IOException($file);
  36. } elseif (!is_file($file) && !is_writeable(dirname($file))) {
  37. // The datastore does not exist and its parent directory is not writeable
  38. throw new IOException(dirname($file));
  39. }
  40. return file_put_contents(
  41. $file,
  42. self::$phpPrefix.base64_encode(gzdeflate(serialize($content))).self::$phpSuffix
  43. );
  44. }
  45. /**
  46. * Read data from a file containing Shaarli database format content.
  47. *
  48. * If the file isn't readable or doesn't exist, default data will be returned.
  49. *
  50. * @param string $file File path.
  51. * @param mixed $default The default value to return if the file isn't readable.
  52. *
  53. * @return mixed The content unserialized, or default if the file isn't readable, or false if it fails.
  54. */
  55. public static function readFlatDB($file, $default = null)
  56. {
  57. // Note that gzinflate is faster than gzuncompress.
  58. // See: http://www.php.net/manual/en/function.gzdeflate.php#96439
  59. if (! is_readable($file)) {
  60. return $default;
  61. }
  62. $data = file_get_contents($file);
  63. if ($data == '') {
  64. return $default;
  65. }
  66. return unserialize(
  67. gzinflate(
  68. base64_decode(
  69. substr($data, strlen(self::$phpPrefix), -strlen(self::$phpSuffix))
  70. )
  71. )
  72. );
  73. }
  74. }