3 * A general file-based stack class
5 * @author Roland Haeder <webmaster@ship-simu.org>
7 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2013 Core Developer Team
8 * @license GNU GPL 3.0 or any newer version
9 * @link http://www.ship-simu.org
11 * This program is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program. If not, see <http://www.gnu.org/licenses/>.
24 class BaseFileStack extends BaseStacker {
26 * Magic for this stack
28 const STACK_MAGIC = 'STACKv0.1';
31 * Protected constructor
33 * @param $className Name of the class
36 protected function __construct ($className) {
37 // Call parent constructor
38 parent::__construct($className);
40 // Calculate header size
42 strlen(self::STACK_MAGIC) +
43 strlen(self::SEPARATOR_HEADER_DATA) +
45 strlen(self::SEPARATOR_HEADER_DATA) +
46 self::LENGTH_POSITION +
47 strlen(self::SEPARATOR_HEADER_ENTRIES)
50 // Init counters and gaps array
51 $this->initCountersGapsArray();
55 * Reads the file header
59 protected function readFileHeader () {
60 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
62 // First rewind to beginning as the header sits at the beginning ...
63 $this->getIteratorInstance()->rewind();
65 // Then read it (see constructor for calculation)
66 $data = $this->getIteratorInstance()->read($this->getHeaderSize());
67 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Read %d bytes (%d wanted).', __METHOD__, __LINE__, strlen($data), $this->getHeaderSize()));
69 // Have all requested bytes been read?
70 assert(strlen($data) == $this->getHeaderSize());
71 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
73 // Last character must be the separator
74 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] data(-1)=%s', __METHOD__, __LINE__, dechex(ord(substr($data, -1, 1)))));
75 assert(substr($data, -1, 1) == chr(self::SEPARATOR_HEADER_ENTRIES));
76 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
78 // Okay, then remove it
79 $data = substr($data, 0, -1);
81 // And update seek position
82 $this->updateSeekPosition();
89 * 2 => current seek position
91 $header = explode(chr(self::SEPARATOR_HEADER_DATA), $data);
94 $this->setHeader($header);
96 // Check if the array has only 3 elements
97 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] header(%d)=%s', __METHOD__, __LINE__, count($header), print_r($header, TRUE)));
98 assert(count($header) == 3);
99 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
102 assert($header[0] == self::STACK_MAGIC);
103 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
105 // Check length of count and seek position
106 assert(strlen($header[1]) == self::LENGTH_COUNT);
107 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
108 assert(strlen($header[2]) == self::LENGTH_POSITION);
109 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
111 // Decode count and seek position
112 $header[1] = hex2bin($header[1]);
113 $header[2] = hex2bin($header[2]);
115 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
119 * Flushes the file header
123 protected function flushFileHeader () {
124 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
126 // Put all informations together
127 $header = sprintf('%s%s%s%s%s%s',
131 // Separator magic<->count
132 chr(self::SEPARATOR_HEADER_DATA),
134 // Total entries (will be zero) and pad it to 20 chars
135 str_pad($this->dec2hex($this->getCounter()), self::LENGTH_COUNT, '0', STR_PAD_LEFT),
137 // Separator count<->seek position
138 chr(self::SEPARATOR_HEADER_DATA),
140 // Position (will be zero)
141 str_pad($this->dec2hex($this->getSeekPosition(), 2), self::LENGTH_POSITION, '0', STR_PAD_LEFT),
143 // Separator position<->entries
144 chr(self::SEPARATOR_HEADER_ENTRIES)
147 // Write it to disk (header is always at seek position 0)
148 $this->writeData(0, $header, FALSE);
150 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
154 * Analyzes entries in stack file. This will count all found (and valid)
155 * entries, mark invalid as damaged and count gaps ("fragmentation"). If
156 * only gaps are found, the file is considered as "virgin" (no entries).
160 private function analyzeFile () {
161 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
163 // Make sure the file is initialized
164 assert($this->isFileInitialized());
166 // Init counters and gaps array
167 $this->initCountersGapsArray();
169 // Output message (as this may take some time)
170 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Analyzing file structure ... (this may take some time)', __METHOD__, __LINE__));
172 // First rewind to the begining
173 $this->getIteratorInstance()->rewind();
175 // Then try to load all entries
176 while ($this->getIteratorInstance()->valid()) {
178 $this->getIteratorInstance()->next();
181 $current = $this->getIteratorInstance()->current();
184 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] current=%s', __METHOD__, __LINE__, print_r($current, TRUE)));
187 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
191 * Initializes this file-based stack.
193 * @param $fileName File name of this stack
194 * @param $type Type of this stack (e.g. url_source for URL sources)
196 * @todo Currently the stack file is not cached, please implement a memory-handling class and if enough RAM is found, cache the whole stack file.
198 protected function initFileStack ($fileName, $type) {
199 // Get a stack file instance
200 $fileInstance = ObjectFactory::createObjectByConfiguredName('stack_file_class', array($fileName));
202 // Get iterator instance
203 $iteratorInstance = ObjectFactory::createObjectByConfiguredName('file_io_iterator_class', array($fileInstance, $this));
205 // Is the instance implementing the right interface?
206 assert($iteratorInstance instanceof SeekableWritableFileIterator);
209 $this->setIteratorInstance($iteratorInstance);
211 // Is the file's header initialized?
212 if (!$this->isFileHeaderInitialized()) {
213 // No, then create it (which may pre-allocate the stack)
214 $this->createFileHeader();
216 // And pre-allocate a bit
217 $this->preAllocateFile('file_stack');
220 // Load the file header
221 $this->readFileHeader();
223 // Count all entries in file
224 $this->analyzeFile();
227 * Get stack index instance. This can be used for faster
228 * "defragmentation" and startup.
230 $indexInstance = FileStackIndexFactory::createFileStackIndexInstance($fileName, $type);
233 $this->setIndexInstance($indexInstance);
237 * Adds a value to given stack
239 * @param $stackerName Name of the stack
240 * @param $value Value to add to this stacker
242 * @throws FullStackerException If the stack is full
244 protected function addValue ($stackerName, $value) {
246 if ($this->isStackFull($stackerName)) {
248 throw new FullStackerException(array($this, $stackerName, $value), self::EXCEPTION_STACKER_IS_FULL);
251 // Now add the value to the stack
252 $this->partialStub('stackerName=' . $stackerName . ',value[]=' . gettype($value));
256 * Get last value from named stacker
258 * @param $stackerName Name of the stack
259 * @return $value Value of last added value
260 * @throws EmptyStackerException If the stack is empty
262 protected function getLastValue ($stackerName) {
263 // Is the stack not yet initialized or full?
264 if ($this->isStackEmpty($stackerName)) {
265 // Throw an exception
266 throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
269 // Now get the last value
270 $this->partialStub('stackerName=' . $stackerName);
278 * Get first value from named stacker
280 * @param $stackerName Name of the stack
281 * @return $value Value of last added value
282 * @throws EmptyStackerException If the stack is empty
284 protected function getFirstValue ($stackerName) {
285 // Is the stack not yet initialized or full?
286 if ($this->isStackEmpty($stackerName)) {
287 // Throw an exception
288 throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
291 // Now get the first value
292 $this->partialStub('stackerName=' . $stackerName);
300 * "Pops" last entry from stack
302 * @param $stackerName Name of the stack
303 * @return $value Value "poped" from array
304 * @throws EmptyStackerException If the stack is empty
306 protected function popLast ($stackerName) {
307 // Is the stack not yet initialized or full?
308 if ($this->isStackEmpty($stackerName)) {
309 // Throw an exception
310 throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
313 // Now, remove the last entry, we don't care about the return value here, see elseif() block above
314 $this->partialStub('stackerName=' . $stackerName);
319 * "Pops" first entry from stack
321 * @param $stackerName Name of the stack
322 * @return $value Value "shifted" from array
323 * @throws EmptyStackerException If the named stacker is empty
325 protected function popFirst ($stackerName) {
326 // Is the stack not yet initialized or full?
327 if ($this->isStackEmpty($stackerName)) {
328 // Throw an exception
329 throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
332 // Now, remove the last entry, we don't care about the return value here, see elseif() block above
333 $this->partialStub('stackerName=' . $stackerName);
338 * Checks whether the given stack is full
340 * @param $stackerName Name of the stack
341 * @return $isFull Whether the stack is full
343 protected function isStackFull ($stackerName) {
344 // File-based stacks will only run full if the disk space is low.
345 // @TODO Please implement this, returning FALSE
353 * Checks whether the given stack is empty
355 * @param $stackerName Name of the stack
356 * @return $isEmpty Whether the stack is empty
357 * @throws NoStackerException If given stack is missing
359 public function isStackEmpty ($stackerName) {
360 // So, is the stack empty?
361 $isEmpty = (($this->getStackCount($stackerName)) == 0);
368 * Initializes given stacker
370 * @param $stackerName Name of the stack
371 * @param $forceReInit Force re-initialization
373 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
375 public function initStack ($stackerName, $forceReInit = FALSE) {
376 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
380 * Initializes all stacks
383 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
385 public function initStacks (array $stacks, $forceReInit = FALSE) {
386 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
390 * Checks whether the given stack is initialized (set in array $stackers)
392 * @param $stackerName Name of the stack
393 * @return $isInitialized Whether the stack is initialized
394 * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
396 public function isStackInitialized ($stackerName) {
397 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
401 * Getter for size of given stack (array count)
403 * @param $stackerName Name of the stack
404 * @return $count Size of stack (array count)
406 public function getStackCount ($stackerName) {
407 // Now, simply return the found count value, this must be up-to-date then!
408 return $this->getCounter();
412 * Calculates minimum length for one entry/block
414 * @return $length Minimum length for one entry/block
416 public function caluclateMinimumBlockLength () {
418 $length = self::getHashLength() + strlen(chr(self::SEPARATOR_HASH_NAME)) + self::LENGTH_NAME + 1 + strlen(self::getBlockSeparator());