paste.chapril.org-privatebin/lib/Persistence/AbstractPersistence.php

136 lines
3.2 KiB
PHP
Raw Normal View History

<?php
/**
2016-07-11 11:58:15 +02:00
* PrivateBin
*
* a zero-knowledge paste bin
*
2016-07-11 11:58:15 +02:00
* @link https://github.com/PrivateBin/PrivateBin
* @copyright 2012 Sébastien SAUVAGE (sebsauvage.net)
* @license https://www.opensource.org/licenses/zlib-license.php The zlib/libpng License
2021-04-05 16:44:12 +02:00
* @version 1.3.5
*/
2016-12-12 18:43:23 +01:00
2016-12-12 18:49:08 +01:00
namespace PrivateBin\Persistence;
2016-07-21 17:09:48 +02:00
use Exception;
/**
* AbstractPersistence
*
* persists data in PHP files
*/
abstract class AbstractPersistence
{
/**
* path in which to persist something
*
* @access private
* @static
* @var string
*/
private static $_path = 'data';
/**
* set the path
*
* @access public
* @static
* @param string $path
*/
public static function setPath($path)
{
self::$_path = $path;
}
/**
* get the path
*
* @access public
* @static
* @param string $filename
2016-07-18 15:13:56 +02:00
* @return string
*/
public static function getPath($filename = null)
{
if (strlen($filename)) {
return self::$_path . DIRECTORY_SEPARATOR . $filename;
} else {
return self::$_path;
}
}
/**
* checks if the file exists
*
* @access protected
* @static
* @param string $filename
* @return bool
*/
protected static function _exists($filename)
{
self::_initialize();
return is_file(self::$_path . DIRECTORY_SEPARATOR . $filename);
}
/**
* prepares path for storage
*
* @access protected
* @static
* @throws Exception
*/
protected static function _initialize()
{
// Create storage directory if it does not exist.
if (!is_dir(self::$_path)) {
if (!@mkdir(self::$_path, 0700)) {
throw new Exception('unable to create directory ' . self::$_path, 10);
}
}
$file = self::$_path . DIRECTORY_SEPARATOR . '.htaccess';
if (!is_file($file)) {
$writtenBytes = 0;
if ($fileCreated = @touch($file)) {
$writtenBytes = @file_put_contents(
$file,
'Require all denied' . PHP_EOL,
LOCK_EX
);
}
if ($fileCreated === false || $writtenBytes === false || $writtenBytes < 19) {
throw new Exception('unable to write to file ' . $file, 11);
}
}
}
/**
* store the data
*
* @access protected
* @static
* @param string $filename
* @param string $data
* @throws Exception
* @return string
*/
protected static function _store($filename, $data)
{
self::_initialize();
2021-06-05 05:52:13 +02:00
$file = self::$_path . DIRECTORY_SEPARATOR . $filename;
$fileCreated = true;
$writtenBytes = 0;
if (!is_file($file)) {
$fileCreated = @touch($file);
}
if ($fileCreated) {
$writtenBytes = @file_put_contents($file, $data, LOCK_EX);
}
if ($fileCreated === false || $writtenBytes === false || $writtenBytes < strlen($data)) {
throw new Exception('unable to write to file ' . $file, 13);
}
2016-06-22 18:08:25 +02:00
@chmod($file, 0640); // protect file access
return $file;
}
}