Continued:
[core.git] / inc / classes / main / file_directories / binary / class_BaseBinaryFile.php
1 <?php
2 /**
3  * A general binary file class
4  *
5  * @author              Roland Haeder <webmaster@ship-simu.org>
6  * @version             0.0.0
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
10  *
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.
15  *
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.
20  *
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/>.
23  */
24 class BaseBinaryFile extends BaseAbstractFile {
25         /**
26          * Separator for header data
27          */
28         const SEPARATOR_HEADER_DATA = 0x01;
29
30         /**
31          * Separator header->entries
32          */
33         const SEPARATOR_HEADER_ENTRIES = 0x02;
34
35         /**
36          * Separator group->hash
37          */
38         const SEPARATOR_GROUP_HASH = 0x03;
39
40         /**
41          * Separator hash->value
42          */
43         const SEPARATOR_HASH_VALUE = 0x04;
44
45         /**
46          * Separator entry->entry
47          */
48         const SEPARATOR_ENTRIES = 0x05;
49
50         /**
51          * Separator type->position
52          */
53         const SEPARATOR_TYPE_POSITION = 0x06;
54
55         /**
56          * Length of count
57          */
58         const LENGTH_COUNT = 20;
59
60         /**
61          * Length of position
62          */
63         const LENGTH_POSITION = 20;
64
65         /**
66          * Length of group
67          */
68         const LENGTH_GROUP = 10;
69
70         /**
71          * Maximum length of entry type
72          */
73         const LENGTH_TYPE = 20;
74
75         //***** Array elements for 'gaps' array *****
76
77         /**
78          * Start of gap
79          */
80         const GAPS_INDEX_START = 'start';
81
82         /**
83          * End of gap
84          */
85         const GAPS_INDEX_END = 'end';
86
87         /**
88          * Current seek position
89          */
90         private $seekPosition = 0;
91
92         /**
93          * Size of header
94          */
95         private $headerSize = 0;
96
97         /**
98          * File header
99          */
100         private $header = array();
101
102         /**
103          * Seek positions for gaps ("fragmentation")
104          */
105         private $gaps = array();
106
107         /**
108          * Seek positions for damaged entries (e.g. mismatching hash sum, ...)
109          */
110         private $damagedEntries = array();
111
112         /**
113          * Back-buffer
114          */
115         private $backBuffer = '';
116
117         /**
118          * Currently loaded block (will be returned by current())
119          */
120         private $currentBlock = '';
121
122         /**
123          * Protected constructor
124          *
125          * @param       $className      Name of the class
126          * @return      void
127          */
128         protected function __construct ($className) {
129                 // Call parent constructor
130                 parent::__construct($className);
131
132                 // Init counters and gaps array
133                 $this->initCountersGapsArray();
134         }
135
136         /**
137          * Checks whether the abstracted file only contains gaps by counting all
138          * gaps' bytes together and compare it to total length.
139          *
140          * @return      $isGapsOnly             Whether the abstracted file only contains gaps
141          */
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)));
148                 } // END - if
149                 */
150
151                 // Now count every gap
152                 $gapsSize = 0;
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]);
156                 } // END - if
157
158                 // Debug output
159                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] gapsSize=%s,this->headerSize=%s', __METHOD__, __LINE__, $gapsSize, $this->getHeaderSize()));
160
161                 // Total gap size + header size must be same as file size
162                 $isGapsOnly = (($this->getHeaderSize() + $gapsSize) == $this->getFileSize());
163
164                 // Return status
165                 return $isGapsOnly;
166         }
167
168         /**
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.
173          *
174          * @return      void
175          */
176         public function initCountersGapsArray () {
177                 // Init counter and seek position
178                 $this->setCounter(0);
179                 $this->setSeekPosition(0);
180
181                 // Init arrays
182                 $this->gaps = array();
183                 $this->damagedEntries = array();
184         }
185
186         /**
187          * Getter for header size
188          *
189          * @return      $totalEntries   Size of file header
190          */
191         public final function getHeaderSize () {
192                 // Get it
193                 return $this->headerSize;
194         }
195
196         /**
197          * Setter for header size
198          *
199          * @param       $headerSize             Size of file header
200          * @return      void
201          */
202         public final function setHeaderSize ($headerSize) {
203                 // Set it
204                 $this->headerSize = $headerSize;
205         }
206
207         /**
208          * Getter for header array
209          *
210          * @return      $totalEntries   Size of file header
211          */
212         public final function getHeader () {
213                 // Get it
214                 return $this->header;
215         }
216
217         /**
218          * Setter for header
219          *
220          * @param       $header         Array for a file header
221          * @return      void
222          */
223         public final function setHeader (array $header) {
224                 // Set it
225                 $this->header = $header;
226         }
227
228         /**
229          * Getter for seek position
230          *
231          * @return      $seekPosition   Current seek position (stored here in object)
232          */
233         public final function getSeekPosition () {
234                 // Get it
235                 return $this->seekPosition;
236         }
237
238         /**
239          * Setter for seek position
240          *
241          * @param       $seekPosition   Current seek position (stored here in object)
242          * @return      void
243          */
244         protected final function setSeekPosition ($seekPosition) {
245                 // And set it
246                 $this->seekPosition = $seekPosition;
247         }
248
249         /**
250          * Updates seekPosition attribute from file to avoid to much access on file.
251          *
252          * @return      void
253          */
254         public function updateSeekPosition () {
255                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
256
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));
260
261                 // And set it here
262                 $this->setSeekPosition($seekPosition);
263
264                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
265         }
266
267         /**
268          * Seeks to beginning of file, updates seek position in this object and
269          * flushes the header.
270          *
271          * @return      void
272          */
273         protected function rewindUpdateSeekPosition () {
274                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
275
276                 // flushFileHeader must be callable
277                 assert(is_callable(array($this, 'flushFileHeader')));
278
279                 // Seek to beginning of file
280                 $this->rewind();
281
282                 // And update seek position ...
283                 $this->updateSeekPosition();
284
285                 // ... to write it back into the file
286                 $this->flushFileHeader();
287
288                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
289         }
290
291         /**
292          * Seeks to old position
293          *
294          * @return      void
295          */
296         protected function seekToOldPosition () {
297                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
298
299                 // Seek to currently ("old") saved position
300                 $this->seek($this->getSeekPosition());
301
302                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
303         }
304
305         /**
306          * Checks whether the block separator has been found
307          *
308          * @param       $str            String to look in
309          * @return      $isFound        Whether the block separator has been found
310          */
311         public static function isBlockSeparatorFound ($str) {
312                 // Determine it
313                 $isFound = (strpos($str, chr(self::SEPARATOR_ENTRIES)) !== FALSE);
314
315                 // Return result
316                 return $isFound;
317         }
318
319         /**
320          * Initializes the back-buffer by setting it to an empty string.
321          *
322          * @return      void
323          */
324         private function initBackBuffer () {
325                 // Simply call the setter
326                 $this->setBackBuffer('');
327         }
328
329         /**
330          * Setter for backBuffer field
331          *
332          * @param       $backBuffer             Characters to "store" in back-buffer
333          * @return      void
334          */
335         private function setBackBuffer ($backBuffer) {
336                 // Cast to string (so no arrays or objects)
337                 $backBuffer = (string) $backBuffer;
338
339                 // ... and set it
340                 $this->backBuffer = $backBuffer;
341         }
342
343         /**
344          * Getter for backBuffer field
345          *
346          * @return      $backBuffer             Characters "stored" in back-buffer
347          */
348         private function getBackBuffer () {
349                 return $this->backBuffer;
350         }
351
352         /**
353          * Setter for currentBlock field
354          *
355          * @param       $currentBlock           Characters to set a currently loaded block
356          * @return      void
357          */
358         private function setCurrentBlock ($currentBlock) {
359                 // Cast to string (so no arrays or objects)
360                 $currentBlock = (string) $currentBlock;
361
362                 // ... and set it
363                 $this->currentBlock = $currentBlock;
364         }
365
366         /**
367          * Gets currently read data
368          *
369          * @return      $current        Currently read data
370          */
371         public function getCurrentBlock () {
372                 // Return it
373                 return $this->currentBlock;
374         }
375
376         /**
377          * Initializes this file class
378          *
379          * @param       $fileName       Name of this abstract file
380          * @return      void
381          */
382         protected function initFile ($fileName) {
383                 // Get a file i/o pointer instance
384                 $pointerInstance = ObjectFactory::createObjectByConfiguredName('file_raw_input_output_class', array($fileName));
385
386                 // ... and set it here
387                 $this->setPointerInstance($pointerInstance);
388         }
389
390         /**
391          * Writes data at given position
392          *
393          * @param       $seekPosition   Seek position
394          * @param       $data                   Data to be written
395          * @param       $flushHeader    Whether to flush the header (default: flush)
396          * @return      void
397          */
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)));
400
401                 // Write data at given position
402                 $this->getPointerInstance()->writeAtPosition($seekPosition, $data);
403
404                 // Update seek position
405                 $this->updateSeekPosition();
406
407                 // Flush the header?
408                 if ($flushHeader === TRUE) {
409                         // Flush header
410                         $this->flushFileHeader();
411
412                         // Seek to old position
413                         $this->seekToOldPosition();
414                 } // END - if
415
416                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
417         }
418
419         /**
420          * Marks the currently loaded block as empty (with length of the block)
421          *
422          * @param       $length         Length of the block
423          * @return      void
424          */
425         protected function markCurrentBlockAsEmpty ($length) {
426                 // Get current seek position
427                 $currentPosition = $this->key();
428
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,
433                 ));
434         }
435
436         /**
437          * Checks whether the file header is initialized
438          *
439          * @return      $isInitialized  Whether the file header is initialized
440          */
441         public function isFileHeaderInitialized () {
442                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
443
444                 // Default is not initialized
445                 $isInitialized = FALSE;
446
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));
452
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__));
457                         } // END - if
458
459                         // Read file header
460                         $this->readFileHeader();
461
462                         // The above method does already check the header
463                         $isInitialized = TRUE;
464                 } // END - if
465
466                 // Return result
467                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] isInitialized=%d - EXIT!', __METHOD__, __LINE__, intval($isInitialized)));
468                 return $isInitialized;
469         }
470
471         /**
472          * Checks whether the assigned file has been initialized
473          *
474          * @return      $isInitialized          Whether the file's size is zero
475          */
476         public function isFileInitialized () {
477                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
478
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));
482
483                 /*
484                  * The returned file size should not be FALSE or NULL as this means
485                  * that the pointer class does not work correctly.
486                  */
487                 assert(is_int($fileSize));
488
489                 // Is more than 0 returned?
490                 $isInitialized = ($fileSize > 0);
491
492                 // Return result
493                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] isInitialized=%d - EXIT!', __METHOD__, __LINE__, intval($isInitialized)));
494                 return $isInitialized;
495         }
496
497         /**
498          * Creates the assigned file
499          *
500          * @return      void
501          */
502         public function createFileHeader () {
503                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
504
505                 // The file's header should not be initialized here
506                 assert(!$this->isFileHeaderInitialized());
507
508                 // Simple flush file header which will create it.
509                 $this->flushFileHeader();
510
511                 // Rewind seek position (to beginning of file) and update/flush file header
512                 $this->rewindUpdateSeekPosition();
513
514                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
515         }
516
517         /**
518          * Pre-allocates file (if enabled) with some space for later faster write access.
519          *
520          * @param       $type   Type of the file
521          * @return      void
522          */
523         public function preAllocateFile ($type) {
524                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
525
526                 // Is it enabled?
527                 if ($this->getConfigInstance()->getConfigEntry($type . '_pre_allocate_enabled') != 'Y') {
528                         // Not enabled
529                         self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Not pre-allocating file.', __METHOD__, __LINE__));
530
531                         // Don't continue here.
532                         return;
533                 } // END - if
534
535                 // Message to user
536                 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Pre-allocating file ...', __METHOD__, __LINE__));
537
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));
541
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));
545
546                 // Now simply write a NUL there. This will pre-allocate the file.
547                 $this->writeData($seekPosition, chr(0));
548
549                 // Rewind seek position (to beginning of file) and update/flush file header
550                 $this->rewindUpdateSeekPosition();
551
552                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
553         }
554
555         /**
556          * Determines seek position
557          *
558          * @return      $seekPosition   Current seek position
559          */
560         public function determineSeekPosition () {
561                 // Call pointer instance
562                 return $this->getPointerInstance()->determineSeekPosition();
563         }
564
565         /**
566          * Seek to given offset (default) or other possibilities as fseek() gives.
567          *
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
571          */
572         public function seek ($offset, $whence = SEEK_SET) {
573                 // Call pointer instance
574                 return $this->getPointerInstance()->seek($offset, $whence);
575         }
576
577         /**
578          * Reads given amount of bytes from file.
579          *
580          * @param       $bytes  Amount of bytes to read
581          * @return      $data   Data read from file
582          */
583         public function read ($bytes = NULL) {
584                 // $bytes shall be integer
585                 assert(is_int($bytes));
586
587                 // Call pointer instance
588                 return $this->getPointerInstance()->read($bytes);
589         }
590
591         /**
592          * Rewinds to the beginning of the file
593          *
594          * @return      $status         Status of this operation
595          */
596         public function rewind () {
597                 // Call pointer instance
598                 return $this->getPointerInstance()->rewind();
599         }
600
601         /**
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).
605          *
606          * @return      void
607          */
608         public function analyzeFile () {
609                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
610
611                 // Make sure the file is initialized
612                 assert($this->isFileInitialized());
613
614                 // Init counters and gaps array
615                 $this->initCountersGapsArray();
616
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__));
619
620                 // First rewind to the begining
621                 $this->rewind();
622
623                 // Then try to load all entries
624                 while ($this->valid()) {
625                         // Go to next entry
626                         $this->next();
627
628                         // Get current entry
629                         $current = $this->getCurrentBlock();
630
631                         /*
632                          * If the block is empty, maybe the whole file is? This could mean
633                          * that the file has been pre-allocated.
634                          */
635                         if (empty($current)) {
636                                 // Then skip this part
637                                 continue;
638                         } // END - if
639
640                         // Debug message
641                         /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] current()=%s', __METHOD__, __LINE__, strlen($current)));
642                 } // END - while
643
644                 // If the last read block is empty, check gaps
645                 if (empty($current)) {
646                         // Output message
647                         self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Found a total of %s gaps.', __METHOD__, __LINE__, count($this->gaps)));
648
649                         // Check gaps, if the whole file is empty.
650                         if ($this->isFileOnlyGaps()) {
651                                 // Only gaps, so don't continue here.
652                                 return;
653                         } // END - if
654
655                         /*
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.
660                          */
661                         if ($this->isDefragmentationNeeded()) {
662                                 // Run "defragmentation"
663                                 $this->doRunDefragmentation();
664                         } // END - if
665                 } // END - if
666                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
667         }
668
669         /**
670          * Advances to next "block" of bytes
671          *
672          * @return      void
673          */
674         public function next () {
675                 // Is there nothing to read?
676                 if (!$this->valid()) {
677                         // Nothing to read
678                         return;
679                 } // END - if
680
681                 // Debug message
682                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d] key()=%s', __FUNCTION__, __LINE__, $this->key()));
683
684                 // Make sure the block instance is set
685                 assert($this->getBlockInstance() instanceof CalculatableBlock);
686
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));
690
691                 // Short be more than zero!
692                 assert($length > 0);
693
694                 // Read possibly back-buffered bytes from previous call of next().
695                 $data = $this->getBackBuffer();
696
697                 /*
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.
701                  */
702                 while ((!$this->isEndOfFileReached()) && (!self::isBlockSeparatorFound($data))) {
703                         // Then read the next possible block
704                         $block = $this->read($length);
705
706                         // Debug message
707                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d] block()=%s,length=%s', __FUNCTION__, __LINE__, strlen($block), $length));
708
709                         // Is it all empty?
710                         if (strlen(trim($block)) == 0) {
711                                 // Mark this block as empty
712                                 $this->markCurrentBlockAsEmpty(strlen($block));
713
714                                 // Skip to next block
715                                 continue;
716                         } // END - if
717
718                         // At this block then
719                         $data .= $block;
720
721                         // A debug message
722                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d] data()=%s', __FUNCTION__, __LINE__, strlen($data)));
723                 } // END - while
724
725                 // EOF reached?
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);
730
731                         // Then abort here silently
732                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('EOF reached.');
733                         return;
734                 } // END - if
735
736                 /*
737                  * Init back-buffer which is the data that has been found beyond the
738                  * separator.
739                  */
740                 $this->initBackBuffer();
741
742                 // Separate data
743                 $dataArray = explode(chr(self::SEPARATOR_ENTRIES), $data);
744
745                 // This array must contain two elements
746                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('dataArray=' . print_r($dataArray, TRUE));
747                 assert(count($dataArray) == 2);
748
749                 // Left part is the actual block, right one the back-buffer data
750                 $this->setCurrentBlock($dataArray[0]);
751                 $this->setBackBuffer($dataArray[1]);
752         }
753
754         /**
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.
757          *
758          * @return      $isValid        Whether the next entry is valid
759          */
760         public function valid () {
761                 // Make sure the block instance is set
762                 assert($this->getBlockInstance() instanceof Block);
763
764                 // First calculate minimum block length
765                 $length = $this->getBlockInstance()->calculateMinimumBlockLength();
766
767                 // Short be more than zero!
768                 assert($length > 0);
769
770                 // Get current seek position
771                 $seekPosition = $this->key();
772
773                 // Then try to read it
774                 $data = $this->read($length);
775
776                 // If some bytes could be read, all is fine
777                 $isValid = ((is_string($data)) && (strlen($data) > 0));
778
779                 // Get header size
780                 $headerSize = $this->getHeaderSize();
781
782                 // Is the seek position at or beyond the header?
783                 if ($seekPosition >= $headerSize) {
784                         // Seek back to old position
785                         $this->seek($seekPosition);
786                 } else {
787                         // Seek directly behind the header
788                         $this->seek($headerSize);
789                 }
790
791                 // Return result
792                 return $isValid;
793         }
794
795         /**
796          * Gets current seek position ("key").
797          *
798          * @return      $key    Current key in iteration
799          */
800         public function key () {
801                 // Call pointer instance
802                 return $this->getPointerInstance()->determineSeekPosition();
803         }
804
805         /**
806          * Reads the file header
807          *
808          * @return      void
809          */
810         public function readFileHeader () {
811                 // Make sure the block instance is set
812                 assert($this->getBlockInstance() instanceof Block);
813
814                 // Call block instance
815                 $this->getBlockInstance()->readFileHeader();
816         }
817
818         /**
819          * Flushes the file header
820          *
821          * @return      void
822          */
823         public function flushFileHeader () {
824                 // Make sure the block instance is set
825                 assert($this->getBlockInstance() instanceof Block);
826
827                 // Call block instance
828                 $this->getBlockInstance()->flushFileHeader();
829         }
830
831         /**
832          * Searches for next suitable gap the given length of data can fit in
833          * including padding bytes.
834          *
835          * @param       $length                 Length of raw data
836          * @return      $seekPosition   Found next gap's seek position
837          */
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);
843                 } // END - if
844
845                 // @TODO Unfinished
846                 $this->partialStub('length=' . $length);
847         }
848 }
849
850 // [EOF]
851 ?>