3 * A general binary file class
5 * @author Roland Haeder <webmaster@ship-simu.org>
7 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2015 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 BaseBinaryFile extends BaseAbstractFile {
26 * Separator for header data
28 const SEPARATOR_HEADER_DATA = 0x01;
31 * Separator header->entries
33 const SEPARATOR_HEADER_ENTRIES = 0x02;
36 * Separator group->hash
38 const SEPARATOR_GROUP_HASH = 0x03;
41 * Separator hash->value
43 const SEPARATOR_HASH_VALUE = 0x04;
46 * Separator entry->entry
48 const SEPARATOR_ENTRIES = 0x05;
51 * Separator type->position
53 const SEPARATOR_TYPE_POSITION = 0x06;
58 const LENGTH_COUNT = 20;
63 const LENGTH_POSITION = 20;
68 const LENGTH_GROUP = 10;
71 * Maximum length of entry type
73 const LENGTH_TYPE = 20;
75 //***** Array elements for 'gaps' array *****
80 const GAPS_INDEX_START = 'start';
85 const GAPS_INDEX_END = 'end';
88 * Current seek position
90 private $seekPosition = 0;
95 private $headerSize = 0;
100 private $header = array();
103 * Seek positions for gaps ("fragmentation")
105 private $gaps = array();
108 * Seek positions for damaged entries (e.g. mismatching hash sum, ...)
110 private $damagedEntries = array();
115 private $backBuffer = '';
118 * Currently loaded block (will be returned by current())
120 private $currentBlock = '';
123 * Protected constructor
125 * @param $className Name of the class
128 protected function __construct ($className) {
129 // Call parent constructor
130 parent::__construct($className);
132 // Init counters and gaps array
133 $this->initCountersGapsArray();
137 * Checks whether the abstracted file only contains gaps by counting all
138 * gaps' bytes together and compare it to total length.
140 * @return $isGapsOnly Whether the abstracted file only contains gaps
142 private function isFileOnlyGaps () {
143 // First/last gap found?
144 /* Only for debugging
145 if (isset($this->gaps[0])) {
146 // Output first and last gap
147 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] this->gaps[0]=%s,this->gaps[%s]=%s', __METHOD__, __LINE__, print_r($this->gaps[0], TRUE), (count($this->gaps) - 1), print_r($this->gaps[count($this->gaps) - 1], TRUE)));
151 // Now count every gap
153 foreach ($this->gaps as $gap) {
154 // Calculate size of found gap: end-start including both
155 $gapsSize += ($gap[self::GAPS_INDEX_END] - $gap[self::GAPS_INDEX_START]);
159 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] gapsSize=%s,this->headerSize=%s', __METHOD__, __LINE__, $gapsSize, $this->getHeaderSize()));
161 // Total gap size + header size must be same as file size
162 $isGapsOnly = (($this->getHeaderSize() + $gapsSize) == $this->getFileSize());
169 * Initializes counter for valid entries, arrays for damaged entries and
170 * an array for gap seek positions. If you call this method on your own,
171 * please re-analyze the file structure. So you are better to call
172 * analyzeFile() instead of this method.
176 public function initCountersGapsArray () {
177 // Init counter and seek position
178 $this->setCounter(0);
179 $this->setSeekPosition(0);
182 $this->gaps = array();
183 $this->damagedEntries = array();
187 * Getter for header size
189 * @return $totalEntries Size of file header
191 public final function getHeaderSize () {
193 return $this->headerSize;
197 * Setter for header size
199 * @param $headerSize Size of file header
202 public final function setHeaderSize ($headerSize) {
204 $this->headerSize = $headerSize;
208 * Getter for header array
210 * @return $totalEntries Size of file header
212 public final function getHeader () {
214 return $this->header;
220 * @param $header Array for a file header
223 public final function setHeader (array $header) {
225 $this->header = $header;
229 * Getter for seek position
231 * @return $seekPosition Current seek position (stored here in object)
233 public final function getSeekPosition () {
235 return $this->seekPosition;
239 * Setter for seek position
241 * @param $seekPosition Current seek position (stored here in object)
244 protected final function setSeekPosition ($seekPosition) {
246 $this->seekPosition = $seekPosition;
250 * Updates seekPosition attribute from file to avoid to much access on file.
254 public function updateSeekPosition () {
255 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
257 // Get key (= seek position)
258 $seekPosition = $this->key();
259 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Setting seekPosition=%s', __METHOD__, __LINE__, $seekPosition));
262 $this->setSeekPosition($seekPosition);
264 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
268 * Seeks to beginning of file, updates seek position in this object and
269 * flushes the header.
273 protected function rewindUpdateSeekPosition () {
274 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
276 // flushFileHeader must be callable
277 assert(is_callable(array($this, 'flushFileHeader')));
279 // Seek to beginning of file
282 // And update seek position ...
283 $this->updateSeekPosition();
285 // ... to write it back into the file
286 $this->flushFileHeader();
288 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
292 * Seeks to old position
296 protected function seekToOldPosition () {
297 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
299 // Seek to currently ("old") saved position
300 $this->seek($this->getSeekPosition());
302 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
306 * Checks whether the block separator has been found
308 * @param $str String to look in
309 * @return $isFound Whether the block separator has been found
311 public static function isBlockSeparatorFound ($str) {
313 $isFound = (strpos($str, chr(self::SEPARATOR_ENTRIES)) !== FALSE);
320 * Initializes the back-buffer by setting it to an empty string.
324 private function initBackBuffer () {
325 // Simply call the setter
326 $this->setBackBuffer('');
330 * Setter for backBuffer field
332 * @param $backBuffer Characters to "store" in back-buffer
335 private function setBackBuffer ($backBuffer) {
336 // Cast to string (so no arrays or objects)
337 $backBuffer = (string) $backBuffer;
340 $this->backBuffer = $backBuffer;
344 * Getter for backBuffer field
346 * @return $backBuffer Characters "stored" in back-buffer
348 private function getBackBuffer () {
349 return $this->backBuffer;
353 * Setter for currentBlock field
355 * @param $currentBlock Characters to set a currently loaded block
358 private function setCurrentBlock ($currentBlock) {
359 // Cast to string (so no arrays or objects)
360 $currentBlock = (string) $currentBlock;
363 $this->currentBlock = $currentBlock;
367 * Gets currently read data
369 * @return $current Currently read data
371 public function getCurrentBlock () {
373 return $this->currentBlock;
377 * Initializes this file class
379 * @param $fileName Name of this abstract file
382 protected function initFile ($fileName) {
383 // Get a file i/o pointer instance
384 $pointerInstance = ObjectFactory::createObjectByConfiguredName('file_raw_input_output_class', array($fileName));
386 // ... and set it here
387 $this->setPointerInstance($pointerInstance);
391 * Writes data at given position
393 * @param $seekPosition Seek position
394 * @param $data Data to be written
395 * @param $flushHeader Whether to flush the header (default: flush)
398 public function writeData ($seekPosition, $data, $flushHeader = TRUE) {
399 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] seekPosition=%s,data()=%s - CALLED!', __METHOD__, __LINE__, $seekPosition, strlen($data)));
401 // Write data at given position
402 $this->getPointerInstance()->writeAtPosition($seekPosition, $data);
404 // Update seek position
405 $this->updateSeekPosition();
408 if ($flushHeader === TRUE) {
410 $this->flushFileHeader();
412 // Seek to old position
413 $this->seekToOldPosition();
416 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
420 * Marks the currently loaded block as empty (with length of the block)
422 * @param $length Length of the block
425 protected function markCurrentBlockAsEmpty ($length) {
426 // Get current seek position
427 $currentPosition = $this->key();
429 // Now add it as gap entry
430 array_push($this->gaps, array(
431 self::GAPS_INDEX_START => ($currentPosition - $length),
432 self::GAPS_INDEX_END => $currentPosition,
437 * Checks whether the file header is initialized
439 * @return $isInitialized Whether the file header is initialized
441 public function isFileHeaderInitialized () {
442 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
444 // Default is not initialized
445 $isInitialized = FALSE;
447 // Is the file initialized?
448 if ($this->isFileInitialized()) {
449 // Some bytes has been written, so rewind to start of it.
450 $rewindStatus = $this->rewind();
451 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] rewindStatus=%s', __METHOD__, __LINE__, $rewindStatus));
453 // Is the rewind() call successfull?
454 if ($rewindStatus != 1) {
455 // Something bad happened
456 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Could not rewind().', __METHOD__, __LINE__));
460 $this->readFileHeader();
462 // The above method does already check the header
463 $isInitialized = TRUE;
467 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] isInitialized=%d - EXIT!', __METHOD__, __LINE__, intval($isInitialized)));
468 return $isInitialized;
472 * Checks whether the assigned file has been initialized
474 * @return $isInitialized Whether the file's size is zero
476 public function isFileInitialized () {
477 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
479 // Get it from iterator which holds the pointer instance. If FALSE is returned
480 $fileSize = $this->size();
481 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] fileSize=%s', __METHOD__, __LINE__, $fileSize));
484 * The returned file size should not be FALSE or NULL as this means
485 * that the pointer class does not work correctly.
487 assert(is_int($fileSize));
489 // Is more than 0 returned?
490 $isInitialized = ($fileSize > 0);
493 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] isInitialized=%d - EXIT!', __METHOD__, __LINE__, intval($isInitialized)));
494 return $isInitialized;
498 * Creates the assigned file
502 public function createFileHeader () {
503 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
505 // The file's header should not be initialized here
506 assert(!$this->isFileHeaderInitialized());
508 // Simple flush file header which will create it.
509 $this->flushFileHeader();
511 // Rewind seek position (to beginning of file) and update/flush file header
512 $this->rewindUpdateSeekPosition();
514 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
518 * Pre-allocates file (if enabled) with some space for later faster write access.
520 * @param $type Type of the file
523 public function preAllocateFile ($type) {
524 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
527 if ($this->getConfigInstance()->getConfigEntry($type . '_pre_allocate_enabled') != 'Y') {
529 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Not pre-allocating file.', __METHOD__, __LINE__));
531 // Don't continue here.
536 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Pre-allocating file ...', __METHOD__, __LINE__));
538 // Calculate minimum length for one entry
539 $minLengthEntry = $this->getBlockInstance()->calculateMinimumBlockLength();
540 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] minLengthEntry=%s', __METHOD__, __LINE__, $minLengthEntry));
542 // Calulcate seek position
543 $seekPosition = $minLengthEntry * $this->getConfigInstance()->getConfigEntry($type . '_pre_allocate_count');
544 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] seekPosition=%s', __METHOD__, __LINE__, $seekPosition));
546 // Now simply write a NUL there. This will pre-allocate the file.
547 $this->writeData($seekPosition, chr(0));
549 // Rewind seek position (to beginning of file) and update/flush file header
550 $this->rewindUpdateSeekPosition();
552 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
556 * Determines seek position
558 * @return $seekPosition Current seek position
560 public function determineSeekPosition () {
561 // Call pointer instance
562 return $this->getPointerInstance()->determineSeekPosition();
566 * Seek to given offset (default) or other possibilities as fseek() gives.
568 * @param $offset Offset to seek to (or used as "base" for other seeks)
569 * @param $whence Added to offset (default: only use offset to seek to)
570 * @return $status Status of file seek: 0 = success, -1 = failed
572 public function seek ($offset, $whence = SEEK_SET) {
573 // Call pointer instance
574 return $this->getPointerInstance()->seek($offset, $whence);
578 * Reads given amount of bytes from file.
580 * @param $bytes Amount of bytes to read
581 * @return $data Data read from file
583 public function read ($bytes = NULL) {
584 // $bytes shall be integer
585 assert(is_int($bytes));
587 // Call pointer instance
588 return $this->getPointerInstance()->read($bytes);
592 * Rewinds to the beginning of the file
594 * @return $status Status of this operation
596 public function rewind () {
597 // Call pointer instance
598 return $this->getPointerInstance()->rewind();
602 * Analyzes entries in index file. This will count all found (and valid)
603 * entries, mark invalid as damaged and count gaps ("fragmentation"). If
604 * only gaps are found, the file is considered as "virgin" (no entries).
608 public function analyzeFile () {
609 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
611 // Make sure the file is initialized
612 assert($this->isFileInitialized());
614 // Init counters and gaps array
615 $this->initCountersGapsArray();
617 // Output message (as this may take some time)
618 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Analyzing file structure ... (this may take some time)', __METHOD__, __LINE__));
620 // First rewind to the begining
623 // Then try to load all entries
624 while ($this->valid()) {
629 $current = $this->getCurrentBlock();
632 * If the block is empty, maybe the whole file is? This could mean
633 * that the file has been pre-allocated.
635 if (empty($current)) {
636 // Then skip this part
641 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] current()=%s', __METHOD__, __LINE__, strlen($current)));
644 // If the last read block is empty, check gaps
645 if (empty($current)) {
647 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Found a total of %s gaps.', __METHOD__, __LINE__, count($this->gaps)));
649 // Check gaps, if the whole file is empty.
650 if ($this->isFileOnlyGaps()) {
651 // Only gaps, so don't continue here.
656 * The above call has calculated a total size of all gaps. If the
657 * percentage of gaps passes a "soft" limit and last
658 * defragmentation is to far in the past, or if a "hard" limit has
659 * reached, run defragmentation.
661 if ($this->isDefragmentationNeeded()) {
662 // Run "defragmentation"
663 $this->doRunDefragmentation();
666 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
670 * Advances to next "block" of bytes
674 public function next () {
675 // Is there nothing to read?
676 if (!$this->valid()) {
682 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d] key()=%s', __FUNCTION__, __LINE__, $this->key()));
684 // Make sure the block instance is set
685 assert($this->getBlockInstance() instanceof CalculatableBlock);
687 // First calculate minimum block length
688 $length = $this->getBlockInstance()->calculateMinimumBlockLength();
689 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d] length=%s', __FUNCTION__, __LINE__, $length));
691 // Short be more than zero!
694 // Read possibly back-buffered bytes from previous call of next().
695 $data = $this->getBackBuffer();
698 * Read until a entry/block separator has been found. The next read
699 * "block" may not fit, so this loop will continue until the EOB or EOF
700 * has been reached whatever comes first.
702 while ((!$this->isEndOfFileReached()) && (!self::isBlockSeparatorFound($data))) {
703 // Then read the next possible block
704 $block = $this->read($length);
707 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d] block()=%s,length=%s', __FUNCTION__, __LINE__, strlen($block), $length));
710 if (strlen(trim($block)) == 0) {
711 // Mark this block as empty
712 $this->markCurrentBlockAsEmpty(strlen($block));
714 // Skip to next block
718 // At this block then
722 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d] data()=%s', __FUNCTION__, __LINE__, strlen($data)));
726 if ($this->isEndOfFileReached()) {
727 // Set whole data as current read block
728 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('Calling setCurrentBlock(' . strlen($data) . ') ...');
729 $this->setCurrentBlock($data);
731 // Then abort here silently
732 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('EOF reached.');
737 * Init back-buffer which is the data that has been found beyond the
740 $this->initBackBuffer();
743 $dataArray = explode(chr(self::SEPARATOR_ENTRIES), $data);
745 // This array must contain two elements
746 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('dataArray=' . print_r($dataArray, TRUE));
747 assert(count($dataArray) == 2);
749 // Left part is the actual block, right one the back-buffer data
750 $this->setCurrentBlock($dataArray[0]);
751 $this->setBackBuffer($dataArray[1]);
755 * Checks wether the current entry is valid (not at the end of the file).
756 * This method will return TRUE if an emptied (nulled) entry has been found.
758 * @return $isValid Whether the next entry is valid
760 public function valid () {
761 // Make sure the block instance is set
762 assert($this->getBlockInstance() instanceof Block);
764 // First calculate minimum block length
765 $length = $this->getBlockInstance()->calculateMinimumBlockLength();
767 // Short be more than zero!
770 // Get current seek position
771 $seekPosition = $this->key();
773 // Then try to read it
774 $data = $this->read($length);
776 // If some bytes could be read, all is fine
777 $isValid = ((is_string($data)) && (strlen($data) > 0));
780 $headerSize = $this->getHeaderSize();
782 // Is the seek position at or beyond the header?
783 if ($seekPosition >= $headerSize) {
784 // Seek back to old position
785 $this->seek($seekPosition);
787 // Seek directly behind the header
788 $this->seek($headerSize);
796 * Gets current seek position ("key").
798 * @return $key Current key in iteration
800 public function key () {
801 // Call pointer instance
802 return $this->getPointerInstance()->determineSeekPosition();
806 * Reads the file header
810 public function readFileHeader () {
811 // Make sure the block instance is set
812 assert($this->getBlockInstance() instanceof Block);
814 // Call block instance
815 $this->getBlockInstance()->readFileHeader();
819 * Flushes the file header
823 public function flushFileHeader () {
824 // Make sure the block instance is set
825 assert($this->getBlockInstance() instanceof Block);
827 // Call block instance
828 $this->getBlockInstance()->flushFileHeader();
832 * Searches for next suitable gap the given length of data can fit in
833 * including padding bytes.
835 * @param $length Length of raw data
836 * @return $seekPosition Found next gap's seek position
838 public function searchNextGap ($length) {
839 // If the file is only gaps, no need to seek
840 if ($this->isFileOnlyGaps()) {
841 // The first empty block is the first one right after the header
842 return ($this->getHeaderSize() + 1);
846 $this->partialStub('length=' . $length);