persistence.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. <?php
  2. /**
  3. * ZeroBin
  4. *
  5. * a zero-knowledge paste bin
  6. *
  7. * @link http://sebsauvage.net/wiki/doku.php?id=php:zerobin
  8. * @copyright 2012 Sébastien SAUVAGE (sebsauvage.net)
  9. * @license http://www.opensource.org/licenses/zlib-license.php The zlib/libpng License
  10. * @version 0.19
  11. */
  12. /**
  13. * persistence
  14. *
  15. * persists data in PHP files
  16. */
  17. abstract class persistence
  18. {
  19. /**
  20. * @access private
  21. * @static
  22. * @var string
  23. */
  24. private static $_path = 'data';
  25. /**
  26. * set the path
  27. *
  28. * @access public
  29. * @static
  30. * @param string $path
  31. * @return void
  32. */
  33. public static function setPath($path)
  34. {
  35. self::$_path = $path;
  36. }
  37. /**
  38. * get the path
  39. *
  40. * @access public
  41. * @static
  42. * @param string $filename
  43. * @return void
  44. */
  45. public static function getPath($filename = null)
  46. {
  47. if(strlen($filename)) {
  48. return self::$_path . DIRECTORY_SEPARATOR . $filename;
  49. } else {
  50. return self::$_path;
  51. }
  52. }
  53. /**
  54. * checks if the file exists
  55. *
  56. * @access protected
  57. * @static
  58. * @param string $filename
  59. * @return bool
  60. */
  61. protected static function _exists($filename)
  62. {
  63. self::_initialize();
  64. return is_file(self::$_path . '/' . $filename);
  65. }
  66. /**
  67. * prepares path for storage
  68. *
  69. * @access protected
  70. * @static
  71. * @return void
  72. */
  73. protected static function _initialize()
  74. {
  75. // Create storage directory if it does not exist.
  76. if (!is_dir(self::$_path)) mkdir(self::$_path, 0705);
  77. // Create .htaccess file if it does not exist.
  78. $file = self::$_path . '/.htaccess';
  79. if (!is_file($file))
  80. {
  81. file_put_contents(
  82. $file,
  83. 'Allow from none' . PHP_EOL .
  84. 'Deny from all'. PHP_EOL
  85. );
  86. }
  87. }
  88. /**
  89. * store the data
  90. *
  91. * @access protected
  92. * @static
  93. * @param string $filename
  94. * @param string $data
  95. * @return string
  96. */
  97. protected static function _store($filename, $data)
  98. {
  99. self::_initialize();
  100. $file = self::$_path . '/' . $filename;
  101. file_put_contents($file, $data);
  102. chmod($file, 0705);
  103. return $file;
  104. }
  105. }