FQFN is now generated by new private method getFqfnFromDataSetInstance()
[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->generateFqfnFromDataSet($dataSetInstance, 'info');
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          * Generates an FQFN from given dataset instance and string
303          *
304          * @param       $dataSetInstance        An instance of a database set class
305          * @param       $rowName                        Name of the row
306          * @return      $fqfn                           The FQFN for this row
307          */
308         private function generateFqfnFromDataSet (StorableCriteria $dataSetInstance, $rowName) {
309                 // This is the FQFN
310                 $fqfn = $this->getSavePath() . $dataSetInstance->getTableName() . '/' . $rowName . '.' . $this->getFileExtension();
311
312                 // Return it
313                 return $fqfn;
314         }
315
316         /**
317          * Creates the table info file from given dataset instance
318          *
319          * @param       $dataSetInstance        An instance of a database set class
320          * @return      void
321          */
322         private function createTableInfoFile (StoreableCriteria $dataSetInstance) {
323                 // Create FQFN for creating the table information file
324                 $fqfn = $this->generateFqfnFromDataSet($dataSetInstance, 'info');
325
326                 // Get the data out from dataset in a local array
327                 $this->tableInfo[$dataSetInstance->getTableName()] = array(
328                         'primary'      => $dataSetInstance->getPrimaryKey(),
329                         'created'      => time(),
330                         'last_updated' => time()
331                 );
332
333                 // Write the data to the file
334                 $this->writeDataArrayToFqfn($fqfn, $this->tableInfo[$dataSetInstance->getTableName()]);
335         }
336
337         /**
338          * Updates the primary key information or creates the table info file if not found
339          *
340          * @param       $dataSetInstance        An instance of a database set class
341          * @return      void
342          */
343         private function updatePrimaryKey (StoreableCriteria $dataSetInstance) {
344                 // Get the information array from lower method
345                 $infoArray = $this->getContentsFromTableInfoFile($dataSetInstance);
346
347                 // Is the primary key there?
348                 if (!isset($this->tableInfo['primary'])) {
349                         // Then create the info file
350                         $this->createTableInfoFile($dataSetInstance);
351                 } elseif (($this->getConfigInstance()->getConfigEntry('db_update_primary_forced') == 'Y') && ($dataSetInstance->getPrimaryKey() != $this->tableInfo['primary'])) {
352                         // Set the array element
353                         $this->tableInfo[$dataSetInstance->getTableName()]['primary'] = $dataSetInstance->getPrimaryKey();
354
355                         // Update the entry
356                         $this->updateTableInfoFile($dataSetInstance);
357                 }
358         }
359
360         /**
361          * Makes sure that the database connection is alive
362          *
363          * @return      void
364          * @todo        Do some checks on the database directory and files here
365          */
366         public function connectToDatabase () {
367         }
368
369         /**
370          * Starts a SELECT query on the database by given return type, table name
371          * and search criteria
372          *
373          * @param       $resultType             Result type ('array', 'object' and 'indexed' are valid)
374          * @param       $tableName              Name of the database table
375          * @param       $criteria               Local search criteria class
376          * @return      $resultData             Result data of the query
377          * @throws      UnsupportedCriteriaException    If the criteria is unsupported
378          * @throws      SqlException                                    If an 'SQL error' occurs
379          */
380         public function querySelect ($resultType, $tableName, LocalSearchCriteria $criteriaInstance) {
381                 // The result is null by any errors
382                 $resultData = null;
383
384                 // Create full path name
385                 $pathName = $this->getSavePath() . $tableName . '/';
386
387                 // A 'select' query is not that easy on local files, so first try to
388                 // find the 'table' which is in fact a directory on the server
389                 try {
390                         // Get a directory pointer instance
391                         $directoryInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName);
392
393                         // Initialize the result data, this need to be rewritten e.g. if a local file cannot be read
394                         $resultData = array(
395                                 'status'        => LocalfileDatabase::RESULT_OKAY,
396                                 'rows'          => array()
397                         );
398
399                         // Initialize limit/skip
400                         $limitFound = 0;
401                         $skipFound = 0;
402                         $idx = 1;
403
404                         // Read the directory with some exceptions
405                         while (($dataFile = $directoryInstance->readDirectoryExcept(array('.', '..', '.htaccess', '.svn', "info." . $this->getFileExtension()))) && ($limitFound < $criteriaInstance->getLimit())) {
406                                 // Does the extension match?
407                                 if (substr($dataFile, -(strlen($this->getFileExtension()))) !== $this->getFileExtension()) {
408                                         // Skip this file!
409                                         continue;
410                                 } // END - if
411
412                                 // Read the file
413                                 $dataArray = $this->getDataArrayFromFile($pathName . $dataFile);
414
415                                 // Is this an array?
416                                 if (is_array($dataArray)) {
417                                         // Search in the criteria with FMFW (First Matches, First Wins)
418                                         foreach ($dataArray as $key => $value) {
419                                                 // Get criteria element
420                                                 $criteria = $criteriaInstance->getCriteriaElemnent($key);
421
422                                                 // Is the criteria met?
423                                                 if ((!is_null($criteria)) && ($criteria == $value))  {
424
425                                                         // Shall we skip this entry?
426                                                         if ($criteriaInstance->getSkip() > 0) {
427                                                                 // We shall skip some entries
428                                                                 if ($skipFound < $criteriaInstance->getSkip()) {
429                                                                         // Skip this entry
430                                                                         $skipFound++;
431                                                                         break;
432                                                                 } // END - if
433                                                         } // END - if
434
435                                                         // Set id number
436                                                         $dataArray[$this->getIndexKey()] = $idx;
437
438                                                         // Entry found!
439                                                         $resultData['rows'][] = $dataArray;
440
441                                                         // Count found entries up
442                                                         $limitFound++;
443                                                         break;
444                                                 } // END - if
445                                         } // END - foreach
446                                 } else {
447                                         // Throw an exception here
448                                         throw new SqlException(array($this, sprintf("File &#39;%s&#39; contains invalid data.", $dataFile), self::DB_CODE_DATA_FILE_CORRUPT), self::EXCEPTION_SQL_QUERY);
449                                 }
450
451                                 // Count entry up
452                                 $idx++;
453                         } // END - while
454
455                         // Close directory and throw the instance away
456                         $directoryInstance->closeDirectory();
457                         unset($directoryInstance);
458
459                         // Reset last error message and exception
460                         $this->resetLastError();
461                 } catch (PathIsNoDirectoryException $e) {
462                         // Path not found means "table not found" for real databases...
463                         $this->lastException = $e;
464                         $this->lastError = $e->getMessage();
465
466                         // So throw an SqlException here with faked error message
467                         throw new SqlException (array($this, sprintf("Table &#39;%s&#39; not found", $tableName), self::DB_CODE_TABLE_MISSING), self::EXCEPTION_SQL_QUERY);
468                 } catch (FrameworkException $e) {
469                         // Catch all exceptions and store them in last error
470                         $this->lastException = $e;
471                         $this->lastError = $e->getMessage();
472                 }
473
474                 // Return the gathered result
475                 return $resultData;
476         }
477
478         /**
479          * "Inserts" a data set instance into a local file database folder
480          *
481          * @param       $dataSetInstance        A storeable data set
482          * @return      void
483          * @throws      SqlException    If an SQL error occurs
484          */
485         public function queryInsertDataSet (StoreableCriteria $dataSetInstance) {
486                 // Create full path name
487                 $fqfn = $this->generateFqfnFromDataSet($dataSetInstance, md5($dataSetInstance->getUniqueValue()));
488
489                 // Try to save the request away
490                 try {
491                         // Write the data away
492                         $this->writeDataArrayToFqfn($fqfn, $dataSetInstance->getCriteriaArray());
493
494                         // Update the primary key
495                         $this->updatePrimaryKey($dataSetInstance);
496
497                         // Reset last error message and exception
498                         $this->resetLastError();
499                 } catch (FrameworkException $e) {
500                         // Catch all exceptions and store them in last error
501                         $this->lastException = $e;
502                         $this->lastError = $e->getMessage();
503
504                         // Throw an SQL exception
505                         throw new SqlException (array($this, sprintf("Cannot write data to table &#39;%s&#39;", $tableName), self::DB_CODE_TABLE_UNWRITEABLE), self::EXCEPTION_SQL_QUERY);
506                 }
507         }
508
509         /**
510          * "Updates" a data set instance with a database layer
511          *
512          * @param       $dataSetInstance        A storeable data set
513          * @return      void
514          * @throws      SqlException    If an SQL error occurs
515          */
516         public function queryUpdateDataSet (StoreableCriteria $dataSetInstance) {
517                 // Create full path name
518                 $pathName = $this->getSavePath() . $dataSetInstance->getTableName() . '/';
519
520                 // Try all the requests
521                 try {
522                         // Get a file pointer instance
523                         $directoryInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName);
524
525                         // Initialize limit/skip
526                         $limitFound = 0;
527                         $skipFound = 0;
528
529                         // Get the criteria array from the dataset
530                         $criteriaArray = $dataSetInstance->getCriteriaArray();
531
532                         // Get search criteria
533                         $searchInstance = $dataSetInstance->getSearchInstance();
534
535                         // Read the directory with some exceptions
536                         while (($dataFile = $directoryInstance->readDirectoryExcept(array('.', '..', '.htaccess', '.svn', "info." . $this->getFileExtension()))) && ($limitFound < $searchInstance->getLimit())) {
537                                 // Does the extension match?
538                                 if (substr($dataFile, -(strlen($this->getFileExtension()))) !== $this->getFileExtension()) {
539                                         // Skip this file!
540                                         continue;
541                                 }
542
543                                 // Open this file for reading
544                                 $dataArray = $this->getDataArrayFromFile($pathName . $dataFile);
545
546                                 // Is this an array?
547                                 if (is_array($dataArray)) {
548                                         // Search in the criteria with FMFW (First Matches, First Wins)
549                                         foreach ($dataArray as $key => $value) {
550                                                 // Get criteria element
551                                                 $criteria = $searchInstance->getCriteriaElemnent($key);
552
553                                                 // Is the criteria met?
554                                                 if ((!is_null($criteria)) && ($criteria == $value))  {
555
556                                                         // Shall we skip this entry?
557                                                         if ($searchInstance->getSkip() > 0) {
558                                                                 // We shall skip some entries
559                                                                 if ($skipFound < $searchInstance->getSkip()) {
560                                                                         // Skip this entry
561                                                                         $skipFound++;
562                                                                         break;
563                                                                 } // END - if
564                                                         } // END - if
565
566                                                         // Entry found, so update it
567                                                         foreach ($criteriaArray as $criteriaKey => $criteriaValue) {
568                                                                 $dataArray[$criteriaKey] = $criteriaValue;
569                                                         } // END - foreach
570
571                                                         // Write the data to a local file
572                                                         $this->writeDataArrayToFqfn($pathName . $dataFile, $dataArray);
573
574                                                         // Count it
575                                                         $limitFound++;
576                                                         break;
577                                                 } // END - if
578                                         } // END - foreach
579                                 } // END - if
580                         } // END - while
581
582                         // Close the file pointer
583                         $directoryInstance->closeDirectory();
584
585                         // Update the primary key
586                         $this->updatePrimaryKey($dataSetInstance);
587
588                         // Reset last error message and exception
589                         $this->resetLastError();
590                 } catch (FrameworkException $e) {
591                         // Catch all exceptions and store them in last error
592                         $this->lastException = $e;
593                         $this->lastError = $e->getMessage();
594
595                         // Throw an SQL exception
596                         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);
597                 }
598         }
599
600         /**
601          * Getter for primary key of specified table or if not found null will be
602          * returned. This must be database-specific.
603          *
604          * @param       $tableName              Name of the table we need the primary key from
605          * @return      $primaryKey             Primary key column of the given table
606          */
607         public function getPrimaryKeyOfTable ($tableName) {
608                 // Default key is null
609                 $primaryKey = null;
610
611                 // Does the table information exist?
612                 if (isset($this->tableInfo[$tableName])) {
613                         // Then return the primary key
614                         $primaryKey = $this->tableInfo[$tableName]['primary'];
615                 } // END - if
616
617                 // Return the column
618                 return $primaryKey;
619         }
620 }
621
622 // [EOF]
623 ?>