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