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