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