1
0

DataStore.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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. * @return void
  78. */
  79. public static function prependRename($srcFile, $destFile)
  80. {
  81. // don't overwrite already converted file
  82. if (!is_readable($destFile)) {
  83. $handle = fopen($srcFile, 'r', false, stream_context_create());
  84. file_put_contents($destFile, self::PROTECTION_LINE . PHP_EOL);
  85. file_put_contents($destFile, $handle, FILE_APPEND);
  86. fclose($handle);
  87. }
  88. unlink($srcFile);
  89. }
  90. }