Continued:
[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 - 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 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          * Determines whether the EOF has been reached
195          *
196          * @return      $isEndOfFileReached             Whether the EOF has been reached
197          * @throws      UnsupportedOperationException   If this method is called
198          */
199         public function isEndOfFileReached () {
200                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
201         }
202
203         /**
204          * Getter for file name
205          *
206          * @return      $fileName       The current file name
207          * @throws      UnsupportedOperationException   If this method is called
208          */
209         public function getFileName () {
210                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
211         }
212
213         /**
214          * Initializes counter for valid entries, arrays for damaged entries and
215          * an array for gap seek positions. If you call this method on your own,
216          * please re-analyze the file structure. So you are better to call
217          * analyzeFile() instead of this method.
218          *
219          * @return      void
220          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
221          */
222         public function initCountersGapsArray () {
223                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
224         }
225
226         /**
227          * Getter for header size
228          *
229          * @return      $totalEntries   Size of file header
230          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
231          */
232         public final function getHeaderSize () {
233                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
234         }
235
236         /**
237          * Setter for header size
238          *
239          * @param       $headerSize             Size of file header
240          * @return      void
241          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
242          */
243         public final function setHeaderSize ($headerSize) {
244                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
245         }
246
247         /**
248          * Getter for header array
249          *
250          * @return      $totalEntries   Size of file header
251          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
252          */
253         public final function getHeader () {
254                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
255         }
256
257         /**
258          * Setter for header
259          *
260          * @param       $header         Array for a file header
261          * @return      void
262          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
263          */
264         public final function setHeader (array $header) {
265                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
266         }
267
268         /**
269          * Updates seekPosition attribute from file to avoid to much access on file.
270          *
271          * @return      void
272          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
273          */
274         public function updateSeekPosition () {
275                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
276         }
277
278         /**
279          * Getter for total entries
280          *
281          * @return      $totalEntries   Total entries in this file
282          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
283          */
284         public final function getCounter () {
285                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
286         }
287
288         /**
289          * "Getter" for file size
290          *
291          * @return      $fileSize       Size of currently loaded file
292          */
293         public function getFileSize () {
294                 // Call iterator's method
295                 return $this->getIteratorInstance()->getFileSize();
296         }
297
298         /**
299          * Writes data at given position
300          *
301          * @param       $seekPosition   Seek position
302          * @param       $data                   Data to be written
303          * @param       $flushHeader    Whether to flush the header (default: flush)
304          * @return      void
305          * @throws      UnsupportedOperationException   This method is not (and maybe never will be) supported
306          */
307         public function writeData ($seekPosition, $data, $flushHeader = TRUE) {
308                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] seekPosition=%s,data[]=%s,flushHeader=%d', __METHOD__, __LINE__, $seekPosition, gettype($data), intval($flushHeader)));
309                 throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
310         }
311
312         /**
313          * Writes given value to the file and returns a hash and gap position for it
314          *
315          * @param       $groupId        Group identifier
316          * @param       $value          Value to be added to the stack
317          * @return      $data           Hash and gap position
318          * @throws      UnsupportedOperationException   If this method is called
319          */
320         public function writeValueToFile ($groupId, $value) {
321                 self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] groupId=' . $groupId . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
322                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
323         }
324
325         /**
326          * Writes given raw data to the file and returns a gap position and length
327          *
328          * @param       $groupId        Group identifier
329          * @param       $hash           Hash from encoded value
330          * @param       $encoded        Encoded value to be written to the file
331          * @return      $data           Gap position and length of the raw data
332          */
333         public function writeDataToFreeGap ($groupId, $hash, $encoded) {
334                 self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] groupId=' . $groupId . ',hash=' . $hash . ',encoded()=' . strlen($encoded));
335                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
336         }
337 }
338
339 // [EOF]
340 ?>