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