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