c6dfc0ee58625cf608fb3135babf752415e04fba
[core.git] / inc / classes / main / database / databases / class_LocalFileDatabase.php
1 <?php
2 /**
3  * Database backend class for storing objects in locally created files.
4  *
5  * This class serializes arrays stored in the dataset instance and saves them
6  * to local files. Every file (except 'info') represents a single line. Every
7  * directory within the 'db' (base) directory represents a table.
8  *
9  * A configurable 'file_io_class' is being used as "storage backend".
10  *
11  * @author              Roland Haeder <webmaster@ship-simu.org>
12  * @version             0.0.0
13  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2012 Core Developer Team
14  * @license             GNU GPL 3.0 or any newer version
15  * @link                http://www.ship-simu.org
16  *
17  * This program is free software: you can redistribute it and/or modify
18  * it under the terms of the GNU General Public License as published by
19  * the Free Software Foundation, either version 3 of the License, or
20  * (at your option) any later version.
21  *
22  * This program is distributed in the hope that it will be useful,
23  * but WITHOUT ANY WARRANTY; without even the implied warranty of
24  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25  * GNU General Public License for more details.
26  *
27  * You should have received a copy of the GNU General Public License
28  * along with this program. If not, see <http://www.gnu.org/licenses/>.
29  */
30 class LocalFileDatabase extends BaseDatabaseBackend implements DatabaseBackendInterface {
31         /**
32          * The file's extension
33          */
34         private $fileExtension = 'serialized';
35
36         /**
37          * The last read file's name
38          */
39         private $lastFile = '';
40
41         /**
42          * The last read file's content including header information
43          */
44         private $lastContents = array();
45
46         /**
47          * Whether the "connection is already up
48          */
49         private $alreadyConnected = false;
50
51         /**
52          * Table information array
53          */
54         private $tableInfo = array();
55
56         /**
57          * Element for index
58          */
59         private $indexKey = '__idx';
60
61         /**
62          * The protected constructor. Do never instance from outside! You need to
63          * set a local file path. The class will then validate it.
64          *
65          * @return      void
66          */
67         protected function __construct () {
68                 // Call parent constructor
69                 parent::__construct(__CLASS__);
70         }
71
72         /**
73          * Create an object of LocalFileDatabase and set the save path from
74          * configuration for local files.
75          *
76          * @return      $databaseInstance       An instance of LocalFileDatabase
77          */
78         public static final function createLocalFileDatabase () {
79                 // Get an instance
80                 $databaseInstance = new LocalFileDatabase();
81
82                 // Get a new compressor channel instance
83                 $compressorInstance = ObjectFactory::createObjectByConfiguredName('compressor_channel_class');
84
85                 // Set the compressor channel
86                 $databaseInstance->setCompressorChannel($compressorInstance);
87
88                 // Get a file IO handler
89                 $fileIoInstance = ObjectFactory::createObjectByConfiguredName('file_io_class');
90
91                 // ... and set it
92                 $databaseInstance->setFileIoInstance($fileIoInstance);
93
94                 // "Connect" to the database
95                 $databaseInstance->connectToDatabase();
96
97                 // Return database instance
98                 return $databaseInstance;
99         }
100
101         /**
102          * Setter for the last read file
103          *
104          * @param       $fqfn   The FQFN of the last read file
105          * @return      void
106          */
107         private final function setLastFile ($fqfn) {
108                 // Cast string and set it
109                 $this->lastFile = (string) $fqfn;
110         }
111
112         /**
113          * Getter for last read file
114          *
115          * @return      $lastFile       The last read file's name with full path
116          */
117         public final function getLastFile () {
118                 return $this->lastFile;
119         }
120
121         /**
122          * Setter for contents of the last read file
123          *
124          * @param               $contents       An array with header and data elements
125          * @return      void
126          */
127         private final function setLastFileContents (array $contents) {
128                 // Set array
129                 $this->lastContents = $contents;
130         }
131
132         /**
133          * Getter for last read file's content as an array
134          *
135          * @return      $lastContent    The array with elements 'header' and 'data'.
136          */
137         public final function getLastContents () {
138                 return $this->lastContents;
139         }
140
141         /**
142          * Getter for file extension
143          *
144          * @return      $fileExtension  The array with elements 'header' and 'data'.
145          */
146         public final function getFileExtension () {
147                 return $this->fileExtension;
148         }
149
150         /**
151          * Getter for index key
152          *
153          * @return      $indexKey       Index key
154          */
155         public final function getIndexKey () {
156                 return $this->indexKey;
157         }
158
159         /**
160          * Reads a local data file  and returns it's contents in an array
161          *
162          * @param       $fqfn   The FQFN for the requested file
163          * @return      $dataArray
164          */
165         private function getDataArrayFromFile ($fqfn) {
166                 // Debug message
167                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DATABASE: Reading elements from database file ' . $fqfn . ' ...');
168
169                 // Init compressed data
170                 $compressedData = $this->getFileIoInstance()->loadFileContents($fqfn);
171                 $compressedData = $compressedData['data'];
172
173                 // Close the file and throw the instance away
174                 unset($fileInstance);
175
176                 // Decompress it
177                 $serializedData = $this->getCompressorChannel()->getCompressor()->decompressStream($compressedData);
178
179                 // Unserialize it
180                 $dataArray = unserialize($serializedData);
181
182                 // Debug message
183                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DATABASE: Read ' . count($dataArray) . ' elements from database file ' . $fqfn . '.');
184
185                 // Finally return it
186                 return $dataArray;
187         }
188
189         /**
190          * Writes data array to local file
191          *
192          * @param       $fqfn           The FQFN of the local file
193          * @param       $dataArray      An array with all the data we shall write
194          * @return      void
195          */
196         private function writeDataArrayToFqfn ($fqfn, array $dataArray) {
197                 // Debug message
198                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DATABASE: Flushing ' . count($dataArray) . ' elements to database file ' . $fqfn . ' ...');
199
200                 // Serialize and compress it
201                 $compressedData = $this->getCompressorChannel()->getCompressor()->compressStream(serialize($dataArray));
202
203                 // Write data
204                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DATABASE: Writing ' . strlen($compressedData) . ' bytes ...');
205
206                 // Write this data BASE64 encoded to the file
207                 $this->getFileIoInstance()->saveFile($fqfn, $compressedData);
208
209                 // Debug message
210                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DATABASE: Flushing ' . count($dataArray) . ' elements to database file completed.');
211         }
212
213         /**
214          * Getter for table information file contents or an empty if info file was not created
215          *
216          * @param       $dataSetInstance        An instance of a database set class
217          * @return      $infoArray                      An array with all table informations
218          */
219         private function getContentsFromTableInfoFile (StoreableCriteria $dataSetInstance) {
220                 // Default content is no data
221                 $infoArray = array();
222
223                 // Create FQFN for getting the table information file
224                 $fqfn = $this->generateFqfnFromDataSet($dataSetInstance, 'info');
225
226                 // Get the file contents
227                 try {
228                         $infoArray = $this->getDataArrayFromFile($fqfn);
229                 } catch (FileIoException $e) {
230                         // Not found, so ignore it here
231                 }
232
233                 // ... and return it
234                 return $infoArray;
235         }
236
237         /**
238          * Generates an FQFN from given dataset instance and string
239          *
240          * @param       $dataSetInstance        An instance of a database set class
241          * @param       $rowName                        Name of the row
242          * @return      $fqfn                           The FQFN for this row
243          */
244         private function generateFqfnFromDataSet (Criteria $dataSetInstance, $rowName) {
245                 // This is the FQFN
246                 $fqfn = $this->getConfigInstance()->getConfigEntry('local_db_path') . $dataSetInstance->getTableName() . '/' . $rowName . '.' . $this->getFileExtension();
247
248                 // Return it
249                 return $fqfn;
250         }
251
252         /**
253          * Creates the table info file from given dataset instance
254          *
255          * @param       $dataSetInstance        An instance of a database set class
256          * @return      void
257          */
258         private function createTableInfoFile (StoreableCriteria $dataSetInstance) {
259                 // Create FQFN for creating the table information file
260                 $fqfn = $this->generateFqfnFromDataSet($dataSetInstance, 'info');
261
262                 // Get the data out from dataset in a local array
263                 $this->tableInfo[$dataSetInstance->getTableName()] = array(
264                         'primary'      => $dataSetInstance->getPrimaryKey(),
265                         'created'      => time(),
266                         'last_updated' => time()
267                 );
268
269                 // Write the data to the file
270                 $this->writeDataArrayToFqfn($fqfn, $this->tableInfo[$dataSetInstance->getTableName()]);
271         }
272
273         /**
274          * Updates the primary key information or creates the table info file if not found
275          *
276          * @param       $dataSetInstance        An instance of a database set class
277          * @return      void
278          */
279         private function updatePrimaryKey (StoreableCriteria $dataSetInstance) {
280                 // Get the information array from lower method
281                 $infoArray = $this->getContentsFromTableInfoFile($dataSetInstance);
282
283                 // Is the primary key there?
284                 if (!isset($this->tableInfo['primary'])) {
285                         // Then create the info file
286                         $this->createTableInfoFile($dataSetInstance);
287                 } elseif (($this->getConfigInstance()->getConfigEntry('db_update_primary_forced') == 'Y') && ($dataSetInstance->getPrimaryKey() != $this->tableInfo['primary'])) {
288                         // Set the array element
289                         $this->tableInfo[$dataSetInstance->getTableName()]['primary'] = $dataSetInstance->getPrimaryKey();
290
291                         // Update the entry
292                         $this->updateTableInfoFile($dataSetInstance);
293                 }
294         }
295
296         /**
297          * Makes sure that the database connection is alive
298          *
299          * @return      void
300          * @todo        Do some checks on the database directory and files here
301          */
302         public function connectToDatabase () {
303         }
304
305         /**
306          * Starts a SELECT query on the database by given return type, table name
307          * and search criteria
308          *
309          * @param       $tableName              Name of the database table
310          * @param       $criteria               Local search criteria class
311          * @return      $resultData             Result data of the query
312          * @throws      UnsupportedCriteriaException    If the criteria is unsupported
313          * @throws      SqlException                                    If an 'SQL error' occurs
314          */
315         public function querySelect ($tableName, LocalSearchCriteria $criteriaInstance) {
316                 // The result is null by any errors
317                 $resultData = NULL;
318
319                 // Create full path name
320                 $pathName = $this->getConfigInstance()->getConfigEntry('local_db_path') . $tableName . '/';
321
322                 // A 'select' query is not that easy on local files, so first try to
323                 // find the 'table' which is in fact a directory on the server
324                 try {
325                         // Get a directory pointer instance
326                         $directoryInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName);
327
328                         // Initialize the result data, this need to be rewritten e.g. if a local file cannot be read
329                         $resultData = array(
330                                 BaseDatabaseBackend::RESULT_INDEX_STATUS => self::RESULT_OKAY,
331                                 BaseDatabaseBackend::RESULT_INDEX_ROWS   => array()
332                         );
333
334                         // Initialize limit/skip
335                         $limitFound = 0;
336                         $skipFound = 0;
337                         $idx = 1;
338
339                         // Read the directory with some exceptions
340                         while (($dataFile = $directoryInstance->readDirectoryExcept(array('.', '..', '.htaccess', '.svn', 'info.' . $this->getFileExtension()))) && (($limitFound < $criteriaInstance->getLimit()) || ($criteriaInstance->getLimit() == 0))) {
341                                 // Does the extension match?
342                                 if (substr($dataFile, -(strlen($this->getFileExtension()))) !== $this->getFileExtension()) {
343                                         // Skip this file!
344                                         continue;
345                                 } // END - if
346
347                                 // Read the file
348                                 $dataArray = $this->getDataArrayFromFile($pathName . $dataFile);
349                                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DATABASE: dataFile=' . $dataFile . ',dataArray='.print_r($dataArray,true));
350
351                                 // Is this an array?
352                                 if (is_array($dataArray)) {
353                                         // Search in the criteria with FMFW (First Matches, First Wins)
354                                         foreach ($dataArray as $key => $value) {
355                                                 // Get criteria element
356                                                 $criteria = $criteriaInstance->getCriteriaElemnent($key);
357
358                                                 // Is the criteria met or none set?
359                                                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DATABASE: criteria[' . gettype($criteria) . ']=' . $criteria . ';()=' . strlen($criteria) . ',criteriaInstance()=' . $criteriaInstance->count() . ',value(' . strlen($value) . ')=' . $value);
360                                                 if (((!is_null($criteria)) && ($criteria == $value)) || ($criteriaInstance->count() == 0))  {
361                                                         // Shall we skip this entry?
362                                                         if ($criteriaInstance->getSkip() > 0) {
363                                                                 // We shall skip some entries
364                                                                 if ($skipFound < $criteriaInstance->getSkip()) {
365                                                                         // Skip this entry
366                                                                         $skipFound++;
367                                                                         break;
368                                                                 } // END - if
369                                                         } // END - if
370
371                                                         // Set id number
372                                                         $dataArray[$this->getIndexKey()] = $idx;
373
374                                                         // Entry found!
375                                                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DATABASE: indexKey=' . $this->getIndexKey() . ',idx=' . $idx . ',dataArray=' . print_r($dataArray, true));
376                                                         $resultData[BaseDatabaseBackend::RESULT_INDEX_ROWS][] = $dataArray;
377
378                                                         // Count found entries up
379                                                         $limitFound++;
380                                                         break;
381                                                 } // END - if
382                                         } // END - foreach
383                                 } else {
384                                         // Throw an exception here
385                                         throw new SqlException(array($this, sprintf("File &#39;%s&#39; contains invalid data.", $dataFile), self::DB_CODE_DATA_FILE_CORRUPT), self::EXCEPTION_SQL_QUERY);
386                                 }
387
388                                 // Count entry up
389                                 $idx++;
390                         } // END - while
391
392                         // Close directory and throw the instance away
393                         $directoryInstance->closeDirectory();
394                         unset($directoryInstance);
395
396                         // Reset last exception
397                         $this->resetLastException();
398                 } catch (PathIsNoDirectoryException $e) {
399                         // Path not found means "table not found" for real databases...
400                         $this->setLastException($e);
401
402                         // So throw an SqlException here with faked error message
403                         throw new SqlException (array($this, sprintf("Table &#39;%s&#39; not found", $tableName), self::DB_CODE_TABLE_MISSING), self::EXCEPTION_SQL_QUERY);
404                 } catch (FrameworkException $e) {
405                         // Catch all exceptions and store them in last error
406                         $this->setLastException($e);
407                 }
408
409                 // Return the gathered result
410                 return $resultData;
411         }
412
413         /**
414          * "Inserts" a data set instance into a local file database folder
415          *
416          * @param       $dataSetInstance        A storeable data set
417          * @return      void
418          * @throws      SqlException    If an SQL error occurs
419          */
420         public function queryInsertDataSet (StoreableCriteria $dataSetInstance) {
421                 // Try to save the request away
422                 try {
423                         // Create full path name
424                         $fqfn = $this->generateFqfnFromDataSet($dataSetInstance, md5($dataSetInstance->getUniqueValue()));
425
426                         // Write the data away
427                         $this->writeDataArrayToFqfn($fqfn, $dataSetInstance->getCriteriaArray());
428
429                         // Update the primary key
430                         $this->updatePrimaryKey($dataSetInstance);
431
432                         // Reset last exception
433                         $this->resetLastException();
434                 } catch (FrameworkException $e) {
435                         // Catch all exceptions and store them in last error
436                         $this->setLastException($e);
437
438                         // Throw an SQL exception
439                         throw new SqlException(array($this, sprintf("Cannot write data to table &#39;%s&#39;, is the table created?", $dataSetInstance->getTableName()), self::DB_CODE_TABLE_UNWRITEABLE), self::EXCEPTION_SQL_QUERY);
440                 }
441         }
442
443         /**
444          * "Updates" a data set instance with a database layer
445          *
446          * @param       $dataSetInstance        A storeable data set
447          * @return      void
448          * @throws      SqlException    If an SQL error occurs
449          */
450         public function queryUpdateDataSet (StoreableCriteria $dataSetInstance) {
451                 // Create full path name
452                 $pathName = $this->getConfigInstance()->getConfigEntry('local_db_path') . $dataSetInstance->getTableName() . '/';
453
454                 // Try all the requests
455                 try {
456                         // Get a file pointer instance
457                         $directoryInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName);
458
459                         // Initialize limit/skip
460                         $limitFound = 0;
461                         $skipFound = 0;
462
463                         // Get the criteria array from the dataset
464                         $criteriaArray = $dataSetInstance->getCriteriaArray();
465
466                         // Get search criteria
467                         $searchInstance = $dataSetInstance->getSearchInstance();
468
469                         // Read the directory with some exceptions
470                         while (($dataFile = $directoryInstance->readDirectoryExcept(array('.', '..', '.htaccess', '.svn', 'info.' . $this->getFileExtension()))) && ($limitFound < $searchInstance->getLimit())) {
471                                 // Does the extension match?
472                                 if (substr($dataFile, -(strlen($this->getFileExtension()))) !== $this->getFileExtension()) {
473                                         // Debug message
474                                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DATABASE: dataFile=' . $dataFile . ',getFileExtension()=' . $this->getFileExtension() . ' - SKIPPED!');
475                                         // Skip this file!
476                                         continue;
477                                 } // END - if
478
479                                 // Open this file for reading
480                                 $dataArray = $this->getDataArrayFromFile($pathName . $dataFile);
481                                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DATABASE: dataFile=' . $dataFile . ',dataArray='.print_r($dataArray,true));
482
483                                 // Is this an array?
484                                 if (is_array($dataArray)) {
485                                         // Search in the criteria with FMFW (First Matches, First Wins)
486                                         foreach ($dataArray as $key => $value) {
487                                                 // Get criteria element
488                                                 $criteria = $searchInstance->getCriteriaElemnent($key);
489                                                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DATABASE: dataFile=' . $dataFile . ',key=' . $key . ',criteria=' . $criteria);
490
491                                                 // Is the criteria met?
492                                                 if (((!is_null($criteria)) && ($criteria == $value)) || ($searchInstance->count() == 0))  {
493                                                         // Shall we skip this entry?
494                                                         if ($searchInstance->getSkip() > 0) {
495                                                                 // We shall skip some entries
496                                                                 if ($skipFound < $searchInstance->getSkip()) {
497                                                                         // Skip this entry
498                                                                         $skipFound++;
499                                                                         break;
500                                                                 } // END - if
501                                                         } // END - if
502
503                                                         // Entry found, so update it
504                                                         foreach ($criteriaArray as $criteriaKey => $criteriaValue) {
505                                                                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DATABASE: criteriaKey=' . $criteriaKey . ',criteriaValue=' . $criteriaValue);
506                                                                 $dataArray[$criteriaKey] = $criteriaValue;
507                                                         } // END - foreach
508
509                                                         // Write the data to a local file
510                                                         $this->writeDataArrayToFqfn($pathName . $dataFile, $dataArray);
511
512                                                         // Count it
513                                                         $limitFound++;
514                                                         break;
515                                                 } // END - if
516                                         } // END - foreach
517                                 } // END - if
518                         } // END - while
519
520                         // Close the file pointer
521                         $directoryInstance->closeDirectory();
522
523                         // Update the primary key
524                         $this->updatePrimaryKey($dataSetInstance);
525
526                         // Reset last exception
527                         $this->resetLastException();
528                 } catch (FrameworkException $e) {
529                         // Catch all exceptions and store them in last error
530                         $this->setLastException($e);
531
532                         // Throw an SQL exception
533                         throw new SqlException(array($this, sprintf("Cannot write data to table &#39;%s&#39;, is the table created?", $dataSetInstance->getTableName()), self::DB_CODE_TABLE_UNWRITEABLE), self::EXCEPTION_SQL_QUERY);
534                 }
535         }
536
537         /**
538          * Getter for primary key of specified table or if not found null will be
539          * returned. This must be database-specific.
540          *
541          * @param       $tableName              Name of the table we need the primary key from
542          * @return      $primaryKey             Primary key column of the given table
543          */
544         public function getPrimaryKeyOfTable ($tableName) {
545                 // Default key is null
546                 $primaryKey = NULL;
547
548                 // Does the table information exist?
549                 if (isset($this->tableInfo[$tableName])) {
550                         // Then return the primary key
551                         $primaryKey = $this->tableInfo[$tableName]['primary'];
552                 } // END - if
553
554                 // Return the column
555                 return $primaryKey;
556         }
557 }
558
559 // [EOF]
560 ?>