Also getSeekPosition() belongs here ... + TODOs.txt updated (--amend rocks!)
[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 - 2012 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 BaseFile {
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) {
579                 // Call pointer instance
580                 return $this->getPointerInstance()->read($bytes);
581         }
582
583         /**
584          * Rewinds to the beginning of the file
585          *
586          * @return      $status         Status of this operation
587          */
588         public function rewind () {
589                 // Call pointer instance
590                 return $this->getPointerInstance()->rewind();
591         }
592
593         /**
594          * Analyzes entries in index file. This will count all found (and valid)
595          * entries, mark invalid as damaged and count gaps ("fragmentation"). If
596          * only gaps are found, the file is considered as "virgin" (no entries).
597          *
598          * @return      void
599          */
600         public function analyzeFile () {
601                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
602
603                 // Make sure the file is initialized
604                 assert($this->isFileInitialized());
605
606                 // Init counters and gaps array
607                 $this->initCountersGapsArray();
608
609                 // Output message (as this may take some time)
610                 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Analyzing file structure ... (this may take some time)', __METHOD__, __LINE__));
611
612                 // First rewind to the begining
613                 $this->rewind();
614
615                 // Then try to load all entries
616                 while ($this->valid()) {
617                         // Go to next entry
618                         $this->next();
619
620                         // Get current entry
621                         $current = $this->getCurrentBlock();
622
623                         /*
624                          * If the block is empty, maybe the whole file is? This could mean
625                          * that the file has been pre-allocated.
626                          */
627                         if (empty($current)) {
628                                 // Then skip this part
629                                 continue;
630                         } // END - if
631
632                         // Debug message
633                         /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] current()=%s', __METHOD__, __LINE__, strlen($current)));
634                 } // END - while
635
636                 // If the last read block is empty, check gaps
637                 if (empty($current)) {
638                         // Output message
639                         self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Found a total of %s gaps.', __METHOD__, __LINE__, count($this->gaps)));
640
641                         // Check gaps, if the whole file is empty.
642                         if ($this->isFileOnlyGaps()) {
643                                 // Only gaps, so don't continue here.
644                                 return;
645                         } // END - if
646
647                         /*
648                          * The above call has calculated a total size of all gaps. If the
649                          * percentage of gaps passes a "soft" limit and last
650                          * defragmentation is to far in the past, or if a "hard" limit has
651                          * reached, run defragmentation.
652                          */
653                         if ($this->isDefragmentationNeeded()) {
654                                 // Run "defragmentation"
655                                 $this->doRunDefragmentation();
656                         } // END - if
657                 } // END - if
658                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
659         }
660
661         /**
662          * Advances to next "block" of bytes
663          *
664          * @return      void
665          */
666         public function next () {
667                 // Is there nothing to read?
668                 if (!$this->valid()) {
669                         // Nothing to read
670                         return;
671                 } // END - if
672
673                 // Debug message
674                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d] key()=%s', __FUNCTION__, __LINE__, $this->key()));
675
676                 // Make sure the block instance is set
677                 assert($this->getBlockInstance() instanceof CalculatableBlock);
678
679                 // First calculate minimum block length
680                 $length = $this->getBlockInstance()->calculateMinimumBlockLength();
681                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d] length=%s', __FUNCTION__, __LINE__, $length));
682
683                 // Short be more than zero!
684                 assert($length > 0);
685
686                 // Read possibly back-buffered bytes from previous call of next().
687                 $data = $this->getBackBuffer();
688
689                 /*
690                  * Read until a entry/block separator has been found. The next read
691                  * "block" may not fit, so this loop will continue until the EOB or EOF
692                  * has been reached whatever comes first.
693                  */
694                 while ((!$this->isEndOfFileReached()) && (!self::isBlockSeparatorFound($data))) {
695                         // Then read the next possible block
696                         $block = $this->read($length);
697
698                         // Debug message
699                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d] block()=%s,length=%s', __FUNCTION__, __LINE__, strlen($block), $length));
700
701                         // Is it all empty?
702                         if (strlen(trim($block)) == 0) {
703                                 // Mark this block as empty
704                                 $this->markCurrentBlockAsEmpty(strlen($block));
705
706                                 // Skip to next block
707                                 continue;
708                         } // END - if
709
710                         // At this block then
711                         $data .= $block;
712
713                         // A debug message
714                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d] data()=%s', __FUNCTION__, __LINE__, strlen($data)));
715                 } // END - while
716
717                 // EOF reached?
718                 if ($this->isEndOfFileReached()) {
719                         // Set whole data as current read block
720                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('Calling setCurrentBlock(' . strlen($data) . ') ...');
721                         $this->setCurrentBlock($data);
722
723                         // Then abort here silently
724                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('EOF reached.');
725                         return;
726                 } // END - if
727
728                 /*
729                  * Init back-buffer which is the data that has been found beyond the
730                  * separator.
731                  */
732                 $this->initBackBuffer();
733
734                 // Separate data
735                 $dataArray = explode(chr(self::SEPARATOR_ENTRIES), $data);
736
737                 // This array must contain two elements
738                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('dataArray=' . print_r($dataArray, TRUE));
739                 assert(count($dataArray) == 2);
740
741                 // Left part is the actual block, right one the back-buffer data
742                 $this->setCurrentBlock($dataArray[0]);
743                 $this->setBackBuffer($dataArray[1]);
744         }
745
746         /**
747          * Checks wether the current entry is valid (not at the end of the file).
748          * This method will return TRUE if an emptied (nulled) entry has been found.
749          *
750          * @return      $isValid        Whether the next entry is valid
751          */
752         public function valid () {
753                 // Make sure the block instance is set
754                 assert($this->getBlockInstance() instanceof Block);
755
756                 // First calculate minimum block length
757                 $length = $this->getBlockInstance()->calculateMinimumBlockLength();
758
759                 // Short be more than zero!
760                 assert($length > 0);
761
762                 // Get current seek position
763                 $seekPosition = $this->key();
764
765                 // Then try to read it
766                 $data = $this->read($length);
767
768                 // If some bytes could be read, all is fine
769                 $isValid = ((is_string($data)) && (strlen($data) > 0));
770
771                 // Get header size
772                 $headerSize = $this->getHeaderSize();
773
774                 // Is the seek position at or beyond the header?
775                 if ($seekPosition >= $headerSize) {
776                         // Seek back to old position
777                         $this->seek($seekPosition);
778                 } else {
779                         // Seek directly behind the header
780                         $this->seek($headerSize);
781                 }
782
783                 // Return result
784                 return $isValid;
785         }
786
787         /**
788          * Gets current seek position ("key").
789          *
790          * @return      $key    Current key in iteration
791          */
792         public function key () {
793                 // Call pointer instance
794                 return $this->getPointerInstance()->determineSeekPosition();
795         }
796
797         /**
798          * Reads the file header
799          *
800          * @return      void
801          */
802         public function readFileHeader () {
803                 // Make sure the block instance is set
804                 assert($this->getBlockInstance() instanceof Block);
805
806                 // Call block instance
807                 $this->getBlockInstance()->readFileHeader();
808         }
809
810         /**
811          * Flushes the file header
812          *
813          * @return      void
814          */
815         public function flushFileHeader () {
816                 // Make sure the block instance is set
817                 assert($this->getBlockInstance() instanceof Block);
818
819                 // Call block instance
820                 $this->getBlockInstance()->flushFileHeader();
821         }
822 }
823
824 // [EOF]
825 ?>