Could generalize ("generic") more code which avoid some duplicate fields and methods...
[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         private 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                 $this->header = explode(chr(self::SEPARATOR_HEADER_DATA), $data);
112
113                 // Check if the array has only 3 elements
114                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] header(%d)=%s', __METHOD__, __LINE__, count($this->header), print_r($this->header, TRUE)));
115                 assert(count($this->header) == 3);
116                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
117
118                 // Check magic
119                 assert($this->header[0] == self::STACK_MAGIC);
120                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
121
122                 // Check length of count and seek position
123                 assert(strlen($this->header[1]) == self::LENGTH_COUNT);
124                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
125                 assert(strlen($this->header[2]) == self::LENGTH_POSITION);
126                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
127
128                 // Decode count and seek position
129                 $this->header[1] = hex2bin($this->header[1]);
130                 $this->header[2] = hex2bin($this->header[2]);
131
132                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
133         }
134
135         /**
136          * Flushes the file header
137          *
138          * @return      void
139          */
140         private function flushFileHeader () {
141                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
142
143                 // Put all informations together
144                 $header = sprintf('%s%s%s%s%s%s',
145                         // Magic
146                         self::STACK_MAGIC,
147
148                         // Separator magic<->count
149                         chr(self::SEPARATOR_HEADER_DATA),
150
151                         // Total entries (will be zero) and pad it to 20 chars
152                         str_pad($this->dec2hex($this->getCounter()), self::LENGTH_COUNT, '0', STR_PAD_LEFT),
153
154                         // Separator count<->seek position
155                         chr(self::SEPARATOR_HEADER_DATA),
156
157                         // Position (will be zero)
158                         str_pad($this->dec2hex($this->getSeekPosition(), 2), self::LENGTH_POSITION, '0', STR_PAD_LEFT),
159
160                         // Separator position<->entries
161                         chr(self::SEPARATOR_HEADER_ENTRIES)
162                 );
163
164                 // Write it to disk (header is always at seek position 0)
165                 $this->writeData(0, $header);
166
167                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
168         }
169
170         /**
171          * Analyzes entries in stack file. This will count all found (and valid)
172          * entries, mark invalid as damaged and count gaps ("fragmentation"). If
173          * only gaps are found, the file is considered as "virgin" (no entries).
174          *
175          * @return      void
176          */
177         private function analyzeFile () {
178                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
179
180                 // Make sure the file is initialized
181                 assert($this->isFileInitialized());
182
183                 // Init counters and gaps array
184                 $this->initCountersGapsArray();
185
186                 // Output message (as this may take some time)
187                 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Analyzing file structure ... (this may take some time)', __METHOD__, __LINE__));
188
189                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
190         }
191
192         /**
193          * Initializes this file-based stack.
194          *
195          * @param       $fileName       File name of this stack
196          * @param       $type           Type of this stack (e.g. url_source for URL sources)
197          * @return      void
198          */
199         protected function initFileStack ($fileName, $type) {
200                 // Get a file i/o pointer instance for stack file
201                 $pointerInstance = ObjectFactory::createObjectByConfiguredName('file_raw_input_output_class', array($fileName));
202
203                 // Get iterator instance
204                 $iteratorInstance = ObjectFactory::createObjectByConfiguredName('file_io_iterator_class', array($pointerInstance));
205
206                 // Is the instance implementing the right interface?
207                 assert($iteratorInstance instanceof SeekableWritableFileIterator);
208
209                 // Set iterator here
210                 $this->setIteratorInstance($iteratorInstance);
211
212                 // Is the file's header initialized?
213                 if (!$this->isFileHeaderInitialized()) {
214                         // No, then create it (which may pre-allocate the stack)
215                         $this->createFileHeader();
216
217                         // And pre-allocate a bit
218                         $this->preAllocateFile('file_stack');
219                 } // END - if
220
221                 // Load the file header
222                 $this->readFileHeader();
223
224                 // Count all entries in file
225                 $this->analyzeFile();
226
227                 /*
228                  * Get stack index instance. This can be used for faster
229                  * "defragmentation" and startup.
230                  */
231                 $indexInstance = FileStackIndexFactory::createFileStackIndexInstance($fileName, $type);
232
233                 // And set it here
234                 $this->setIndexInstance($indexInstance);
235         }
236
237         /**
238          * Adds a value to given stack
239          *
240          * @param       $stackerName    Name of the stack
241          * @param       $value                  Value to add to this stacker
242          * @return      void
243          * @throws      FullStackerException    If the stack is full
244          */
245         protected function addValue ($stackerName, $value) {
246                 // Do some tests
247                 if ($this->isStackFull($stackerName)) {
248                         // Stacker is full
249                         throw new FullStackerException(array($this, $stackerName, $value), self::EXCEPTION_STACKER_IS_FULL);
250                 } // END - if
251
252                 // Now add the value to the stack
253                 $this->partialStub('stackerName=' . $stackerName . ',value[]=' . gettype($value));
254         }
255
256         /**
257          * Get last value from named stacker
258          *
259          * @param       $stackerName    Name of the stack
260          * @return      $value                  Value of last added value
261          * @throws      EmptyStackerException   If the stack is empty
262          */
263         protected function getLastValue ($stackerName) {
264                 // Is the stack not yet initialized or full?
265                 if ($this->isStackEmpty($stackerName)) {
266                         // Throw an exception
267                         throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
268                 } // END - if
269
270                 // Now get the last value
271                 $this->partialStub('stackerName=' . $stackerName);
272                 $value = NULL;
273
274                 // Return it
275                 return $value;
276         }
277
278         /**
279          * Get first value from named stacker
280          *
281          * @param       $stackerName    Name of the stack
282          * @return      $value                  Value of last added value
283          * @throws      EmptyStackerException   If the stack is empty
284          */
285         protected function getFirstValue ($stackerName) {
286                 // Is the stack not yet initialized or full?
287                 if ($this->isStackEmpty($stackerName)) {
288                         // Throw an exception
289                         throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
290                 } // END - if
291
292                 // Now get the first value
293                 $this->partialStub('stackerName=' . $stackerName);
294                 $value = NULL;
295
296                 // Return it
297                 return $value;
298         }
299
300         /**
301          * "Pops" last entry from stack
302          *
303          * @param       $stackerName    Name of the stack
304          * @return      $value                  Value "poped" from array
305          * @throws      EmptyStackerException   If the stack is empty
306          */
307         protected function popLast ($stackerName) {
308                 // Is the stack not yet initialized or full?
309                 if ($this->isStackEmpty($stackerName)) {
310                         // Throw an exception
311                         throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
312                 } // END - if
313
314                 // Now, remove the last entry, we don't care about the return value here, see elseif() block above
315                 $this->partialStub('stackerName=' . $stackerName);
316                 return NULL;
317         }
318
319         /**
320          * "Pops" first entry from stack
321          *
322          * @param       $stackerName    Name of the stack
323          * @return      $value                  Value "shifted" from array
324          * @throws      EmptyStackerException   If the named stacker is empty
325          */
326         protected function popFirst ($stackerName) {
327                 // Is the stack not yet initialized or full?
328                 if ($this->isStackEmpty($stackerName)) {
329                         // Throw an exception
330                         throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
331                 } // END - if
332
333                 // Now, remove the last entry, we don't care about the return value here, see elseif() block above
334                 $this->partialStub('stackerName=' . $stackerName);
335                 return NULL;
336         }
337
338         /**
339          * Checks whether the given stack is full
340          *
341          * @param       $stackerName    Name of the stack
342          * @return      $isFull                 Whether the stack is full
343          */
344         protected function isStackFull ($stackerName) {
345                 // File-based stacks will only run full if the disk space is low.
346                 // @TODO Please implement this, returning FALSE
347                 $isFull = FALSE;
348
349                 // Return result
350                 return $isFull;
351         }
352
353         /**
354          * Checks whether the given stack is empty
355          *
356          * @param       $stackerName            Name of the stack
357          * @return      $isEmpty                        Whether the stack is empty
358          * @throws      NoStackerException      If given stack is missing
359          */
360         public function isStackEmpty ($stackerName) {
361                 // So, is the stack empty?
362                 $isEmpty = (($this->getStackCount($stackerName)) == 0);
363
364                 // Return result
365                 return $isEmpty;
366         }
367
368         /**
369          * Initializes given stacker
370          *
371          * @param       $stackerName    Name of the stack
372          * @param       $forceReInit    Force re-initialization
373          * @return      void
374          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
375          */
376         public function initStack ($stackerName, $forceReInit = FALSE) {
377                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
378         }
379
380         /**
381          * Initializes all stacks
382          *
383          * @return      void
384          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
385          */
386         public function initStacks (array $stacks, $forceReInit = FALSE) {
387                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
388         }
389
390         /**
391          * Checks whether the given stack is initialized (set in array $stackers)
392          *
393          * @param       $stackerName    Name of the stack
394          * @return      $isInitialized  Whether the stack is initialized
395          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
396          */
397         public function isStackInitialized ($stackerName) {
398                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
399         }
400
401         /**
402          * Getter for size of given stack (array count)
403          *
404          * @param       $stackerName    Name of the stack
405          * @return      $count                  Size of stack (array count)
406          */
407         public function getStackCount ($stackerName) {
408                 // Now, simply return the found count value, this must be up-to-date then!
409                 return $this->getCounter();
410         }
411 }
412
413 // [EOF]
414 ?>