If the EOF is reached (means no block found or really reached the last block),
[core.git] / inc / classes / main / stacker / file / class_BaseFileStack.php
1 <?php
2 /**
3  * A general file-based stack class
4  *
5  * @author              Roland Haeder <webmaster@ship-simu.org>
6  * @version             0.0.0
7  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2013 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 BaseFileStack extends BaseStacker {
25         /**
26          * Magic for this stack
27          */
28         const STACK_MAGIC = 'STACKv0.1';
29
30         /**
31          * Protected constructor
32          *
33          * @param       $className      Name of the class
34          * @return      void
35          */
36         protected function __construct ($className) {
37                 // Call parent constructor
38                 parent::__construct($className);
39
40                 // Calculate header size
41                 $this->setHeaderSize(
42                         strlen(self::STACK_MAGIC) +
43                         strlen(self::SEPARATOR_HEADER_DATA) +
44                         self::LENGTH_COUNT +
45                         strlen(self::SEPARATOR_HEADER_DATA) +
46                         self::LENGTH_POSITION +
47                         strlen(self::SEPARATOR_HEADER_ENTRIES)
48                 );
49
50                 // Init counters and gaps array
51                 $this->initCountersGapsArray();
52         }
53
54         /**
55          * Reads the file header
56          *
57          * @return      void
58          */
59         protected function readFileHeader () {
60                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
61
62                 // First rewind to beginning as the header sits at the beginning ...
63                 $this->getIteratorInstance()->rewind();
64
65                 // Then read it (see constructor for calculation)
66                 $data = $this->getIteratorInstance()->read($this->getHeaderSize());
67                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Read %d bytes (%d wanted).', __METHOD__, __LINE__, strlen($data), $this->getHeaderSize()));
68
69                 // Have all requested bytes been read?
70                 assert(strlen($data) == $this->getHeaderSize());
71                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
72
73                 // Last character must be the separator
74                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] data(-1)=%s', __METHOD__, __LINE__, dechex(ord(substr($data, -1, 1)))));
75                 assert(substr($data, -1, 1) == chr(self::SEPARATOR_HEADER_ENTRIES));
76                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
77
78                 // Okay, then remove it
79                 $data = substr($data, 0, -1);
80
81                 // And update seek position
82                 $this->updateSeekPosition();
83
84                 /*
85                  * Now split it:
86                  *
87                  * 0 => magic
88                  * 1 => total entries
89                  * 2 => current seek position
90                  */
91                 $header = explode(chr(self::SEPARATOR_HEADER_DATA), $data);
92
93                 // Set header here
94                 $this->setHeader($header);
95
96                 // Check if the array has only 3 elements
97                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] header(%d)=%s', __METHOD__, __LINE__, count($header), print_r($header, TRUE)));
98                 assert(count($header) == 3);
99                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
100
101                 // Check magic
102                 assert($header[0] == self::STACK_MAGIC);
103                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
104
105                 // Check length of count and seek position
106                 assert(strlen($header[1]) == self::LENGTH_COUNT);
107                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
108                 assert(strlen($header[2]) == self::LENGTH_POSITION);
109                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
110
111                 // Decode count and seek position
112                 $header[1] = hex2bin($header[1]);
113                 $header[2] = hex2bin($header[2]);
114
115                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
116         }
117
118         /**
119          * Flushes the file header
120          *
121          * @return      void
122          */
123         protected function flushFileHeader () {
124                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
125
126                 // Put all informations together
127                 $header = sprintf('%s%s%s%s%s%s',
128                         // Magic
129                         self::STACK_MAGIC,
130
131                         // Separator magic<->count
132                         chr(self::SEPARATOR_HEADER_DATA),
133
134                         // Total entries (will be zero) and pad it to 20 chars
135                         str_pad($this->dec2hex($this->getCounter()), self::LENGTH_COUNT, '0', STR_PAD_LEFT),
136
137                         // Separator count<->seek position
138                         chr(self::SEPARATOR_HEADER_DATA),
139
140                         // Position (will be zero)
141                         str_pad($this->dec2hex($this->getSeekPosition(), 2), self::LENGTH_POSITION, '0', STR_PAD_LEFT),
142
143                         // Separator position<->entries
144                         chr(self::SEPARATOR_HEADER_ENTRIES)
145                 );
146
147                 // Write it to disk (header is always at seek position 0)
148                 $this->writeData(0, $header, FALSE);
149
150                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
151         }
152
153         /**
154          * Analyzes entries in stack file. This will count all found (and valid)
155          * entries, mark invalid as damaged and count gaps ("fragmentation"). If
156          * only gaps are found, the file is considered as "virgin" (no entries).
157          *
158          * @return      void
159          */
160         private function analyzeFile () {
161                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
162
163                 // Make sure the file is initialized
164                 assert($this->isFileInitialized());
165
166                 // Init counters and gaps array
167                 $this->initCountersGapsArray();
168
169                 // Output message (as this may take some time)
170                 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Analyzing file structure ... (this may take some time)', __METHOD__, __LINE__));
171
172                 // First rewind to the begining
173                 $this->getIteratorInstance()->rewind();
174
175                 // Then try to load all entries
176                 while ($this->getIteratorInstance()->valid()) {
177                         // Go to next entry
178                         $this->getIteratorInstance()->next();
179
180                         // Get current entry
181                         $current = $this->getIteratorInstance()->current();
182
183                         // Simply output it
184                         self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] current(%s)=%s', __METHOD__, __LINE__, strlen($current), print_r($current, TRUE)));
185                 } // END - while
186
187                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
188         }
189
190         /**
191          * Initializes this file-based stack.
192          *
193          * @param       $fileName       File name of this stack
194          * @param       $type           Type of this stack (e.g. url_source for URL sources)
195          * @return      void
196          * @todo        Currently the stack file is not cached, please implement a memory-handling class and if enough RAM is found, cache the whole stack file.
197          */
198         protected function initFileStack ($fileName, $type) {
199                 // Get a stack file instance
200                 $fileInstance = ObjectFactory::createObjectByConfiguredName('stack_file_class', array($fileName));
201
202                 // Get iterator instance
203                 $iteratorInstance = ObjectFactory::createObjectByConfiguredName('file_io_iterator_class', array($fileInstance, $this));
204
205                 // Is the instance implementing the right interface?
206                 assert($iteratorInstance instanceof SeekableWritableFileIterator);
207
208                 // Set iterator here
209                 $this->setIteratorInstance($iteratorInstance);
210
211                 // Is the file's header initialized?
212                 if (!$this->isFileHeaderInitialized()) {
213                         // No, then create it (which may pre-allocate the stack)
214                         $this->createFileHeader();
215
216                         // And pre-allocate a bit
217                         $this->preAllocateFile('file_stack');
218                 } // END - if
219
220                 // Load the file header
221                 $this->readFileHeader();
222
223                 // Count all entries in file
224                 $this->analyzeFile();
225
226                 /*
227                  * Get stack index instance. This can be used for faster
228                  * "defragmentation" and startup.
229                  */
230                 $indexInstance = FileStackIndexFactory::createFileStackIndexInstance($fileName, $type);
231
232                 // And set it here
233                 $this->setIndexInstance($indexInstance);
234         }
235
236         /**
237          * Adds a value to given stack
238          *
239          * @param       $stackerName    Name of the stack
240          * @param       $value                  Value to add to this stacker
241          * @return      void
242          * @throws      FullStackerException    If the stack is full
243          */
244         protected function addValue ($stackerName, $value) {
245                 // Do some tests
246                 if ($this->isStackFull($stackerName)) {
247                         // Stacker is full
248                         throw new FullStackerException(array($this, $stackerName, $value), self::EXCEPTION_STACKER_IS_FULL);
249                 } // END - if
250
251                 // Now add the value to the stack
252                 $this->partialStub('stackerName=' . $stackerName . ',value[]=' . gettype($value));
253         }
254
255         /**
256          * Get last value from named stacker
257          *
258          * @param       $stackerName    Name of the stack
259          * @return      $value                  Value of last added value
260          * @throws      EmptyStackerException   If the stack is empty
261          */
262         protected function getLastValue ($stackerName) {
263                 // Is the stack not yet initialized or full?
264                 if ($this->isStackEmpty($stackerName)) {
265                         // Throw an exception
266                         throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
267                 } // END - if
268
269                 // Now get the last value
270                 $this->partialStub('stackerName=' . $stackerName);
271                 $value = NULL;
272
273                 // Return it
274                 return $value;
275         }
276
277         /**
278          * Get first value from named stacker
279          *
280          * @param       $stackerName    Name of the stack
281          * @return      $value                  Value of last added value
282          * @throws      EmptyStackerException   If the stack is empty
283          */
284         protected function getFirstValue ($stackerName) {
285                 // Is the stack not yet initialized or full?
286                 if ($this->isStackEmpty($stackerName)) {
287                         // Throw an exception
288                         throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
289                 } // END - if
290
291                 // Now get the first value
292                 $this->partialStub('stackerName=' . $stackerName);
293                 $value = NULL;
294
295                 // Return it
296                 return $value;
297         }
298
299         /**
300          * "Pops" last entry from stack
301          *
302          * @param       $stackerName    Name of the stack
303          * @return      $value                  Value "poped" from array
304          * @throws      EmptyStackerException   If the stack is empty
305          */
306         protected function popLast ($stackerName) {
307                 // Is the stack not yet initialized or full?
308                 if ($this->isStackEmpty($stackerName)) {
309                         // Throw an exception
310                         throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
311                 } // END - if
312
313                 // Now, remove the last entry, we don't care about the return value here, see elseif() block above
314                 $this->partialStub('stackerName=' . $stackerName);
315                 return NULL;
316         }
317
318         /**
319          * "Pops" first entry from stack
320          *
321          * @param       $stackerName    Name of the stack
322          * @return      $value                  Value "shifted" from array
323          * @throws      EmptyStackerException   If the named stacker is empty
324          */
325         protected function popFirst ($stackerName) {
326                 // Is the stack not yet initialized or full?
327                 if ($this->isStackEmpty($stackerName)) {
328                         // Throw an exception
329                         throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
330                 } // END - if
331
332                 // Now, remove the last entry, we don't care about the return value here, see elseif() block above
333                 $this->partialStub('stackerName=' . $stackerName);
334                 return NULL;
335         }
336
337         /**
338          * Checks whether the given stack is full
339          *
340          * @param       $stackerName    Name of the stack
341          * @return      $isFull                 Whether the stack is full
342          */
343         protected function isStackFull ($stackerName) {
344                 // File-based stacks will only run full if the disk space is low.
345                 // @TODO Please implement this, returning FALSE
346                 $isFull = FALSE;
347
348                 // Return result
349                 return $isFull;
350         }
351
352         /**
353          * Checks whether the given stack is empty
354          *
355          * @param       $stackerName            Name of the stack
356          * @return      $isEmpty                        Whether the stack is empty
357          * @throws      NoStackerException      If given stack is missing
358          */
359         public function isStackEmpty ($stackerName) {
360                 // So, is the stack empty?
361                 $isEmpty = (($this->getStackCount($stackerName)) == 0);
362
363                 // Return result
364                 return $isEmpty;
365         }
366
367         /**
368          * Initializes given stacker
369          *
370          * @param       $stackerName    Name of the stack
371          * @param       $forceReInit    Force re-initialization
372          * @return      void
373          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
374          */
375         public function initStack ($stackerName, $forceReInit = FALSE) {
376                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
377         }
378
379         /**
380          * Initializes all stacks
381          *
382          * @return      void
383          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
384          */
385         public function initStacks (array $stacks, $forceReInit = FALSE) {
386                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
387         }
388
389         /**
390          * Checks whether the given stack is initialized (set in array $stackers)
391          *
392          * @param       $stackerName    Name of the stack
393          * @return      $isInitialized  Whether the stack is initialized
394          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
395          */
396         public function isStackInitialized ($stackerName) {
397                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
398         }
399
400         /**
401          * Getter for size of given stack (array count)
402          *
403          * @param       $stackerName    Name of the stack
404          * @return      $count                  Size of stack (array count)
405          */
406         public function getStackCount ($stackerName) {
407                 // Now, simply return the found count value, this must be up-to-date then!
408                 return $this->getCounter();
409         }
410
411         /**
412          * Calculates minimum length for one entry/block
413          *
414          * @return      $length         Minimum length for one entry/block
415          */
416         public function caluclateMinimumBlockLength () {
417                 // Calulcate it
418                 $length = self::getHashLength() + strlen(chr(self::SEPARATOR_HASH_NAME)) + self::LENGTH_NAME + 1 + strlen(self::getBlockSeparator());
419
420                 // Return it
421                 return $length;
422         }
423 }
424
425 // [EOF]
426 ?>