Added simple loop for checking entries. This will change in the future which is
[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 - 2012 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          * 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          * Protected constructor
42          *
43          * @param       $className      Name of the class
44          * @return      void
45          */
46         protected function __construct ($className) {
47                 // Call parent constructor
48                 parent::__construct($className);
49
50                 // Calculate header size
51                 $this->setHeaderSize(
52                         strlen(self::INDEX_MAGIC) +
53                         strlen(self::SEPARATOR_HEADER_DATA) +
54                         self::LENGTH_COUNT +
55                         strlen(self::SEPARATOR_HEADER_ENTRIES)
56                 );
57
58                 // Init counters and gaps array
59                 $this->initCountersGapsArray();
60         }
61
62         /**
63          * Reads the file header
64          *
65          * @return      void
66          */
67         protected function readFileHeader () {
68                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
69
70                 // First rewind to beginning as the header sits at the beginning ...
71                 $this->getIteratorInstance()->rewind();
72
73                 // Then read it (see constructor for calculation)
74                 $data = $this->getIteratorInstance()->read($this->getHeaderSize());
75                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Read %d bytes (%d wanted).', __METHOD__, __LINE__, strlen($data), $this->getHeaderSize()));
76
77                 // Have all requested bytes been read?
78                 assert(strlen($data) == $this->getHeaderSize());
79                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
80
81                 // Last character must be the separator
82                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] data(-1)=%s', __METHOD__, __LINE__, dechex(ord(substr($data, -1, 1)))));
83                 assert(substr($data, -1, 1) == chr(self::SEPARATOR_HEADER_ENTRIES));
84                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
85
86                 // Okay, then remove it
87                 $data = substr($data, 0, -1);
88
89                 // And update seek position
90                 $this->updateSeekPosition();
91
92                 /*
93                  * Now split it:
94                  *
95                  * 0 => magic
96                  * 1 => total entries
97                  */
98                 $header = explode(chr(self::SEPARATOR_HEADER_DATA), $data);
99
100                 // Set it here
101                 $this->setHeader($header);
102
103                 // Check if the array has only 3 elements
104                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] header(%d)=%s', __METHOD__, __LINE__, count($header), print_r($header, TRUE)));
105                 assert(count($header) == 2);
106                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
107
108                 // Check magic
109                 assert($header[0] == self::INDEX_MAGIC);
110                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
111
112                 // Check length of count
113                 assert(strlen($header[1]) == self::LENGTH_COUNT);
114                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
115
116                 // Decode count
117                 $header[1] = hex2bin($header[1]);
118
119                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
120         }
121
122         /**
123          * Flushes the file header
124          *
125          * @return      void
126          */
127         protected function flushFileHeader () {
128                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
129
130                 // Put all informations together
131                 $header = sprintf('%s%s%s%s',
132                         // Magic
133                         self::INDEX_MAGIC,
134
135                         // Separator header data
136                         chr(self::SEPARATOR_HEADER_DATA),
137
138                         // Total entries
139                         str_pad($this->dec2hex($this->getCounter()), self::LENGTH_COUNT, '0', STR_PAD_LEFT),
140
141                         // Separator header<->entries
142                         chr(self::SEPARATOR_HEADER_ENTRIES)
143                 );
144
145                 // Write it to disk (header is always at seek position 0)
146                 $this->writeData(0, $header, FALSE);
147
148                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
149         }
150
151         /**
152          * Analyzes entries in index file. This will count all found (and valid)
153          * entries, mark invalid as damaged and count gaps ("fragmentation"). If
154          * only gaps are found, the file is considered as "virgin" (no entries).
155          *
156          * @return      void
157          */
158         private function analyzeFile () {
159                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
160
161                 // Make sure the file is initialized
162                 assert($this->isFileInitialized());
163
164                 // Init counters and gaps array
165                 $this->initCountersGapsArray();
166
167                 // Output message (as this may take some time)
168                 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Analyzing file structure ... (this may take some time)', __METHOD__, __LINE__));
169
170                 // First rewind to the begining
171                 $this->getIteratorInstance()->rewind();
172
173                 // Then try to load all entries
174                 while ($this->getIteratorInstance()->next()) {
175                         // Get current entry
176                         $current = $this->getIteratorInstance()->current();
177
178                         // Simply output it
179                         self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] current=%s', __METHOD__, __LINE__, print_r($current, TRUE)));
180                 } // END - while
181
182                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
183         }
184
185         /**
186          * Calculates minimum length for one entry
187          *
188          * @return      $length         Minimum length for one entry
189          */
190         protected function caluclateMinimumFileEntryLength () {
191                 // Calulcate it
192                 // @TODO Not finished yet
193                 $length = 0;
194
195                 // Return it
196                 return $length;
197         }
198
199         /**
200          * Initializes this index
201          *
202          * @param       $fileName       File name of this index
203          * @return      void
204          * @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.
205          */
206         protected function initIndex ($fileName) {
207                 // Append index file extension
208                 $fileName .= $this->getConfigInstance()->getConfigEntry('index_extension');
209
210                 // Get a file i/o pointer instance for index file
211                 $fileInstance = ObjectFactory::createObjectByConfiguredName('index_file_class', array($fileName));
212
213                 // Get iterator instance
214                 $iteratorInstance = ObjectFactory::createObjectByConfiguredName('file_io_iterator_class', array($fileInstance));
215
216                 // Is the instance implementing the right interface?
217                 assert($iteratorInstance instanceof SeekableWritableFileIterator);
218
219                 // Set iterator here
220                 $this->setIteratorInstance($iteratorInstance);
221
222                 // Is the file's header initialized?
223                 if (!$this->isFileHeaderInitialized()) {
224                         // No, then create it (which may pre-allocate the index)
225                         $this->createFileHeader();
226
227                         // And pre-allocate a bit
228                         $this->preAllocateFile('index');
229                 } // END - if
230
231                 // Load the file header
232                 $this->readFileHeader();
233
234                 // Count all entries in file
235                 $this->analyzeFile();
236         }
237 }
238
239 // [EOF]
240 ?>