Source for file File.php
Documentation is available at File.php
/* vim: set expandtab tabstop=4 shiftwidth=4: */
// +----------------------------------------------------------------------+
// | Copyright (c) 2002-2003 Brent Cook |
// +----------------------------------------------------------------------+
// | This library is free software; you can redistribute it and/or |
// | modify it under the terms of the GNU Lesser General Public |
// | License as published by the Free Software Foundation; either |
// | version 2.1 of the License, or (at your option) any later version. |
// | This library is distributed in the hope that it will be useful, |
// | but WITHOUT ANY WARRANTY; without even the implied warranty of |
// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
// | Lesser General Public License for more details. |
// | You should have received a copy of the GNU Lesser General Public |
// | License along with this library; if not, write to the Free Software |
// | Foundation, Inc., 59 Temple Place, Suite 330,Boston,MA 02111-1307 USA|
// +----------------------------------------------------------------------+
// $Id: File.php,v 1.12 2003/01/27 04:31:42 busterb Exp $
* Location in the index file for a block location
* Location in the index file for a block size
* Location in the index file for a block value size
* Location in the index file for a block key
* DBA_Driver_File provides a simple, file-based implementation of a
* DBM-style database. It uses two files, and index and a data file to
* manage key/value pairs. These two files use the suffixes '.dat' and
* '.idx'. When a database is opened, only the index file is read. The
* index file contains pointers to locations within the data file, which
* are used to retrieve values.
* The class uses a concept of blocks for data storage. When the first value
* is inserted, a new block is created by appending to the data file. If that
* value is deleted, it remains in the data file, but is marked as empty in
* the index file. A list of available blocks is kept, so when a new value
* is inserted, its size is compared to the list of available blocks. If one
* is of sufficient size, it is reused and marked as used in the index file.
* Blocks can be of any length.
* In updating the index, lines are simply appended to the file after each
* operation. So, the index file might have the same block listed multiple time
* , just in different states. When the database is closed, it rewrites the
* index file, removing and duplicate entries for a single block. The index
* reader only uses the last entry for a block from the index file, so if close
* is not called for some reason, the index file is still in a valid state.
* The optimize function merely removes duplicated index entries by rewriting
* the file, the same as close.
* The sync function calls fflush on the data and index files.
// {{{ instance variables
* Indicates the current ability for read/write operations
* Indicates the current ability for read operations
* Determines if the driver should use an index file
// {{{ DBA_Driver_File($indexed = true)
* @param string $driver dba driver to use
// call the base constructor
// {{{ open($dbName='', $mode='r', $persistent = false)
* @param string $dbName The name of a database
* @param string $mode The mode in which to open a database.
* 'n' creates a new database and opens read-write.
* 'c' creates a new database if the database does not
* exist and opens read-write.
* @param boolean $persistent Determines whether to open the database
* peristently. Not supported here.
* @return object PEAR_Error on failure
function open($dbName= '', $mode= 'r', $persistent = false )
$this->_dbName = $dbName;
$dat_name = $dbName. '.dat';
$idx_name = $dbName. '.idx';
$this->_writable = false;
// should we create a new database?
} // otherwise, we just open for writing
$this->_idxFP = @fopen($idx_name, $file_mode);
if ($this->_idxFP === false ) {
$this->_writable = false;
$this->_readable = false;
'could not open idx file '. $idx_name);
$this->_datFP = @fopen($dat_name, $file_mode);
if ($this->_datFP === false ) {
$this->_writable = false;
$this->_readable = false;
'could not open data file '. $dat_name);
// get a shared lock if read-only, otherwise get an exclusive lock
flock ($this -> _idxFP, LOCK_SH );
flock ($this -> _datFP, LOCK_SH );
flock ($this -> _idxFP, LOCK_EX );
flock ($this -> _datFP, LOCK_EX );
// we are writing to a new file, so we do not need to read anything
if ($file_mode != 'w+') {
* Closes an open database.
* @return object PEAR_Error on failure
$this->_readable = false;
$this->_writable = false;
* Reopens an already open database in read-only or write mode.
* If the database is already in the requested mode, then this function
* @param string $mode 'r' for read-only, 'w' for read/write
* @return object PEAR_Error on failure
// Reopening as read-only
return $this->open($this->_dbName, 'r');
if (($mode == 'w') && (!$this -> _writable))
// Reopening as read-write
return $this->open($this->_dbName, 'w');
// {{{ _DBA_Driver_File()
* PEAR emulated destructor calls close on PHP shutdown
function _DBA_Driver_File ()
* Returns the name of the opened database. Assumes database is open
* @returns string the name of the opened database
* Returns the current open status for the database
* @return boolean true if the database is open, false if it is closed
return($this->_readable || $this->_writable);
* Returns the current read status for the database
* @return boolean true if the database is readable, false if it is not
* Returns the current write status for the database
* @return boolean true if the database is writable, false if it is not
* Removes the value at location $key
* @param string $key key to remove
* @return object PEAR_Error on failure
if (isset ($this->_usedBlocks[$key])) {
$this->_freeUsedBlock ($key);
* Returns the value that is stored at $key.
* @param string $key key to examine
* @return mixed the requested value on success, false on failure
if (!isset ($this->_usedBlocks[$key])) {
* Returns the first key in the database
* @return mixed string on success, false on failure
reset($this->_usedBlocks);
return key($this->_usedBlocks);
* Returns the next key in the database, false if there is a problem
* @return mixed string on success, false on failure
&& next($this->_usedBlocks)) {
return key($this->_usedBlocks);
* Returns all keys in the database
* Calculates the size of the database in number of keys
* @return int number of keys in the database
return sizeof($this->_usedBlocks);
// {{{ insert($key, $value)
* Inserts a new value at $key. Will not overwrite if the key/value pair
* @param string $key key to insert
* @param string $value value to store
* @return object PEAR_Error on failure
return $this->replace($key, $value);
// {{{ replace($key, $value)
* Inserts a new value at key. If the key/value pair
* already exist, overwrites the value
* @param $key string the key to insert
* @param $val string the value to store
* @return object PEAR_Error on failure
// is the database in a usable state?
// get how much space we need
if (!isset ($this->_usedBlocks[$key])) {
$this->_writeNewBlock ($key, $value, $vsize);
// is the value smaller or equal in size to its block size
// move to the block's location in the data file
fseek($this->_datFP, $loc);
// write to the data file
// update internal indecies
$this->_writeIdxEntry ($loc, $size, $vsize, $key);
// the value is larger than its allocated space
// free this value's allocated block
$this->_freeUsedBlock ($key);
$this->_writeNewBlock ($key, $value, $vsize);
// {{{ _writeNewBlock($key, $value, $vsize)
* Allocates a new block of at least $vsize and writes $key=>$val
function _writeNewBlock ($key, $value, $vsize)
// is there is a sufficiently sized block free ?
$loc = $this->_getFreeBlock ($vsize);
// update free block list
$size = $this->_freeBlocks[$loc];
unset ($this->_freeBlocks[$loc]);
// move to the block's location in the data file
fseek($this->_datFP, $loc, SEEK_SET );
// write to the data file
$this->_usedBlocks[$key] = array ($loc, $size, $vsize);
$this->_writeIdxEntry ($loc, $size, $vsize, $key);
// there is not a sufficiently sized block free
// move to the end of the data file
fseek($this ->_datFP, 0 , SEEK_END );
$loc = ftell($this->_datFP);
// write to the data file
$size = $vsize + ceil($vsize / 20 ); // make size 5% larger
// add a useless "\n" to new values. This makes the data file
// readable in any text editor. Useful when things go wrong :P
// update internal block lists
$this->_usedBlocks[$key] = array ($loc, $size, $vsize);
$this->_writeIdxEntry ($loc, $size, $vsize, $key);
// {{{ _getFreeBlock($reqsize)
* Returns a block location from the free list
* @param int $reqsize Requested size
* @returns mixed location of free block, false if there are no free blocks
function _getFreeBlock ($reqsize)
// check if we have any blocks to choose from
// iterate through the blocks in blockIndex to find
foreach ($this->_freeBlocks as $loc=> $size) {
// {{{ _freeUsedBlock($key)
* Places a used block on the free list, updates indicies accordingly
function _freeUsedBlock ($key)
unset ($this->_usedBlocks[$key]);
$this->_freeBlocks[$loc] = $size;
$this->_writeIdxEntry ($loc, $size);
* Creates a new database file if one does not exist. If it already exists,
* updates the last-updated timestamp on the database
* @param string $dbName the database to create
* @return object PEAR_Error on failure
if (!(@touch($dbName. '.dat') && @touch($dbName. '.idx'))) {
return $this->raiseError('Could not create database: '. $dbName);
// {{{ db_exists($dbName)
* Indicates whether a database with given name exists
* @param string $dbName the database name to check for existence
* @return boolean true if the database exists, false if it doesn't
* Removes a database from existence
* @param string $dbName the database name to drop
* @return object PEAR_Error on failure
* Removes the last open database from existence
* @return object PEAR_Error on failure
return $this->db_drop($this->_dbName);
* Check whether key exists
* @return boolean true if the key exists, false if it doesn't
return($this->isOpen() && isset ($this->_usedBlocks[$key]));
* Synchronizes an open database to disk
* Optimizes an open database
* Reads the entries in an index file
* Assumes that $this->_idxFP is valid and readable
// clear out old data if a previous database was opened
$this->_usedBlocks = array ();
$this->_freeBlocks = array ();
$usedBlocks = array (); // temporary used index
while (fscanf($this->_idxFP, '%u|%u|%u|%s', $loc, $size, $vsize, $key))
// is this an free block?
// check if this block had been previously marked as used
if (isset ($usedBlocks[$loc])) {
unset ($this->_usedBlocks[$usedBlocks[$loc]]);
unset ($usedBlocks[$loc]);
$this->_freeBlocks[$loc] = $size;
// check if this block had been previously marked as free
if (isset ($this->_freeBlocks[$loc])) {
unset ($this->_freeBlocks[$loc]);
$this->_usedBlocks[$key] = array ($loc, $size, $vsize);
$usedBlocks[$loc] = $key;
$key = ''; // reset key for the next iteration
* Rewrites the index file, removing free entries
* Assumes that $this->_idxFP is valid and writable
// move the file pointer to the beginning; ftruncate does not do this
if (isset ($this->_freeBlocks)) {
foreach ($this->_freeBlocks as $loc=> $size) {
$this->_writeIdxEntry ($loc,$size);
if (isset ($this->_usedBlocks)) {
foreach ($this->_usedBlocks as $key=> $block) {
// {{{ _writeIdxEntry($loc, $size, $vsize=NULL, $key=NULL)
* Writes a used block entry to an index file
function _writeIdxEntry ($loc, $size, $vsize=NULL , $key=NULL )
// write a free block entry
fputs($this->_idxFP, " $loc|$size\n" );
// write a used block entry
fputs($this->_idxFP, " $loc|$size|$vsize|$key\n" );
Documentation generated on Mon, 11 Mar 2019 14:59:54 -0400 by phpDocumentor 1.4.4. PEAR Logo Copyright © PHP Group 2004.
|