DataStore.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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.1
  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($filename, self::PROTECTION_LINE . PHP_EOL . Json::encode($data));
  45. return true;
  46. } catch (Exception $e) {
  47. return false;
  48. }
  49. }
  50. /**
  51. * get the data
  52. *
  53. * @access public
  54. * @static
  55. * @param string $filename
  56. * @return stdClass|false $data
  57. */
  58. public static function get($filename)
  59. {
  60. return json_decode(substr(file_get_contents($filename), strlen(self::PROTECTION_LINE . PHP_EOL)));
  61. }
  62. /**
  63. * rename a file, prepending the protection line at the beginning
  64. *
  65. * @access public
  66. * @static
  67. * @param string $srcFile
  68. * @param string $destFile
  69. * @param string $prefix (optional)
  70. * @return void
  71. */
  72. public static function prependRename($srcFile, $destFile, $prefix = '')
  73. {
  74. // don't overwrite already converted file
  75. if (!is_readable($destFile)) {
  76. $handle = fopen($srcFile, 'r', false, stream_context_create());
  77. file_put_contents($destFile, $prefix . DataStore::PROTECTION_LINE . PHP_EOL);
  78. file_put_contents($destFile, $handle, FILE_APPEND);
  79. fclose($handle);
  80. }
  81. unlink($srcFile);
  82. }
  83. }