* @version 0.0.0 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2020 Core Developer Team * @license GNU GPL 3.0 or any newer version * @link http://www.ship-simu.org * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ abstract class BaseFileStack extends BaseStacker { // Exception codes const EXCEPTION_BAD_MAGIC = 0xe100; /** * Magic for this stack */ const STACK_MAGIC = 'STACKv0.1'; /** * Name of array index for gap position */ const ARRAY_INDEX_GAP_POSITION = 'gap'; /** * Name of array index for hash */ const ARRAY_INDEX_HASH = 'hash'; /** * Name of array index for length of raw data */ const ARRAY_INDEX_DATA_LENGTH = 'length'; /** * An instance of an Indexable class */ private $indexInstance = NULL; /** * Protected constructor * * @param $className Name of the class * @return void */ protected function __construct (string $className) { // Call parent constructor parent::__construct($className); } /** * Setter for Indexable instance * * @param $indexInstance An instance of an Indexable class * @return void */ protected final function setIndexInstance (Indexable $indexInstance) { $this->indexInstance = $indexInstance; } /** * Getter for Indexable instance * * @return $indexInstance An instance of an Indexable class */ public final function getIndexInstance () { return $this->indexInstance; } /** * Reads the file header * * @return void * @todo To hard assertions here, better rewrite them to exceptions * @throws UnexpectedValueException If header is not proper length * @throws InvalidMagicException If a bad magic was found */ public function readFileHeader () { // First rewind to beginning as the header sits at the beginning ... /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: CALLED!', __METHOD__, __LINE__)); $this->getIteratorInstance()->rewind(); // Then read it (see constructor for calculation) $data = $this->getIteratorInstance()->read($this->getIteratorInstance()->getHeaderSize()); /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: Read %d bytes (%d wanted).', strlen($data), $this->getIteratorInstance()->getHeaderSize())); // Have all requested bytes been read? if (strlen($data) != $this->getIteratorInstance()->getHeaderSize()) { // Bad data length throw new UnexpectedValueException(sprintf('data(%d)=%s does not match iteratorInstance->headerSize=%d', strlen($data), $data, $this->getIteratorInstance()->getHeaderSize() )); } // Last character must be the separator /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: data(-1)=%s', dechex(ord(substr($data, -1, 1))))); if (substr($data, -1, 1) !== chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES)) { // Not valid separator throw new UnexpectedValueException(sprintf('data=%s does not have separator=%s at the end.', $data, BaseBinaryFile::SEPARATOR_HEADER_ENTRIES )); } // Okay, then remove it $data = substr($data, 0, -1); // And update seek position $this->getIteratorInstance()->updateSeekPosition(); /* * Now split it: * * 0 => magic * 1 => total entries * 2 => current seek position */ $header = explode(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA), $data); // Set header here $this->getIteratorInstance()->setHeader($header); // Check if the array has only 3 elements /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: header(%d)=%s', count($header), print_r($header, true))); if (count($header) != 3) { // Header array count is not expected throw new UnexpectedValueException(sprintf('data=%s has %d elements, expected 3', $data, count($header) )); } elseif ($header[0] != self::STACK_MAGIC) { // Bad magic throw new InvalidMagicException($data, self::EXCEPTION_BAD_MAGIC); } // Check length of count and seek position if (strlen($header[1]) != BaseBinaryFile::LENGTH_COUNT) { // Count length not valid throw new UnexpectedValueException(sprintf('header[1](%d)=%s is not expected %d length', strlen($header[1]), $header[1], BaseBinaryFile::LENGTH_COUNT )); } elseif (strlen($header[1]) != BaseBinaryFile::LENGTH_POSITION) { // Position length not valid throw new UnexpectedValueException(sprintf('header[2](%d)=%s is not expected %d length', strlen($header[1]), $header[1], BaseBinaryFile::LENGTH_POSITION )); } // Decode count and seek position $header[1] = hex2bin($header[1]); $header[2] = hex2bin($header[2]); // Trace message /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: EXIT!', __METHOD__, __LINE__)); } /** * Flushes the file header * * @return void */ public function flushFileHeader () { // Put all informations together /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: CALLED!', __METHOD__, __LINE__)); $header = sprintf('%s%s%s%s%s%s', // Magic self::STACK_MAGIC, // Separator magic<->count chr(BaseBinaryFile::SEPARATOR_HEADER_DATA), // Total entries (will be zero) and pad it to 20 chars str_pad(StringUtils::dec2hex($this->getIteratorInstance()->getCounter()), BaseBinaryFile::LENGTH_COUNT, '0', STR_PAD_LEFT), // Separator count<->seek position chr(BaseBinaryFile::SEPARATOR_HEADER_DATA), // Position (will be zero) str_pad(StringUtils::dec2hex($this->getIteratorInstance()->getSeekPosition(), 2), BaseBinaryFile::LENGTH_POSITION, '0', STR_PAD_LEFT), // Separator position<->entries chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES) ); // Write it to disk (header is always at seek position 0) $this->getIteratorInstance()->writeData(0, $header, false); // Trace message /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: EXIT!', __METHOD__, __LINE__)); } /** * Initializes this file-based stack. * * @param $fileInfoInstance An instance of a SplFileInfo class * @param $type Type of this stack (e.g. url_source for URL sources) * @return void * @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. */ protected function initFileStack (SplFileInfo $fileInfoInstance, string $type) { // Get a stack file instance /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: fileInfoInstance=%s,type=%s - CALLED!', $fileInfoInstance, $type)); $fileInstance = ObjectFactory::createObjectByConfiguredName('stack_file_class', array($fileInfoInstance, $this)); // Get iterator instance $iteratorInstance = ObjectFactory::createObjectByConfiguredName('file_iterator_class', array($fileInstance)); // Set iterator here $this->setIteratorInstance($iteratorInstance); // Calculate header size $this->getIteratorInstance()->setHeaderSize( strlen(self::STACK_MAGIC) + strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA)) + BaseBinaryFile::LENGTH_COUNT + strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA)) + BaseBinaryFile::LENGTH_POSITION + strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES)) ); // Init counters and gaps array $this->getIteratorInstance()->initCountersGapsArray(); // Is the file's header initialized? if (!$this->getIteratorInstance()->isFileHeaderInitialized()) { // No, then create it (which may pre-allocate the stack) $this->getIteratorInstance()->createFileHeader(); // And pre-allocate a bit $this->getIteratorInstance()->preAllocateFile('file_stack'); } // Load the file header $this->readFileHeader(); // Count all entries in file $this->getIteratorInstance()->analyzeFile(); /* * Get stack index instance. This can be used for faster * "defragmentation" and startup. */ $indexInstance = FileStackIndexFactory::createFileStackIndexInstance($fileInfoInstance, $type); // And set it here $this->setIndexInstance($indexInstance); } /** * Adds a value to given stack * * @param $stackerName Name of the stack * @param $value Value to add to this stacker * @return void * @throws FullStackerException If the stack is full * @throws InvalidArgumentException Not all variable types are wanted here */ protected function addValue (string $stackerName, $value) { // Do some tests /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('stackerName=%s,value[%s]=%s - CALLED!', $stackerName, gettype($value), print_r($value, true))); if ($this->isStackFull($stackerName)) { // Stacker is full throw new FullStackerException(array($this, $stackerName, $value), self::EXCEPTION_STACKER_IS_FULL); } elseif (is_resource($value) || is_object($value)) { // Not wanted type throw new InvalidArgumentException(sprintf('value[]=%s is not supported', gettype($value))); } /* * Now add the value to the file stack which returns gap position, a * hash and length of the raw data. */ $data = $this->getIteratorInstance()->writeValueToFile($stackerName, $value); // Add the hash and gap position to the index $this->getIndexInstance()->addHashToIndex($stackerName, $data); } /** * Get last value from named stacker * * @param $stackerName Name of the stack * @return $value Value of last added value * @throws EmptyStackerException If the stack is empty */ protected function getLastValue (string $stackerName) { // Is the stack not yet initialized or full? if ($this->isStackEmpty($stackerName)) { // Throw an exception throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY); } // END - if // Now get the last value /* NOISY-DEBUG: */ $this->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName); $value = NULL; // Return it return $value; } /** * Get first value from named stacker * * @param $stackerName Name of the stack * @return $value Value of last added value * @throws EmptyStackerException If the stack is empty */ protected function getFirstValue (string $stackerName) { // Is the stack not yet initialized or full? if ($this->isStackEmpty($stackerName)) { // Throw an exception throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY); } // END - if // Now get the first value /* NOISY-DEBUG: */ $this->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName); $value = NULL; // Return it return $value; } /** * "Pops" last entry from stack * * @param $stackerName Name of the stack * @return $value Value "poped" from array * @throws EmptyStackerException If the stack is empty */ protected function popLast (string $stackerName) { // Is the stack not yet initialized or full? if ($this->isStackEmpty($stackerName)) { // Throw an exception throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY); } // END - if // Now, remove the last entry, we don't care about the return value here, see elseif() block above /* NOISY-DEBUG: */ $this->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName); return NULL; } /** * "Pops" first entry from stack * * @param $stackerName Name of the stack * @return $value Value "shifted" from array * @throws EmptyStackerException If the named stacker is empty */ protected function popFirst (string $stackerName) { // Is the stack not yet initialized or full? if ($this->isStackEmpty($stackerName)) { // Throw an exception throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY); } // END - if // Now, remove the last entry, we don't care about the return value here, see elseif() block above /* NOISY-DEBUG: */ $this->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName); return NULL; } /** * Checks whether the given stack is full * * @param $stackerName Name of the stack * @return $isFull Whether the stack is full */ protected function isStackFull (string $stackerName) { // File-based stacks will only run full if the disk space is low. // @TODO Please implement this, returning false $isFull = false; // Return result return $isFull; } /** * Checks whether the given stack is empty * * @param $stackerName Name of the stack * @return $isEmpty Whether the stack is empty * @throws NoStackerException If given stack is missing */ public function isStackEmpty (string $stackerName) { // So, is the stack empty? $isEmpty = (($this->getStackCount($stackerName)) == 0); // Return result return $isEmpty; } /** * Initializes given stacker * * @param $stackerName Name of the stack * @param $forceReInit Force re-initialization * @return void * @throws UnsupportedOperationException This method is not (and maybe never will be) supported */ public function initStack (string $stackerName, bool $forceReInit = false) { throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION); } /** * Initializes all stacks * * @return void * @throws UnsupportedOperationException This method is not (and maybe never will be) supported */ public function initStacks (array $stacks, bool $forceReInit = false) { throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION); } /** * Checks whether the given stack is initialized (set in array $stackers) * * @param $stackerName Name of the stack * @return $isInitialized Whether the stack is initialized * @throws UnsupportedOperationException This method is not (and maybe never will be) supported */ public function isStackInitialized (string $stackerName) { throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION); } /** * Determines whether the EOF has been reached * * @return $isEndOfFileReached Whether the EOF has been reached * @throws UnsupportedOperationException This method is not (and maybe never will be) supported */ public function isEndOfFileReached () { throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION); } /** * Getter for size of given stack (array count) * * @param $stackerName Name of the stack * @return $count Size of stack (array count) */ public function getStackCount (string $stackerName) { // Now, simply return the found count value, this must be up-to-date then! return $this->getIteratorInstance()->getCounter(); } /** * Calculates minimum length for one entry/block * * @return $length Minimum length for one entry/block */ public function calculateMinimumBlockLength () { // Calulcate it $length = // Length of entry group BaseBinaryFile::LENGTH_GROUP + strlen(chr(BaseBinaryFile::SEPARATOR_GROUP_HASH)) + // Hash + value self::getHashLength() + strlen(chr(BaseBinaryFile::SEPARATOR_HASH_VALUE)) + 1 + // Final separator strlen(chr(BaseBinaryFile::SEPARATOR_ENTRIES)); // Return it return $length; } /** * Initializes counter for valid entries, arrays for damaged entries and * an array for gap seek positions. If you call this method on your own, * please re-analyze the file structure. So you are better to call * analyzeFile() instead of this method. * * @return void * @throws UnsupportedOperationException This method is not (and maybe never will be) supported */ public function initCountersGapsArray () { throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION); } /** * Getter for header size * * @return $totalEntries Size of file header * @throws UnsupportedOperationException This method is not (and maybe never will be) supported */ public final function getHeaderSize () { throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION); } /** * Setter for header size * * @param $headerSize Size of file header * @return void * @throws UnsupportedOperationException This method is not (and maybe never will be) supported */ public final function setHeaderSize (int $headerSize) { throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION); } /** * Getter for header array * * @return $totalEntries Size of file header * @throws UnsupportedOperationException This method is not (and maybe never will be) supported */ public final function getHeader () { throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION); } /** * Setter for header * * @param $header Array for a file header * @return void * @throws UnsupportedOperationException This method is not (and maybe never will be) supported */ public final function setHeader (array $header) { throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION); } /** * Updates seekPosition attribute from file to avoid to much access on file. * * @return void * @throws UnsupportedOperationException This method is not (and maybe never will be) supported */ public function updateSeekPosition () { throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION); } /** * Getter for total entries * * @return $totalEntries Total entries in this file * @throws UnsupportedOperationException This method is not (and maybe never will be) supported */ public final function getCounter () { throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION); } /** * Writes data at given position * * @param $seekPosition Seek position * @param $data Data to be written * @param $flushHeader Whether to flush the header (default: flush) * @return void * @throws UnsupportedOperationException This method is not (and maybe never will be) supported */ public function writeData (int $seekPosition, string $data, bool $flushHeader = true) { /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: seekPosition=%s,data[]=%s,flushHeader=%d', $seekPosition, gettype($data), intval($flushHeader))); throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION); } /** * Writes given value to the file and returns a hash and gap position for it * * @param $groupId Group identifier * @param $value Value to be added to the stack * @return $data Hash and gap position * @throws UnsupportedOperationException This method is not (and maybe never will be) supported */ public function writeValueToFile (string $groupId, $value) { /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: groupId=%s,value[%s]=%s', $groupId, gettype($value), print_r($value, true))); throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION); } /** * Searches for next suitable gap the given length of data can fit in * including padding bytes. * * @param $length Length of raw data * @return $seekPosition Found next gap's seek position * @throws UnsupportedOperationException This method is not (and maybe never will be) supported */ public function searchNextGap (int $length) { // Not supported here /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: length=%d - CALLED!', $length)); throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION); } /** * "Getter" for file size * * @return $fileSize Size of currently loaded file */ public function getFileSize () { // Call iterator's method return $this->getIteratorInstance()->getFileSize(); } /** * Writes given raw data to the file and returns a gap position and length * * @param $groupId Group identifier * @param $hash Hash from encoded value * @param $encoded Encoded value to be written to the file * @return $data Gap position and length of the raw data */ public function writeDataToFreeGap (string $groupId, string $hash, string $encoded) { // Raw data been written to the file /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: groupId=%s,hash=%s,encoded()=%d - CALLED!', $groupId, $hash, strlen($encoded))); $rawData = sprintf('%s%s%s%s%s', $groupId, BaseBinaryFile::SEPARATOR_GROUP_HASH, hex2bin($hash), BaseBinaryFile::SEPARATOR_HASH_VALUE, $encoded ); // Search for next free gap /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: groupId=%s,hash=%s,rawData()=%d', $groupId, $hash, strlen($rawData))); $gapPosition = $this->getIteratorInstance()->searchNextGap(strlen($rawData)); // Gap position cannot be smaller than header length + 1 if ($gapPosition <= $this->getIteratorInstance()->getHeaderSize()) { // Improper gap position throw new UnexpectedValueException(sprintf('gapPosition[%s]=%d is not larger than headerSize=%d', gettype($gapPosition), $gapPosition, $this->getIteratorInstance()->getHeaderSize() )); } // Then write the data at that gap /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: groupId=%s,hash=%s,gapPosition=%s', $groupId, $hash, $gapPosition)); $this->getIteratorInstance()->writeData($gapPosition, $rawData); // Return gap position, hash and length of raw data /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: groupId=%s,hash=%s,rawData()=%d - EXIT!', $groupId, $hash, strlen($rawData))); return [ self::ARRAY_INDEX_GAP_POSITION => $gapPosition, self::ARRAY_INDEX_HASH => $hash, self::ARRAY_INDEX_DATA_LENGTH => strlen($rawData), ]; } }