3 * A general binary file class
5 * @author Roland Haeder <webmaster@ship-simu.org>
7 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2014 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 BaseFile {
26 * Separator for header data
28 const SEPARATOR_HEADER_DATA = 0x01;
31 * Separator header->entries
33 const SEPARATOR_HEADER_ENTRIES = 0x02;
36 * Separator hash->name
38 const SEPARATOR_HASH_NAME = 0x03;
41 * Separator entry->entry
43 const SEPARATOR_ENTRIES = 0x04;
46 * Separator type->position
48 const SEPARATOR_TYPE_POSITION = 0x05;
53 const LENGTH_COUNT = 20;
58 const LENGTH_POSITION = 20;
63 const LENGTH_NAME = 10;
66 * Maximum length of entry type
68 const LENGTH_TYPE = 20;
70 //***** Array elements for 'gaps' array *****
75 const GAPS_INDEX_START = 'start';
80 const GAPS_INDEX_END = 'end';
83 * Current seek position
85 private $seekPosition = 0;
90 private $headerSize = 0;
95 private $header = array();
98 * Seek positions for gaps ("fragmentation")
100 private $gaps = array();
103 * Seek positions for damaged entries (e.g. mismatching hash sum, ...)
105 private $damagedEntries = array();
110 private $backBuffer = '';
113 * Currently loaded block (will be returned by current())
115 private $currentBlock = '';
118 * Protected constructor
120 * @param $className Name of the class
123 protected function __construct ($className) {
124 // Call parent constructor
125 parent::__construct($className);
127 // Init counters and gaps array
128 $this->initCountersGapsArray();
132 * Checks whether the abstracted file only contains gaps by counting all
133 * gaps' bytes together and compare it to total length.
135 * @return $isGapsOnly Whether the abstracted file only contains gaps
137 private function isFileOnlyGaps () {
138 // First/last gap found?
139 /* Only for debugging
140 if (isset($this->gaps[0])) {
141 // Output first and last gap
142 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)));
146 // Now count every gap
148 foreach ($this->gaps as $gap) {
149 // Calculate size of found gap: end-start including both
150 $gapsSize += ($gap[self::GAPS_INDEX_END] - $gap[self::GAPS_INDEX_START]);
154 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] gapsSize=%s,this->headerSize=%s', __METHOD__, __LINE__, $gapsSize, $this->getHeaderSize()));
156 // Total gap size + header size must be same as file size
157 $isGapsOnly = (($this->getHeaderSize() + $gapsSize) == $this->getFileSize());
164 * Initializes counter for valid entries, arrays for damaged entries and
165 * an array for gap seek positions. If you call this method on your own,
166 * please re-analyze the file structure. So you are better to call
167 * analyzeFile() instead of this method.
171 public function initCountersGapsArray () {
172 // Init counter and seek position
173 $this->setCounter(0);
174 $this->setSeekPosition(0);
177 $this->gaps = array();
178 $this->damagedEntries = array();
182 * Getter for header size
184 * @return $totalEntries Size of file header
186 public final function getHeaderSize () {
188 return $this->headerSize;
192 * Setter for header size
194 * @param $headerSize Size of file header
197 public final function setHeaderSize ($headerSize) {
199 $this->headerSize = $headerSize;
203 * Getter for header array
205 * @return $totalEntries Size of file header
207 public final function getHeader () {
209 return $this->header;
215 * @param $header Array for a file header
218 public final function setHeader (array $header) {
220 $this->header = $header;
224 * Getter for seek position
226 * @return $seekPosition Current seek position (stored here in object)
228 public final function getSeekPosition () {
230 return $this->seekPosition;
234 * Setter for seek position
236 * @param $seekPosition Current seek position (stored here in object)
239 protected final function setSeekPosition ($seekPosition) {
241 $this->seekPosition = $seekPosition;
245 * Updates seekPosition attribute from file to avoid to much access on file.
249 public function updateSeekPosition () {
250 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
252 // Get key (= seek position)
253 $seekPosition = $this->key();
254 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Setting seekPosition=%s', __METHOD__, __LINE__, $seekPosition));
257 $this->setSeekPosition($seekPosition);
259 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
263 * Seeks to beginning of file, updates seek position in this object and
264 * flushes the header.
268 protected function rewindUpdateSeekPosition () {
269 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
271 // flushFileHeader must be callable
272 assert(is_callable(array($this, 'flushFileHeader')));
274 // Seek to beginning of file
277 // And update seek position ...
278 $this->updateSeekPosition();
280 // ... to write it back into the file
281 $this->flushFileHeader();
283 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
287 * Seeks to old position
291 protected function seekToOldPosition () {
292 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
294 // Seek to currently ("old") saved position
295 $this->seek($this->getSeekPosition());
297 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
301 * Checks whether the block separator has been found
303 * @param $str String to look in
304 * @return $isFound Whether the block separator has been found
306 public static function isBlockSeparatorFound ($str) {
308 $isFound = (strpos($str, chr(self::SEPARATOR_ENTRIES)) !== FALSE);
315 * Initializes the back-buffer by setting it to an empty string.
319 private function initBackBuffer () {
320 // Simply call the setter
321 $this->setBackBuffer('');
325 * Setter for backBuffer field
327 * @param $backBuffer Characters to "store" in back-buffer
330 private function setBackBuffer ($backBuffer) {
331 // Cast to string (so no arrays or objects)
332 $backBuffer = (string) $backBuffer;
335 $this->backBuffer = $backBuffer;
339 * Getter for backBuffer field
341 * @return $backBuffer Characters "stored" in back-buffer
343 private function getBackBuffer () {
344 return $this->backBuffer;
348 * Setter for currentBlock field
350 * @param $currentBlock Characters to set a currently loaded block
353 private function setCurrentBlock ($currentBlock) {
354 // Cast to string (so no arrays or objects)
355 $currentBlock = (string) $currentBlock;
358 $this->currentBlock = $currentBlock;
362 * Gets currently read data
364 * @return $current Currently read data
366 public function getCurrentBlock () {
368 return $this->currentBlock;
372 * Initializes this file class
374 * @param $fileName Name of this abstract file
377 protected function initFile ($fileName) {
378 // Get a file i/o pointer instance
379 $pointerInstance = ObjectFactory::createObjectByConfiguredName('file_raw_input_output_class', array($fileName));
381 // ... and set it here
382 $this->setPointerInstance($pointerInstance);
386 * Writes data at given position
388 * @param $seekPosition Seek position
389 * @param $data Data to be written
390 * @param $flushHeader Whether to flush the header (default: flush)
393 public function writeData ($seekPosition, $data, $flushHeader = TRUE) {
394 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] seekPosition=%s,data()=%s - CALLED!', __METHOD__, __LINE__, $seekPosition, strlen($data)));
396 // Write data at given position
397 $this->getPointerInstance()->writeAtPosition($seekPosition, $data);
399 // Update seek position
400 $this->updateSeekPosition();
403 if ($flushHeader === TRUE) {
405 $this->flushFileHeader();
407 // Seek to old position
408 $this->seekToOldPosition();
411 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
415 * Marks the currently loaded block as empty (with length of the block)
417 * @param $length Length of the block
420 protected function markCurrentBlockAsEmpty ($length) {
421 // Get current seek position
422 $currentPosition = $this->key();
424 // Now add it as gap entry
425 array_push($this->gaps, array(
426 self::GAPS_INDEX_START => ($currentPosition - $length),
427 self::GAPS_INDEX_END => $currentPosition,
432 * Checks whether the file header is initialized
434 * @return $isInitialized Whether the file header is initialized
436 public function isFileHeaderInitialized () {
437 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
439 // Default is not initialized
440 $isInitialized = FALSE;
442 // Is the file initialized?
443 if ($this->isFileInitialized()) {
444 // Some bytes has been written, so rewind to start of it.
445 $rewindStatus = $this->rewind();
446 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] rewindStatus=%s', __METHOD__, __LINE__, $rewindStatus));
448 // Is the rewind() call successfull?
449 if ($rewindStatus != 1) {
450 // Something bad happened
451 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Could not rewind().', __METHOD__, __LINE__));
455 $this->readFileHeader();
457 // The above method does already check the header
458 $isInitialized = TRUE;
462 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] isInitialized=%d - EXIT!', __METHOD__, __LINE__, intval($isInitialized)));
463 return $isInitialized;
467 * Checks whether the assigned file has been initialized
469 * @return $isInitialized Whether the file's size is zero
471 public function isFileInitialized () {
472 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
474 // Get it from iterator which holds the pointer instance. If FALSE is returned
475 $fileSize = $this->size();
476 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] fileSize=%s', __METHOD__, __LINE__, $fileSize));
479 * The returned file size should not be FALSE or NULL as this means
480 * that the pointer class does not work correctly.
482 assert(is_int($fileSize));
484 // Is more than 0 returned?
485 $isInitialized = ($fileSize > 0);
488 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] isInitialized=%d - EXIT!', __METHOD__, __LINE__, intval($isInitialized)));
489 return $isInitialized;
493 * Creates the assigned file
497 public function createFileHeader () {
498 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
500 // The file's header should not be initialized here
501 assert(!$this->isFileHeaderInitialized());
503 // Simple flush file header which will create it.
504 $this->flushFileHeader();
506 // Rewind seek position (to beginning of file) and update/flush file header
507 $this->rewindUpdateSeekPosition();
509 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
513 * Pre-allocates file (if enabled) with some space for later faster write access.
515 * @param $type Type of the file
518 public function preAllocateFile ($type) {
519 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
522 if ($this->getConfigInstance()->getConfigEntry($type . '_pre_allocate_enabled') != 'Y') {
524 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Not pre-allocating file.', __METHOD__, __LINE__));
526 // Don't continue here.
531 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Pre-allocating file ...', __METHOD__, __LINE__));
533 // Calculate minimum length for one entry
534 $minLengthEntry = $this->getBlockInstance()->calculateMinimumBlockLength();
535 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] minLengthEntry=%s', __METHOD__, __LINE__, $minLengthEntry));
537 // Calulcate seek position
538 $seekPosition = $minLengthEntry * $this->getConfigInstance()->getConfigEntry($type . '_pre_allocate_count');
539 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] seekPosition=%s', __METHOD__, __LINE__, $seekPosition));
541 // Now simply write a NUL there. This will pre-allocate the file.
542 $this->writeData($seekPosition, chr(0));
544 // Rewind seek position (to beginning of file) and update/flush file header
545 $this->rewindUpdateSeekPosition();
547 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
551 * Determines seek position
553 * @return $seekPosition Current seek position
555 public function determineSeekPosition () {
556 // Call pointer instance
557 return $this->getPointerInstance()->determineSeekPosition();
561 * Seek to given offset (default) or other possibilities as fseek() gives.
563 * @param $offset Offset to seek to (or used as "base" for other seeks)
564 * @param $whence Added to offset (default: only use offset to seek to)
565 * @return $status Status of file seek: 0 = success, -1 = failed
567 public function seek ($offset, $whence = SEEK_SET) {
568 // Call pointer instance
569 return $this->getPointerInstance()->seek($offset, $whence);
573 * Reads given amount of bytes from file.
575 * @param $bytes Amount of bytes to read
576 * @return $data Data read from file
578 public function read ($bytes = NULL) {
579 // $bytes shall be integer
580 assert(is_int($bytes));
582 // Call pointer instance
583 return $this->getPointerInstance()->read($bytes);
587 * Rewinds to the beginning of the file
589 * @return $status Status of this operation
591 public function rewind () {
592 // Call pointer instance
593 return $this->getPointerInstance()->rewind();
597 * Analyzes entries in index file. This will count all found (and valid)
598 * entries, mark invalid as damaged and count gaps ("fragmentation"). If
599 * only gaps are found, the file is considered as "virgin" (no entries).
603 public function analyzeFile () {
604 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
606 // Make sure the file is initialized
607 assert($this->isFileInitialized());
609 // Init counters and gaps array
610 $this->initCountersGapsArray();
612 // Output message (as this may take some time)
613 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Analyzing file structure ... (this may take some time)', __METHOD__, __LINE__));
615 // First rewind to the begining
618 // Then try to load all entries
619 while ($this->valid()) {
624 $current = $this->getCurrentBlock();
627 * If the block is empty, maybe the whole file is? This could mean
628 * that the file has been pre-allocated.
630 if (empty($current)) {
631 // Then skip this part
636 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] current()=%s', __METHOD__, __LINE__, strlen($current)));
639 // If the last read block is empty, check gaps
640 if (empty($current)) {
642 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Found a total of %s gaps.', __METHOD__, __LINE__, count($this->gaps)));
644 // Check gaps, if the whole file is empty.
645 if ($this->isFileOnlyGaps()) {
646 // Only gaps, so don't continue here.
651 * The above call has calculated a total size of all gaps. If the
652 * percentage of gaps passes a "soft" limit and last
653 * defragmentation is to far in the past, or if a "hard" limit has
654 * reached, run defragmentation.
656 if ($this->isDefragmentationNeeded()) {
657 // Run "defragmentation"
658 $this->doRunDefragmentation();
661 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
665 * Advances to next "block" of bytes
669 public function next () {
670 // Is there nothing to read?
671 if (!$this->valid()) {
677 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d] key()=%s', __FUNCTION__, __LINE__, $this->key()));
679 // Make sure the block instance is set
680 assert($this->getBlockInstance() instanceof CalculatableBlock);
682 // First calculate minimum block length
683 $length = $this->getBlockInstance()->calculateMinimumBlockLength();
684 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d] length=%s', __FUNCTION__, __LINE__, $length));
686 // Short be more than zero!
689 // Read possibly back-buffered bytes from previous call of next().
690 $data = $this->getBackBuffer();
693 * Read until a entry/block separator has been found. The next read
694 * "block" may not fit, so this loop will continue until the EOB or EOF
695 * has been reached whatever comes first.
697 while ((!$this->isEndOfFileReached()) && (!self::isBlockSeparatorFound($data))) {
698 // Then read the next possible block
699 $block = $this->read($length);
702 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d] block()=%s,length=%s', __FUNCTION__, __LINE__, strlen($block), $length));
705 if (strlen(trim($block)) == 0) {
706 // Mark this block as empty
707 $this->markCurrentBlockAsEmpty(strlen($block));
709 // Skip to next block
713 // At this block then
717 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d] data()=%s', __FUNCTION__, __LINE__, strlen($data)));
721 if ($this->isEndOfFileReached()) {
722 // Set whole data as current read block
723 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('Calling setCurrentBlock(' . strlen($data) . ') ...');
724 $this->setCurrentBlock($data);
726 // Then abort here silently
727 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('EOF reached.');
732 * Init back-buffer which is the data that has been found beyond the
735 $this->initBackBuffer();
738 $dataArray = explode(chr(self::SEPARATOR_ENTRIES), $data);
740 // This array must contain two elements
741 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('dataArray=' . print_r($dataArray, TRUE));
742 assert(count($dataArray) == 2);
744 // Left part is the actual block, right one the back-buffer data
745 $this->setCurrentBlock($dataArray[0]);
746 $this->setBackBuffer($dataArray[1]);
750 * Checks wether the current entry is valid (not at the end of the file).
751 * This method will return TRUE if an emptied (nulled) entry has been found.
753 * @return $isValid Whether the next entry is valid
755 public function valid () {
756 // Make sure the block instance is set
757 assert($this->getBlockInstance() instanceof Block);
759 // First calculate minimum block length
760 $length = $this->getBlockInstance()->calculateMinimumBlockLength();
762 // Short be more than zero!
765 // Get current seek position
766 $seekPosition = $this->key();
768 // Then try to read it
769 $data = $this->read($length);
771 // If some bytes could be read, all is fine
772 $isValid = ((is_string($data)) && (strlen($data) > 0));
775 $headerSize = $this->getHeaderSize();
777 // Is the seek position at or beyond the header?
778 if ($seekPosition >= $headerSize) {
779 // Seek back to old position
780 $this->seek($seekPosition);
782 // Seek directly behind the header
783 $this->seek($headerSize);
791 * Gets current seek position ("key").
793 * @return $key Current key in iteration
795 public function key () {
796 // Call pointer instance
797 return $this->getPointerInstance()->determineSeekPosition();
801 * Reads the file header
805 public function readFileHeader () {
806 // Make sure the block instance is set
807 assert($this->getBlockInstance() instanceof Block);
809 // Call block instance
810 $this->getBlockInstance()->readFileHeader();
814 * Flushes the file header
818 public function flushFileHeader () {
819 // Make sure the block instance is set
820 assert($this->getBlockInstance() instanceof Block);
822 // Call block instance
823 $this->getBlockInstance()->flushFileHeader();