DataStore.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. <?php
  2. /**
  3. * PrivateBin
  4. *
  5. * a zero-knowledge paste bin
  6. *
  7. * @link https://github.com/PrivateBin/PrivateBin
  8. * @copyright 2012 Sébastien SAUVAGE (sebsauvage.net)
  9. * @license https://www.opensource.org/licenses/zlib-license.php The zlib/libpng License
  10. * @version 1.3.5
  11. */
  12. namespace PrivateBin\Persistence;
  13. use Exception;
  14. use PrivateBin\Json;
  15. /**
  16. * DataStore
  17. *
  18. * Handles data storage for Data\Filesystem.
  19. */
  20. class DataStore extends AbstractPersistence
  21. {
  22. /**
  23. * first line in file, to protect its contents
  24. *
  25. * @const string
  26. */
  27. const PROTECTION_LINE = '<?php http_response_code(403); /*';
  28. /**
  29. * store the data
  30. *
  31. * @access public
  32. * @static
  33. * @param string $filename
  34. * @param array $data
  35. * @return bool
  36. */
  37. public static function store($filename, $data)
  38. {
  39. $path = self::getPath();
  40. if (strpos($filename, $path) === 0) {
  41. $filename = substr($filename, strlen($path));
  42. }
  43. try {
  44. self::_store(
  45. $filename,
  46. self::PROTECTION_LINE . PHP_EOL . Json::encode($data)
  47. );
  48. return true;
  49. } catch (Exception $e) {
  50. return false;
  51. }
  52. }
  53. /**
  54. * get the data
  55. *
  56. * @access public
  57. * @static
  58. * @param string $filename
  59. * @return array|false $data
  60. */
  61. public static function get($filename)
  62. {
  63. return Json::decode(
  64. substr(
  65. file_get_contents($filename),
  66. strlen(self::PROTECTION_LINE . PHP_EOL)
  67. )
  68. );
  69. }
  70. /**
  71. * rename a file, prepending the protection line at the beginning
  72. *
  73. * @access public
  74. * @static
  75. * @param string $srcFile
  76. * @param string $destFile
  77. * @param string $prefix (optional)
  78. * @return void
  79. */
  80. public static function prependRename($srcFile, $destFile, $prefix = '')
  81. {
  82. // don't overwrite already converted file
  83. if (!is_readable($destFile)) {
  84. $handle = fopen($srcFile, 'r', false, stream_context_create());
  85. file_put_contents($destFile, $prefix . self::PROTECTION_LINE . PHP_EOL);
  86. file_put_contents($destFile, $handle, FILE_APPEND);
  87. fclose($handle);
  88. }
  89. unlink($srcFile);
  90. }
  91. }