Added new interfaces Handleable/-DataSet and ProtocolHandler (no content yet).
[core.git] / inc / classes / main / index / class_BaseIndex.php
1 <?php
2 /**
3  * A general index class
4  *
5  * @author              Roland Haeder <webmaster@ship-simu.org>
6  * @version             0.0.0
7  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2014 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 BaseIndex extends BaseFrameworkSystem {
25         /**
26          * Magic for this index
27          */
28         const INDEX_MAGIC = 'INDEXv0.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          */
46         public function readFileHeader () {
47                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
48
49                 // First rewind to beginning as the header sits at the beginning ...
50                 $this->getIteratorInstance()->rewind();
51
52                 // Then read it (see constructor for calculation)
53                 $data = $this->getIteratorInstance()->read($this->getIteratorInstance()->getHeaderSize());
54                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Read %d bytes (%d wanted).', __METHOD__, __LINE__, strlen($data), $this->getIteratorInstance()->getHeaderSize()));
55
56                 // Have all requested bytes been read?
57                 assert(strlen($data) == $this->getIteratorInstance()->getHeaderSize());
58                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
59
60                 // Last character must be the separator
61                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] data(-1)=%s', __METHOD__, __LINE__, dechex(ord(substr($data, -1, 1)))));
62                 assert(substr($data, -1, 1) == chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES));
63                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
64
65                 // Okay, then remove it
66                 $data = substr($data, 0, -1);
67
68                 // And update seek position
69                 $this->getIteratorInstance()->updateSeekPosition();
70
71                 /*
72                  * Now split it:
73                  *
74                  * 0 => magic
75                  * 1 => total entries
76                  */
77                 $header = explode(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA), $data);
78
79                 // Set it here
80                 $this->getIteratorInstance()->setHeader($header);
81
82                 // Check if the array has only 3 elements
83                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] header(%d)=%s', __METHOD__, __LINE__, count($header), print_r($header, TRUE)));
84                 assert(count($header) == 2);
85                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
86
87                 // Check magic
88                 assert($header[0] == self::INDEX_MAGIC);
89                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
90
91                 // Check length of count
92                 assert(strlen($header[1]) == BaseBinaryFile::LENGTH_COUNT);
93                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
94
95                 // Decode count
96                 $header[1] = hex2bin($header[1]);
97
98                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
99         }
100
101         /**
102          * Flushes the file header
103          *
104          * @return      void
105          */
106         public function flushFileHeader () {
107                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
108
109                 // Put all informations together
110                 $header = sprintf('%s%s%s%s',
111                         // Magic
112                         self::INDEX_MAGIC,
113
114                         // Separator header data
115                         chr(BaseBinaryFile::SEPARATOR_HEADER_DATA),
116
117                         // Total entries
118                         str_pad($this->dec2hex($this->getIteratorInstance()->getCounter()), BaseBinaryFile::LENGTH_COUNT, '0', STR_PAD_LEFT),
119
120                         // Separator header<->entries
121                         chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES)
122                 );
123
124                 // Write it to disk (header is always at seek position 0)
125                 $this->getIteratorInstance()->writeData(0, $header, FALSE);
126
127                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
128         }
129
130         /**
131          * Initializes this index
132          *
133          * @param       $fileName       File name of this index
134          * @return      void
135          * @todo        Currently the index file is not cached, please implement a memory-handling class and if enough RAM is found, cache the whole index file.
136          */
137         protected function initIndex ($fileName) {
138                 // Append index file extension
139                 $fileName .= $this->getConfigInstance()->getConfigEntry('index_extension');
140
141                 // Get a file i/o pointer instance for index file
142                 $fileInstance = ObjectFactory::createObjectByConfiguredName('index_file_class', array($fileName, $this));
143
144                 // Get iterator instance
145                 $iteratorInstance = ObjectFactory::createObjectByConfiguredName('file_iterator_class', array($fileInstance));
146
147                 // Is the instance implementing the right interface?
148                 assert($iteratorInstance instanceof SeekableWritableFileIterator);
149
150                 // Set iterator here
151                 $this->setIteratorInstance($iteratorInstance);
152
153                 // Calculate header size
154                 $this->getIteratorInstance()->setHeaderSize(
155                         strlen(self::INDEX_MAGIC) +
156                         strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA)) +
157                         BaseBinaryFile::LENGTH_COUNT +
158                         strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES))
159                 );
160
161                 // Init counters and gaps array
162                 $this->getIteratorInstance()->initCountersGapsArray();
163
164                 // Is the file's header initialized?
165                 if (!$this->getIteratorInstance()->isFileHeaderInitialized()) {
166                         // No, then create it (which may pre-allocate the index)
167                         $this->getIteratorInstance()->createFileHeader();
168
169                         // And pre-allocate a bit
170                         $this->getIteratorInstance()->preAllocateFile('index');
171                 } // END - if
172
173                 // Load the file header
174                 $this->readFileHeader();
175
176                 // Count all entries in file
177                 $this->getIteratorInstance()->analyzeFile();
178         }
179
180         /**
181          * Calculates minimum length for one entry/block
182          *
183          * @return      $length         Minimum length for one entry/block
184          */
185         public function calculateMinimumBlockLength () {
186                 // Calulcate it
187                 $length = BaseBinaryFile::LENGTH_TYPE + strlen(chr(BaseBinaryFile::SEPARATOR_TYPE_POSITION)) + BaseBinaryFile::LENGTH_POSITION + strlen(chr(BaseBinaryFile::SEPARATOR_ENTRIES));
188
189                 // Return it
190                 return $length;
191         }
192
193         /**
194          * Close a file source and set it's instance to null and the file name
195          * to empty.
196          *
197          * @return      void
198          * @throws      UnsupportedOperationException   If this method is called
199          */
200         public function closeFile () {
201                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
202         }
203
204         /**
205          * Determines whether the EOF has been reached
206          *
207          * @return      $isEndOfFileReached             Whether the EOF has been reached
208          * @throws      UnsupportedOperationException   If this method is called
209          */
210         public function isEndOfFileReached () {
211                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
212         }
213
214         /**
215          * Getter for file name
216          *
217          * @return      $fileName       The current file name
218          * @throws      UnsupportedOperationException   If this method is called
219          */
220         public function getFileName () {
221                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
222         }
223
224         /**
225          * Initializes counter for valid entries, arrays for damaged entries and
226          * an array for gap seek positions. If you call this method on your own,
227          * please re-analyze the file structure. So you are better to call
228          * analyzeFile() instead of this method.
229          *
230          * @return      void
231          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
232          */
233         public function initCountersGapsArray () {
234                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
235         }
236
237         /**
238          * Getter for header size
239          *
240          * @return      $totalEntries   Size of file header
241          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
242          */
243         public final function getHeaderSize () {
244                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
245         }
246
247         /**
248          * Setter for header size
249          *
250          * @param       $headerSize             Size of file header
251          * @return      void
252          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
253          */
254         public final function setHeaderSize ($headerSize) {
255                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
256         }
257
258         /**
259          * Getter for header array
260          *
261          * @return      $totalEntries   Size of file header
262          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
263          */
264         public final function getHeader () {
265                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
266         }
267
268         /**
269          * Setter for header
270          *
271          * @param       $header         Array for a file header
272          * @return      void
273          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
274          */
275         public final function setHeader (array $header) {
276                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
277         }
278
279         /**
280          * Updates seekPosition attribute from file to avoid to much access on file.
281          *
282          * @return      void
283          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
284          */
285         public function updateSeekPosition () {
286                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
287         }
288
289         /**
290          * Getter for total entries
291          *
292          * @return      $totalEntries   Total entries in this file
293          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
294          */
295         public final function getCounter () {
296                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
297         }
298
299         /**
300          * "Getter" for file size
301          *
302          * @return      $fileSize       Size of currently loaded file
303          */
304         public function getFileSize () {
305                 // Call iterator's method
306                 return $this->getIteratorInstance()->getFileSize();
307         }
308 }
309
310 // [EOF]
311 ?>