PrivateBin/lib/Model/AbstractModel.php

165 lines
3.1 KiB
PHP
Raw Normal View History

<?php
/**
2016-07-11 17:58:15 +08:00
* PrivateBin
*
* a zero-knowledge paste bin
*
2016-07-11 17:58:15 +08: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
* @version 1.1.1
*/
2016-12-13 01:43:23 +08:00
2016-12-13 01:49:08 +08:00
namespace PrivateBin\Model;
2016-07-21 23:09:48 +08:00
use Exception;
use PrivateBin\Configuration;
use PrivateBin\Data\AbstractData;
use PrivateBin\Sjcl;
2016-07-21 23:09:48 +08:00
use stdClass;
/**
* AbstractModel
*
2016-07-11 17:58:15 +08:00
* Abstract model for PrivateBin objects.
*/
2016-07-21 23:09:48 +08:00
abstract class AbstractModel
{
/**
* Instance ID.
*
* @access protected
* @var string
*/
protected $_id = '';
/**
* Instance data.
*
* @access protected
* @var stdClass
*/
protected $_data;
/**
* Configuration.
*
* @access protected
2016-08-09 18:21:32 +08:00
* @var Configuration
*/
protected $_conf;
/**
* Data storage.
*
* @access protected
2016-08-09 18:21:32 +08:00
* @var AbstractData
*/
protected $_store;
/**
* Instance constructor.
*
* @access public
2016-08-09 18:21:32 +08:00
* @param Configuration $configuration
* @param AbstractData $storage
*/
2016-08-09 18:21:32 +08:00
public function __construct(Configuration $configuration, AbstractData $storage)
{
$this->_conf = $configuration;
$this->_store = $storage;
$this->_data = new stdClass;
$this->_data->meta = new stdClass;
}
/**
* Get ID.
*
* @access public
* @return string
*/
public function getId()
{
return $this->_id;
}
/**
* Set ID.
*
* @access public
* @param string $id
* @throws Exception
*/
public function setId($id)
{
if (!self::isValidId($id)) {
throw new Exception('Invalid paste ID.', 60);
}
$this->_id = $id;
}
/**
* Set data and recalculate ID.
*
* @access public
* @param string $data
* @throws Exception
*/
public function setData($data)
{
2016-08-09 19:07:11 +08:00
if (!Sjcl::isValid($data)) {
throw new Exception('Invalid data.', 61);
}
$this->_data->data = $data;
// We just want a small hash to avoid collisions:
// Half-MD5 (64 bits) will do the trick
$this->setId(substr(hash('md5', $data), 0, 16));
}
/**
* Get instance data.
*
* @access public
2016-07-19 20:44:17 +08:00
* @return stdClass
*/
abstract public function get();
/**
* Store the instance's data.
*
* @access public
* @throws Exception
*/
abstract public function store();
/**
* Delete the current instance.
*
* @access public
* @throws Exception
*/
abstract public function delete();
/**
* Test if current instance exists in store.
*
* @access public
* @return bool
*/
abstract public function exists();
/**
* Validate ID.
*
* @access public
* @static
* @param string $id
* @return bool
*/
public static function isValidId($id)
{
return (bool) preg_match('#\A[a-f\d]{16}\z#', (string) $id);
}
}