Fixed a typo
[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          * Whether 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       $tableName              Name of the database table
341          * @param       $criteria               Local search criteria class
342          * @return      $resultData             Result data of the query
343          * @throws      UnsupportedCriteriaException    If the criteria is unsupported
344          * @throws      SqlException                                    If an 'SQL error' occurs
345          */
346         public function querySelect ($tableName, LocalSearchCriteria $criteriaInstance) {
347                 // The result is null by any errors
348                 $resultData = NULL;
349
350                 // Create full path name
351                 $pathName = $this->getConfigInstance()->getConfigEntry('local_db_path') . $tableName . '/';
352
353                 // A 'select' query is not that easy on local files, so first try to
354                 // find the 'table' which is in fact a directory on the server
355                 try {
356                         // Get a directory pointer instance
357                         $directoryInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName);
358
359                         // Initialize the result data, this need to be rewritten e.g. if a local file cannot be read
360                         $resultData = array(
361                                 BaseDatabaseFrontend::RESULT_INDEX_STATUS => LocalfileDatabase::RESULT_OKAY,
362                                 BaseDatabaseFrontend::RESULT_INDEX_ROWS   => array()
363                         );
364
365                         // Initialize limit/skip
366                         $limitFound = 0;
367                         $skipFound = 0;
368                         $idx = 1;
369
370                         // Read the directory with some exceptions
371                         while (($dataFile = $directoryInstance->readDirectoryExcept(array('.', '..', '.htaccess', '.svn', 'info.' . $this->getFileExtension()))) && (($limitFound < $criteriaInstance->getLimit()) || ($criteriaInstance->getLimit() == 0))) {
372                                 // Does the extension match?
373                                 if (substr($dataFile, -(strlen($this->getFileExtension()))) !== $this->getFileExtension()) {
374                                         // Skip this file!
375                                         continue;
376                                 } // END - if
377
378                                 // Read the file
379                                 $dataArray = $this->getDataArrayFromFile($pathName . $dataFile);
380
381                                 // Is this an array?
382                                 if (is_array($dataArray)) {
383                                         // Search in the criteria with FMFW (First Matches, First Wins)
384                                         foreach ($dataArray as $key => $value) {
385                                                 // Get criteria element
386                                                 $criteria = $criteriaInstance->getCriteriaElemnent($key);
387
388                                                 // Is the criteria met?
389                                                 //* NOISY-DEBUG: */ $this->debugOutput('DATABASE: criteria[' . gettype($criteria) . ']=' . $criteria . ',()=' . strlen($criteria) . ',value=' . $value . ',()=' . strlen($value));
390                                                 if ((!is_null($criteria)) && ($criteria == $value))  {
391                                                         // Shall we skip this entry?
392                                                         if ($criteriaInstance->getSkip() > 0) {
393                                                                 // We shall skip some entries
394                                                                 if ($skipFound < $criteriaInstance->getSkip()) {
395                                                                         // Skip this entry
396                                                                         $skipFound++;
397                                                                         break;
398                                                                 } // END - if
399                                                         } // END - if
400
401                                                         // Set id number
402                                                         $dataArray[$this->getIndexKey()] = $idx;
403
404                                                         // Entry found!
405                                                         //* NOISY-DEBUG: */ $this->debugOutput('DATABASE: indexKey=' . $this->getIndexKey() . ',idx=' . $idx . ',dataArray=' . print_r($dataArray, true));
406                                                         $resultData[BaseDatabaseFrontend::RESULT_INDEX_ROWS][] = $dataArray;
407
408                                                         // Count found entries up
409                                                         $limitFound++;
410                                                         break;
411                                                 } // END - if
412                                         } // END - foreach
413                                 } else {
414                                         // Throw an exception here
415                                         throw new SqlException(array($this, sprintf("File &#39;%s&#39; contains invalid data.", $dataFile), self::DB_CODE_DATA_FILE_CORRUPT), self::EXCEPTION_SQL_QUERY);
416                                 }
417
418                                 // Count entry up
419                                 $idx++;
420                         } // END - while
421
422                         // Close directory and throw the instance away
423                         $directoryInstance->closeDirectory();
424                         unset($directoryInstance);
425
426                         // Reset last error message and exception
427                         $this->resetLastError();
428                 } catch (PathIsNoDirectoryException $e) {
429                         // Path not found means "table not found" for real databases...
430                         $this->lastException = $e;
431                         $this->lastError     = $e->getMessage();
432
433                         // So throw an SqlException here with faked error message
434                         throw new SqlException (array($this, sprintf("Table &#39;%s&#39; not found", $tableName), self::DB_CODE_TABLE_MISSING), self::EXCEPTION_SQL_QUERY);
435                 } catch (FrameworkException $e) {
436                         // Catch all exceptions and store them in last error
437                         $this->lastException = $e;
438                         $this->lastError     = $e->getMessage();
439                 }
440
441                 // Return the gathered result
442                 return $resultData;
443         }
444
445         /**
446          * "Inserts" a data set instance into a local file database folder
447          *
448          * @param       $dataSetInstance        A storeable data set
449          * @return      void
450          * @throws      SqlException    If an SQL error occurs
451          */
452         public function queryInsertDataSet (StoreableCriteria $dataSetInstance) {
453                 // Create full path name
454                 $fqfn = $this->generateFqfnFromDataSet($dataSetInstance, md5($dataSetInstance->getUniqueValue()));
455
456                 // Try to save the request away
457                 try {
458                         // Write the data away
459                         $this->writeDataArrayToFqfn($fqfn, $dataSetInstance->getCriteriaArray());
460
461                         // Update the primary key
462                         $this->updatePrimaryKey($dataSetInstance);
463
464                         // Reset last error message and exception
465                         $this->resetLastError();
466                 } catch (FrameworkException $e) {
467                         // Catch all exceptions and store them in last error
468                         $this->lastException = $e;
469                         $this->lastError     = $e->getMessage();
470
471                         // Throw an SQL exception
472                         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);
473                 }
474         }
475
476         /**
477          * "Updates" a data set instance with a database layer
478          *
479          * @param       $dataSetInstance        A storeable data set
480          * @return      void
481          * @throws      SqlException    If an SQL error occurs
482          */
483         public function queryUpdateDataSet (StoreableCriteria $dataSetInstance) {
484                 // Create full path name
485                 $pathName = $this->getConfigInstance()->getConfigEntry('local_db_path') . $dataSetInstance->getTableName() . '/';
486
487                 // Try all the requests
488                 try {
489                         // Get a file pointer instance
490                         $directoryInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName);
491
492                         // Initialize limit/skip
493                         $limitFound = 0;
494                         $skipFound = 0;
495
496                         // Get the criteria array from the dataset
497                         $criteriaArray = $dataSetInstance->getCriteriaArray();
498
499                         // Get search criteria
500                         $searchInstance = $dataSetInstance->getSearchInstance();
501
502                         // Read the directory with some exceptions
503                         while (($dataFile = $directoryInstance->readDirectoryExcept(array('.', '..', '.htaccess', '.svn', "info." . $this->getFileExtension()))) && ($limitFound < $searchInstance->getLimit())) {
504                                 // Does the extension match?
505                                 if (substr($dataFile, -(strlen($this->getFileExtension()))) !== $this->getFileExtension()) {
506                                         // Skip this file!
507                                         continue;
508                                 }
509
510                                 // Open this file for reading
511                                 $dataArray = $this->getDataArrayFromFile($pathName . $dataFile);
512
513                                 // Is this an array?
514                                 if (is_array($dataArray)) {
515                                         // Search in the criteria with FMFW (First Matches, First Wins)
516                                         foreach ($dataArray as $key => $value) {
517                                                 // Get criteria element
518                                                 $criteria = $searchInstance->getCriteriaElemnent($key);
519
520                                                 // Is the criteria met?
521                                                 if ((!is_null($criteria)) && ($criteria == $value))  {
522
523                                                         // Shall we skip this entry?
524                                                         if ($searchInstance->getSkip() > 0) {
525                                                                 // We shall skip some entries
526                                                                 if ($skipFound < $searchInstance->getSkip()) {
527                                                                         // Skip this entry
528                                                                         $skipFound++;
529                                                                         break;
530                                                                 } // END - if
531                                                         } // END - if
532
533                                                         // Entry found, so update it
534                                                         foreach ($criteriaArray as $criteriaKey => $criteriaValue) {
535                                                                 $dataArray[$criteriaKey] = $criteriaValue;
536                                                         } // END - foreach
537
538                                                         // Write the data to a local file
539                                                         $this->writeDataArrayToFqfn($pathName . $dataFile, $dataArray);
540
541                                                         // Count it
542                                                         $limitFound++;
543                                                         break;
544                                                 } // END - if
545                                         } // END - foreach
546                                 } // END - if
547                         } // END - while
548
549                         // Close the file pointer
550                         $directoryInstance->closeDirectory();
551
552                         // Update the primary key
553                         $this->updatePrimaryKey($dataSetInstance);
554
555                         // Reset last error message and exception
556                         $this->resetLastError();
557                 } catch (FrameworkException $e) {
558                         // Catch all exceptions and store them in last error
559                         $this->lastException = $e;
560                         $this->lastError = $e->getMessage();
561
562                         // Throw an SQL exception
563                         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);
564                 }
565         }
566
567         /**
568          * Getter for primary key of specified table or if not found null will be
569          * returned. This must be database-specific.
570          *
571          * @param       $tableName              Name of the table we need the primary key from
572          * @return      $primaryKey             Primary key column of the given table
573          */
574         public function getPrimaryKeyOfTable ($tableName) {
575                 // Default key is null
576                 $primaryKey = NULL;
577
578                 // Does the table information exist?
579                 if (isset($this->tableInfo[$tableName])) {
580                         // Then return the primary key
581                         $primaryKey = $this->tableInfo[$tableName]['primary'];
582                 } // END - if
583
584                 // Return the column
585                 return $primaryKey;
586         }
587 }
588
589 // [EOF]
590 ?>