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