More cleanups of public closeFile() method as it is private now and shall only
[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 - 2015 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
41         /**
42          * Reads the file header
43          *
44          * @return      void
45          * @todo        To hard assertions here, better rewrite them to exceptions
46          */
47         public function readFileHeader () {
48                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
49
50                 // First rewind to beginning as the header sits at the beginning ...
51                 $this->getIteratorInstance()->rewind();
52
53                 // Then read it (see constructor for calculation)
54                 $data = $this->getIteratorInstance()->read($this->getIteratorInstance()->getHeaderSize());
55                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Read %d bytes (%d wanted).', __METHOD__, __LINE__, strlen($data), $this->getIteratorInstance()->getHeaderSize()));
56
57                 // Have all requested bytes been read?
58                 assert(strlen($data) == $this->getIteratorInstance()->getHeaderSize());
59                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
60
61                 // Last character must be the separator
62                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] data(-1)=%s', __METHOD__, __LINE__, dechex(ord(substr($data, -1, 1)))));
63                 assert(substr($data, -1, 1) == chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES));
64                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
65
66                 // Okay, then remove it
67                 $data = substr($data, 0, -1);
68
69                 // And update seek position
70                 $this->getIteratorInstance()->updateSeekPosition();
71
72                 /*
73                  * Now split it:
74                  *
75                  * 0 => magic
76                  * 1 => total entries
77                  * 2 => current seek position
78                  */
79                 $header = explode(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA), $data);
80
81                 // Set header here
82                 $this->getIteratorInstance()->setHeader($header);
83
84                 // Check if the array has only 3 elements
85                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] header(%d)=%s', __METHOD__, __LINE__, count($header), print_r($header, TRUE)));
86                 assert(count($header) == 3);
87                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
88
89                 // Check magic
90                 assert($header[0] == self::STACK_MAGIC);
91                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
92
93                 // Check length of count and seek position
94                 assert(strlen($header[1]) == BaseBinaryFile::LENGTH_COUNT);
95                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
96                 assert(strlen($header[2]) == BaseBinaryFile::LENGTH_POSITION);
97                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
98
99                 // Decode count and seek position
100                 $header[1] = hex2bin($header[1]);
101                 $header[2] = hex2bin($header[2]);
102
103                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
104         }
105
106         /**
107          * Flushes the file header
108          *
109          * @return      void
110          */
111         public function flushFileHeader () {
112                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
113
114                 // Put all informations together
115                 $header = sprintf('%s%s%s%s%s%s',
116                         // Magic
117                         self::STACK_MAGIC,
118
119                         // Separator magic<->count
120                         chr(BaseBinaryFile::SEPARATOR_HEADER_DATA),
121
122                         // Total entries (will be zero) and pad it to 20 chars
123                         str_pad($this->dec2hex($this->getIteratorInstance()->getCounter()), BaseBinaryFile::LENGTH_COUNT, '0', STR_PAD_LEFT),
124
125                         // Separator count<->seek position
126                         chr(BaseBinaryFile::SEPARATOR_HEADER_DATA),
127
128                         // Position (will be zero)
129                         str_pad($this->dec2hex($this->getIteratorInstance()->getSeekPosition(), 2), BaseBinaryFile::LENGTH_POSITION, '0', STR_PAD_LEFT),
130
131                         // Separator position<->entries
132                         chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES)
133                 );
134
135                 // Write it to disk (header is always at seek position 0)
136                 $this->getIteratorInstance()->writeData(0, $header, FALSE);
137
138                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
139         }
140
141         /**
142          * Initializes this file-based stack.
143          *
144          * @param       $fileName       File name of this stack
145          * @param       $type           Type of this stack (e.g. url_source for URL sources)
146          * @return      void
147          * @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.
148          */
149         protected function initFileStack ($fileName, $type) {
150                 // Get a stack file instance
151                 $fileInstance = ObjectFactory::createObjectByConfiguredName('stack_file_class', array($fileName, $this));
152
153                 // Get iterator instance
154                 $iteratorInstance = ObjectFactory::createObjectByConfiguredName('file_iterator_class', array($fileInstance));
155
156                 // Is the instance implementing the right interface?
157                 assert($iteratorInstance instanceof SeekableWritableFileIterator);
158
159                 // Set iterator here
160                 $this->setIteratorInstance($iteratorInstance);
161
162                 // Calculate header size
163                 $this->getIteratorInstance()->setHeaderSize(
164                         strlen(self::STACK_MAGIC) +
165                         strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA)) +
166                         BaseBinaryFile::LENGTH_COUNT +
167                         strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA)) +
168                         BaseBinaryFile::LENGTH_POSITION +
169                         strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES))
170                 );
171
172                 // Init counters and gaps array
173                 $this->getIteratorInstance()->initCountersGapsArray();
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          * Determines whether the EOF has been reached
366          *
367          * @return      $isEndOfFileReached             Whether the EOF has been reached
368          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
369          */
370         public function isEndOfFileReached () {
371                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
372         }
373
374         /**
375          * Getter for file name
376          *
377          * @return      $fileName       The current file name
378          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
379          */
380         public function getFileName () {
381                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
382         }
383
384         /**
385          * Getter for size of given stack (array count)
386          *
387          * @param       $stackerName    Name of the stack
388          * @return      $count                  Size of stack (array count)
389          */
390         public function getStackCount ($stackerName) {
391                 // Now, simply return the found count value, this must be up-to-date then!
392                 return $this->getIteratorInstance()->getCounter();
393         }
394
395         /**
396          * Calculates minimum length for one entry/block
397          *
398          * @return      $length         Minimum length for one entry/block
399          */
400         public function calculateMinimumBlockLength () {
401                 // Calulcate it
402                 $length = self::getHashLength() + strlen(chr(BaseBinaryFile::SEPARATOR_HASH_NAME)) + BaseBinaryFile::LENGTH_NAME + 1 + strlen(chr(BaseBinaryFile::SEPARATOR_ENTRIES));
403
404                 // Return it
405                 return $length;
406         }
407
408         /**
409          * Initializes counter for valid entries, arrays for damaged entries and
410          * an array for gap seek positions. If you call this method on your own,
411          * please re-analyze the file structure. So you are better to call
412          * analyzeFile() instead of this method.
413          *
414          * @return      void
415          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
416          */
417         public function initCountersGapsArray () {
418                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
419         }
420
421         /**
422          * Getter for header size
423          *
424          * @return      $totalEntries   Size of file header
425          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
426          */
427         public final function getHeaderSize () {
428                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
429         }
430
431         /**
432          * Setter for header size
433          *
434          * @param       $headerSize             Size of file header
435          * @return      void
436          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
437          */
438         public final function setHeaderSize ($headerSize) {
439                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
440         }
441
442         /**
443          * Getter for header array
444          *
445          * @return      $totalEntries   Size of file header
446          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
447          */
448         public final function getHeader () {
449                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
450         }
451
452         /**
453          * Setter for header
454          *
455          * @param       $header         Array for a file header
456          * @return      void
457          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
458          */
459         public final function setHeader (array $header) {
460                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
461         }
462
463         /**
464          * Updates seekPosition attribute from file to avoid to much access on file.
465          *
466          * @return      void
467          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
468          */
469         public function updateSeekPosition () {
470                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
471         }
472
473         /**
474          * Getter for total entries
475          *
476          * @return      $totalEntries   Total entries in this file
477          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
478          */
479         public final function getCounter () {
480                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
481         }
482
483         /**
484          * "Getter" for file size
485          *
486          * @return      $fileSize       Size of currently loaded file
487          */
488         public function getFileSize () {
489                 // Call iterator's method
490                 return $this->getIteratorInstance()->getFileSize();
491         }
492 }
493
494 // [EOF]
495 ?>