d228d796f60f5169bfea730a8cb741f191a58295
[core.git] / inc / classes / main / file_directories / class_BaseFile.php
1 <?php
2 /**
3  * A general 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 BaseFile extends BaseFrameworkSystem {
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          * Length of output from hash()
84          */
85         private static $hashLength = NULL;
86
87         /**
88          * Counter for total entries
89          */
90         private $totalEntries = 0;
91
92         /**
93          * Current seek position
94          */
95         private $seekPosition = 0;
96
97         /**
98          * Size of header
99          */
100         private $headerSize = 0;
101
102         /**
103          * File header
104          */
105         private $header = array();
106
107         /**
108          * Seek positions for gaps ("fragmentation")
109          */
110         private $gaps = array();
111
112         /**
113          * Seek positions for damaged entries (e.g. mismatching hash sum, ...)
114          */
115         private $damagedEntries = array();
116
117         /**
118          * The current file we are working in
119          */
120         private $fileName = '';
121
122         /**
123          * Back-buffer
124          */
125         private $backBuffer = '';
126
127         /**
128          * Currently loaded block (will be returned by current())
129          */
130         private $currentBlock = '';
131
132         /**
133          * Protected constructor
134          *
135          * @param       $className      Name of the class
136 y        * @return      void
137          */
138         protected function __construct ($className) {
139                 // Call parent constructor
140                 parent::__construct($className);
141
142                 // Init counters and gaps array
143                 $this->initCountersGapsArray();
144         }
145
146         /**
147          * Destructor for cleaning purposes, etc
148          *
149          * @return      void
150          */
151         public final function __destruct() {
152                 // Try to close a file
153                 $this->closeFile();
154
155                 // Call the parent destructor
156                 parent::__destruct();
157         }
158
159         /**
160          * Initializes counter for valid entries, arrays for damaged entries and
161          * an array for gap seek positions. If you call this method on your own,
162          * please re-analyze the file structure. So you are better to call
163          * analyzeFile() instead of this method.
164          *
165          * @return      void
166          */
167         protected function initCountersGapsArray () {
168                 // Init counter and seek position
169                 $this->setCounter(0);
170                 $this->setSeekPosition(0);
171
172                 // Init arrays
173                 $this->gaps = array();
174                 $this->damagedEntries = array();
175         }
176
177         /**
178          * Getter for total entries
179          *
180          * @return      $totalEntries   Total entries in this file
181          */
182         protected final function getCounter () {
183                 // Get it
184                 return $this->totalEntries;
185         }
186
187         /**
188          * Setter for total entries
189          *
190          * @param       $totalEntries   Total entries in this file
191          * @return      void
192          */
193         protected final function setCounter ($counter) {
194                 // Set it
195                 $this->totalEntries = $counter;
196         }
197
198         /**
199          * Increment counter
200          *
201          * @return      void
202          */
203         protected final function incrementCounter () {
204                 // Get it
205                 $this->totalEntries++;
206         }
207
208         /**
209          * Getter for header size
210          *
211          * @return      $totalEntries   Size of file header
212          */
213         public final function getHeaderSize () {
214                 // Get it
215                 return $this->headerSize;
216         }
217
218         /**
219          * Setter for header size
220          *
221          * @param       $headerSize             Size of file header
222          * @return      void
223          */
224         protected final function setHeaderSize ($headerSize) {
225                 // Set it
226                 $this->headerSize = $headerSize;
227         }
228
229         /**
230          * Getter for header array
231          *
232          * @return      $totalEntries   Size of file header
233          */
234         protected final function getHeade () {
235                 // Get it
236                 return $this->header;
237         }
238
239         /**
240          * Setter for header
241          *
242          * @param       $header         Array for a file header
243          * @return      void
244          */
245         protected final function setHeader (array $header) {
246                 // Set it
247                 $this->header = $header;
248         }
249
250         /**
251          * Getter for seek position
252          *
253          * @return      $seekPosition   Current seek position (stored here in object)
254          */
255         protected final function getSeekPosition () {
256                 // Get it
257                 return $this->seekPosition;
258         }
259
260         /**
261          * Setter for seek position
262          *
263          * @param       $seekPosition   Current seek position (stored here in object)
264          * @return      void
265          */
266         protected final function setSeekPosition ($seekPosition) {
267                 // And set it
268                 $this->seekPosition = $seekPosition;
269         }
270
271         /**
272          * Updates seekPosition attribute from file to avoid to much access on file.
273          *
274          * @return      void
275          */
276         protected function updateSeekPosition () {
277                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
278
279                 // Get key (= seek position)
280                 $seekPosition = $this->getIteratorInstance()->key();
281                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Setting seekPosition=%s', __METHOD__, __LINE__, $seekPosition));
282
283                 // And set it here
284                 $this->setSeekPosition($seekPosition);
285
286                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
287         }
288
289         /**
290          * Seeks to beginning of file, updates seek position in this object and
291          * flushes the header.
292          *
293          * @return      void
294          */
295         protected function rewindUpdateSeekPosition () {
296                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
297
298                 // flushFileHeader must be callable
299                 assert(is_callable(array($this, 'flushFileHeader')));
300
301                 // Seek to beginning of file
302                 $this->getIteratorInstance()->rewind();
303
304                 // And update seek position ...
305                 $this->updateSeekPosition();
306
307                 // ... to write it back into the file
308                 $this->flushFileHeader();
309
310                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!!', __METHOD__, __LINE__));
311         }
312
313         /**
314          * Seeks to old position
315          *
316          * @return      void
317          */
318         protected function seekToOldPosition () {
319                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
320
321                 // Seek to currently ("old") saved position
322                 $this->getIteratorInstance()->seek($this->getSeekPosition());
323
324                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!!', __METHOD__, __LINE__));
325         }
326
327         /**
328          * Checks whether the block separator has been found
329          *
330          * @param       $str            String to look in
331          * @return      $isFound        Whether the block separator has been found
332          */
333         public static function isBlockSeparatorFound ($str) {
334                 // Determine it
335                 $isFound = (strpos($str, chr(self::SEPARATOR_ENTRIES)) !== FALSE);
336
337                 // Return result
338                 return $isFound;
339         }
340
341         /**
342          * Getter for the file pointer
343          *
344          * @return      $filePointer    The file pointer which shall be a valid file resource
345          * @throws      UnsupportedOperationException   If this method is called
346          */
347         public final function getPointer () {
348                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
349         }
350
351         /**
352          * Setter for file name
353          *
354          * @param       $fileName       The new file name
355          * @return      void
356          */
357         protected final function setFileName ($fileName) {
358                 $fileName = (string) $fileName;
359                 $this->fileName = $fileName;
360         }
361
362         /**
363          * Getter for file name
364          *
365          * @return      $fileName       The current file name
366          */
367         public final function getFileName () {
368                 return $this->fileName;
369         }
370
371         /**
372          * Initializes the back-buffer by setting it to an empty string.
373          *
374          * @return      void
375          */
376         private function initBackBuffer () {
377                 // Simply call the setter
378                 $this->setBackBuffer('');
379         }
380
381         /**
382          * Setter for backBuffer field
383          *
384          * @param       $backBuffer             Characters to "store" in back-buffer
385          * @return      void
386          */
387         private function setBackBuffer ($backBuffer) {
388                 // Cast to string (so no arrays or objects)
389                 $backBuffer = (string) $backBuffer;
390
391                 // ... and set it
392                 $this->backBuffer = $backBuffer;
393         }
394
395         /**
396          * Getter for backBuffer field
397          *
398          * @return      $backBuffer             Characters "stored" in back-buffer
399          */
400         private function getBackBuffer () {
401                 return $this->backBuffer;
402         }
403
404         /**
405          * Setter for currentBlock field
406          *
407          * @param       $currentBlock           Characters to set a currently loaded block
408          * @return      void
409          */
410         private function setCurrentBlock ($currentBlock) {
411                 // Cast to string (so no arrays or objects)
412                 $currentBlock = (string) $currentBlock;
413
414                 // ... and set it
415                 $this->currentBlock = $currentBlock;
416         }
417
418         /**
419          * Gets currently read data
420          *
421          * @return      $current        Currently read data
422          */
423         public function getCurrentBlock () {
424                 // Return it
425                 return $this->currentBlock;
426         }
427
428         /**
429          * Initializes this file class
430          *
431          * @param       $fileName       Name of this abstract file
432          * @return      void
433          */
434         protected function initFile ($fileName) {
435                 // Get a file i/o pointer instance
436                 $pointerInstance = ObjectFactory::createObjectByConfiguredName('file_raw_input_output_class', array($fileName));
437
438                 // ... and set it here
439                 $this->setPointerInstance($pointerInstance);
440         }
441
442         /**
443          * Writes data at given position
444          *
445          * @param       $seekPosition   Seek position
446          * @param       $data                   Data to be written
447          * @param       $flushHeader    Whether to flush the header (default: flush)
448          * @return      void
449          */
450         protected function writeData ($seekPosition, $data, $flushHeader = TRUE) {
451                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] seekPosition=%s,data()=%s - CALLED!', __METHOD__, __LINE__, $seekPosition, strlen($data)));
452
453                 // Write data at given position
454                 $this->getPointerInstance()->writeAtPosition($seekPosition, $data);
455
456                 // Update seek position
457                 $this->updateSeekPosition();
458
459                 // Flush the header?
460                 if ($flushHeader === TRUE) {
461                         // Flush header
462                         $this->flushFileHeader();
463
464                         // Seek to old position
465                         $this->seekToOldPosition();
466                 } // END - if
467
468                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
469         }
470
471         /**
472          * Marks the currently loaded block as empty (with length of the block)
473          *
474          * @param       $length         Length of the block
475          * @return      void
476          */
477         protected function markCurrentBlockAsEmpty ($length) {
478                 // Get current seek position
479                 $currentPosition = $this->key();
480
481                 // Now add it as gap entry
482                 array_push($this->gaps, array(
483                         self::GAPS_INDEX_START  => ($currentPosition - $length),
484                         self::GAPS_INDEX_END    => $currentPosition,
485                 ));
486         }
487
488         /**
489          * Checks whether the file header is initialized
490          *
491          * @return      $isInitialized  Whether the file header is initialized
492          */
493         public function isFileHeaderInitialized () {
494                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
495
496                 // Default is not initialized
497                 $isInitialized = FALSE;
498
499                 // Is the file initialized?
500                 if ($this->isFileInitialized()) {
501                         // Some bytes has been written, so rewind to start of it.
502                         $rewindStatus = $this->rewind();
503                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] rewindStatus=%s', __METHOD__, __LINE__, $rewindStatus));
504
505                         // Is the rewind() call successfull?
506                         if ($rewindStatus != 1) {
507                                 // Something bad happened
508                                 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Could not rewind().', __METHOD__, __LINE__));
509                         } // END - if
510
511                         // Read file header
512                         $this->readFileHeader();
513
514                         // The above method does already check the header
515                         $isInitialized = TRUE;
516                 } // END - if
517
518                 // Return result
519                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] isInitialized=%d - EXIT!', __METHOD__, __LINE__, intval($isInitialized)));
520                 return $isInitialized;
521         }
522
523         /**
524          * Checks whether the assigned file has been initialized
525          *
526          * @return      $isInitialized          Whether the file's size is zero
527          */
528         public function isFileInitialized () {
529                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
530
531                 // Get it from iterator which holds the pointer instance. If FALSE is returned
532                 $fileSize = $this->size();
533                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] fileSize=%s', __METHOD__, __LINE__, $fileSize));
534
535                 /*
536                  * The returned file size should not be FALSE or NULL as this means
537                  * that the pointer class does not work correctly.
538                  */
539                 assert(is_int($fileSize));
540
541                 // Is more than 0 returned?
542                 $isInitialized = ($fileSize > 0);
543
544                 // Return result
545                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] isInitialized=%d - EXIT!', __METHOD__, __LINE__, intval($isInitialized)));
546                 return $isInitialized;
547         }
548
549         /**
550          * Creates the assigned file
551          *
552          * @return      void
553          */
554         public function createFileHeader () {
555                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
556
557                 // The file's header should not be initialized here
558                 assert(!$this->isFileHeaderInitialized());
559
560                 // Simple flush file header which will create it.
561                 $this->flushFileHeader();
562
563                 // Rewind seek position (to beginning of file) and update/flush file header
564                 $this->rewindUpdateSeekPosition();
565
566                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!!', __METHOD__, __LINE__));
567         }
568
569         /**
570          * Pre-allocates file (if enabled) with some space for later faster write access.
571          *
572          * @param       $type   Type of the file
573          * @return      void
574          */
575         public function preAllocateFile ($type) {
576                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
577
578                 // Is it enabled?
579                 if ($this->getConfigInstance()->getConfigEntry($type . '_pre_allocate_enabled') != 'Y') {
580                         // Not enabled
581                         self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Not pre-allocating file.', __METHOD__, __LINE__));
582
583                         // Don't continue here.
584                         return;
585                 } // END - if
586
587                 // Message to user
588                 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Pre-allocating file ...', __METHOD__, __LINE__));
589
590                 // Calculate minimum length for one entry
591                 $minLengthEntry = $this->getBlockInstance()->calculateMinimumBlockLength();
592                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] minLengthEntry=%s', __METHOD__, __LINE__, $minLengthEntry));
593
594                 // Calulcate seek position
595                 $seekPosition = $minLengthEntry * $this->getConfigInstance()->getConfigEntry($type . '_pre_allocate_count');
596                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] seekPosition=%s', __METHOD__, __LINE__, $seekPosition));
597
598                 // Now simply write a NUL there. This will pre-allocate the file.
599                 $this->writeData($seekPosition, chr(0));
600
601                 // Rewind seek position (to beginning of file) and update/flush file header
602                 $this->rewindUpdateSeekPosition();
603
604                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
605         }
606
607         /**
608          * Close a file source and set it's instance to null and the file name
609          * to empty
610          *
611          * @return      void
612          * @todo        ~10% done?
613          */
614         public function closeFile () {
615                 $this->partialStub('Unfinished method.');
616
617                 // Remove file name
618                 $this->setFileName('');
619         }
620
621         /**
622          * Determines seek position
623          *
624          * @return      $seekPosition   Current seek position
625          */
626         public function determineSeekPosition () {
627                 // Call pointer instance
628                 return $this->getPointerInstance()->determineSeekPosition();
629         }
630
631         /**
632          * Seek to given offset (default) or other possibilities as fseek() gives.
633          *
634          * @param       $offset         Offset to seek to (or used as "base" for other seeks)
635          * @param       $whence         Added to offset (default: only use offset to seek to)
636          * @return      $status         Status of file seek: 0 = success, -1 = failed
637          */
638         public function seek ($offset, $whence = SEEK_SET) {
639                 // Call pointer instance
640                 return $this->getPointerInstance()->seek($offset, $whence);
641         }
642
643         /**
644          * Size of this file
645          *
646          * @return      $size   Size (in bytes) of file
647          * @todo        Handle seekStatus
648          */
649         public function size () {
650                 // Call pointer instance
651                 return $this->getPointerInstance()->size();
652         }
653
654         /**
655          * Read data a file pointer
656          *
657          * @return      mixed   The result of fread()
658          * @throws      NullPointerException    If the file pointer instance
659          *                                                                      is not set by setPointer()
660          * @throws      InvalidResourceException        If there is being set
661          */
662         public function readFromFile () {
663                 // Call pointer instance
664                 return $this->getPointerInstance()->readFromFile();
665         }
666
667         /**
668          * Reads given amount of bytes from file.
669          *
670          * @param       $bytes  Amount of bytes to read
671          * @return      $data   Data read from file
672          */
673         public function read ($bytes) {
674                 // Call pointer instance
675                 return $this->getPointerInstance()->read($bytes);
676         }
677
678         /**
679          * Write data to a file pointer
680          *
681          * @param       $dataStream             The data stream we shall write to the file
682          * @return      mixed                   Number of writes bytes or FALSE on error
683          * @throws      NullPointerException    If the file pointer instance
684          *                                                                      is not set by setPointer()
685          * @throws      InvalidResourceException        If there is being set
686          *                                                                                      an invalid file resource
687          */
688         public function writeToFile ($dataStream) {
689                 // Call pointer instance
690                 return $this->getPointerInstance()->writeToFile($dataStream);
691         }
692
693         /**
694          * Rewinds to the beginning of the file
695          *
696          * @return      $status         Status of this operation
697          */
698         public function rewind () {
699                 // Call pointer instance
700                 return $this->getPointerInstance()->rewind();
701         }
702
703         /**
704          * Determines whether the EOF has been reached
705          *
706          * @return      $isEndOfFileReached             Whether the EOF has been reached
707          */
708         public final function isEndOfFileReached () {
709                 // Call pointer instance
710                 return $this->getPointerInstance()->isEndOfFileReached();
711         }
712
713         /**
714          * Analyzes entries in index file. This will count all found (and valid)
715          * entries, mark invalid as damaged and count gaps ("fragmentation"). If
716          * only gaps are found, the file is considered as "virgin" (no entries).
717          *
718          * @return      void
719          */
720         public function analyzeFile () {
721                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
722
723                 // Make sure the file is initialized
724                 assert($this->isFileInitialized());
725
726                 // Init counters and gaps array
727                 $this->initCountersGapsArray();
728
729                 // Output message (as this may take some time)
730                 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Analyzing file structure ... (this may take some time)', __METHOD__, __LINE__));
731
732                 // First rewind to the begining
733                 $this->rewind();
734
735                 // Then try to load all entries
736                 while ($this->valid()) {
737                         // Go to next entry
738                         $this->next();
739
740                         // Get current entry
741                         $current = $this->getCurrentBlock();
742
743                         // Debug message
744                         /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] current()=%s', __METHOD__, __LINE__, strlen($current)));
745                 } // END - while
746
747                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
748         }
749
750         /**
751          * Advances to next "block" of bytes
752          *
753          * @return      void
754          */
755         public function next () {
756                 // Is there nothing to read?
757                 if (!$this->valid()) {
758                         // Nothing to read
759                         return;
760                 } // END - if
761
762                 // Make sure the block instance is set
763                 assert($this->getBlockInstance() instanceof CalculatableBlock);
764
765                 // First calculate minimum block length
766                 $length = $this->getBlockInstance()->calculateMinimumBlockLength();
767
768                 // Short be more than zero!
769                 assert($length > 0);
770
771                 // Read possibly back-buffered bytes from previous call of next().
772                 $data = $this->getBackBuffer();
773
774                 /*
775                  * Read until a entry/block separator has been found. The next read
776                  * "block" may not fit, so this loop will continue until the EOB or EOF
777                  * has been reached whatever comes first.
778                  */
779                 while ((!$this->isEndOfFileReached()) && (!self::isBlockSeparatorFound($data))) {
780                         // Then read the next possible block
781                         $block = $this->read($length);
782
783                         // Is it all empty?
784                         if (strlen(trim($block)) == 0) {
785                                 // Mark this block as empty
786                                 $this->markCurrentBlockAsEmpty($length);
787
788                                 // Skip to next block
789                                 continue;
790                         } // END - if
791
792                         // At this block then
793                         $data .= $block;
794
795                         // A debug message
796                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d] data()=%s', __FUNCTION__, __LINE__, strlen($data)));
797                 } // END - if
798
799                 // EOF reached?
800                 if ($this->isEndOfFileReached()) {
801                         // Set whole data as current read block
802                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('Calling setCurrentBlock(' . strlen($data) . ') ...');
803                         $this->setCurrentBlock($data);
804
805                         // Then abort here silently
806                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('EOF reached.');
807                         return;
808                 } // END - if
809
810                 /*
811                  * Init back-buffer which is the data that has been found beyond the
812                  * separator.
813                  */
814                 $this->initBackBuffer();
815
816                 // Separate data
817                 $dataArray = explode(chr(self::SEPARATOR_ENTRIES), $data);
818
819                 // This array must contain two elements
820                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('dataArray=' . print_r($dataArray, TRUE));
821                 assert(count($dataArray) == 2);
822
823                 // Left part is the actual block, right one the back-buffer data
824                 $this->setCurrentBlock($dataArray[0]);
825                 $this->setBackBuffer($dataArray[1]);
826         }
827
828         /**
829          * Checks wether the current entry is valid (not at the end of the file).
830          * This method will return TRUE if an emptied (nulled) entry has been found.
831          *
832          * @return      $isValid        Whether the next entry is valid
833          */
834         public function valid () {
835                 // Make sure the block instance is set
836                 assert($this->getBlockInstance() instanceof Block);
837
838                 // First calculate minimum block length
839                 $length = $this->getBlockInstance()->calculateMinimumBlockLength();
840
841                 // Short be more than zero!
842                 assert($length > 0);
843
844                 // Get current seek position
845                 $seekPosition = $this->key();
846
847                 // Then try to read it
848                 $data = $this->read($length);
849
850                 // If some bytes could be read, all is fine
851                 $isValid = ((is_string($data)) && (strlen($data) > 0));
852
853                 // Get header size
854                 $headerSize = $this->getBlockInstance()->getHeaderSize();
855
856                 // Is the seek position at or beyond the header?
857                 if ($seekPosition >= $headerSize) {
858                         // Seek back to old position
859                         $this->seek($seekPosition);
860                 } else {
861                         // Seek directly behind the header
862                         $this->seek($headerSize);
863                 }
864
865                 // Return result
866                 return $isValid;
867         }
868
869         /**
870          * Gets current seek position ("key").
871          *
872          * @return      $key    Current key in iteration
873          */
874         public function key () {
875                 // Call pointer instance
876                 return $this->getPointerInstance()->determineSeekPosition();
877         }
878
879         /**
880          * Reads the file header
881          *
882          * @return      void
883          */
884         public function readFileHeader () {
885                 // Make sure the block instance is set
886                 assert($this->getBlockInstance() instanceof Block);
887
888                 // Call block instance
889                 $this->getBlockInstance()->readFileHeader();
890         }
891
892         /**
893          * Flushes the file header
894          *
895          * @return      void
896          */
897         public function flushFileHeader () {
898                 // Make sure the block instance is set
899                 assert($this->getBlockInstance() instanceof Block);
900
901                 // Call block instance
902                 $this->getBlockInstance()->flushFileHeader();
903         }
904 }
905
906 // [EOF]
907 ?>