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