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