1
0

persistence.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  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. * path in which to persist something
  21. *
  22. * @access private
  23. * @static
  24. * @var string
  25. */
  26. private static $_path = 'data';
  27. /**
  28. * set the path
  29. *
  30. * @access public
  31. * @static
  32. * @param string $path
  33. * @return void
  34. */
  35. public static function setPath($path)
  36. {
  37. self::$_path = $path;
  38. }
  39. /**
  40. * get the path
  41. *
  42. * @access public
  43. * @static
  44. * @param string $filename
  45. * @return void
  46. */
  47. public static function getPath($filename = null)
  48. {
  49. if(strlen($filename)) {
  50. return self::$_path . DIRECTORY_SEPARATOR . $filename;
  51. } else {
  52. return self::$_path;
  53. }
  54. }
  55. /**
  56. * checks if the file exists
  57. *
  58. * @access protected
  59. * @static
  60. * @param string $filename
  61. * @return bool
  62. */
  63. protected static function _exists($filename)
  64. {
  65. self::_initialize();
  66. return is_file(self::$_path . '/' . $filename);
  67. }
  68. /**
  69. * prepares path for storage
  70. *
  71. * @access protected
  72. * @static
  73. * @return void
  74. */
  75. protected static function _initialize()
  76. {
  77. // Create storage directory if it does not exist.
  78. if (!is_dir(self::$_path)) mkdir(self::$_path, 0705);
  79. // Create .htaccess file if it does not exist.
  80. $file = self::$_path . '/.htaccess';
  81. if (!is_file($file))
  82. {
  83. file_put_contents(
  84. $file,
  85. 'Allow from none' . PHP_EOL .
  86. 'Deny from all'. PHP_EOL,
  87. LOCK_EX
  88. );
  89. }
  90. }
  91. /**
  92. * store the data
  93. *
  94. * @access protected
  95. * @static
  96. * @param string $filename
  97. * @param string $data
  98. * @return string
  99. */
  100. protected static function _store($filename, $data)
  101. {
  102. self::_initialize();
  103. $file = self::$_path . '/' . $filename;
  104. file_put_contents($file, $data, LOCK_EX);
  105. chmod($file, 0705);
  106. return $file;
  107. }
  108. }