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