Constants PATH and _DB_TYPE replaced
[shipsimu.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, this is free software
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
28         // Constants for MySQL backward-compatiblity (PLEASE FIX THEM!)
29         const DB_CODE_TABLE_MISSING     = 0x100;
30         const DB_CODE_TABLE_UNWRITEABLE = 0x101;
31         const DB_CODE_DATA_FILE_CORRUPT = 0x102;
32
33         /**
34          * Save path for "file database"
35          */
36         private $savePath = "";
37
38         /**
39          * The file's extension
40          */
41         private $fileExtension = "serialized";
42
43         /**
44          * The last read file's name
45          */
46         private $lastFile = "";
47
48         /**
49          * The last read file's content including header information
50          */
51         private $lastContents = array();
52
53         /**
54          * Wether the "connection is already up
55          */
56         private $alreadyConnected = false;
57
58         /**
59          * Last error message
60          */
61         private $lastError = "";
62
63         /**
64          * Last exception
65          */
66         private $lastException = null;
67
68         /**
69          * Table information array
70          */
71         private $tableInfo = array();
72
73         /**
74          * The protected constructor. Do never instance from outside! You need to
75          * set a local file path. The class will then validate it.
76          *
77          * @return      void
78          */
79         protected function __construct() {
80                 // Call parent constructor
81                 parent::__construct(__CLASS__);
82
83                 // Clean up a little
84                 $this->removeNumberFormaters();
85                 $this->removeSystemArray();
86         }
87
88         /**
89          * Create an object of LocalFileDatabase and set the save path for local files.
90          * This method also validates the given file path.
91          *
92          * @param               $savePath                                       The local file path string
93          * @param               $ioInstance                             The input/output handler. This
94          *                                                                      should be FileIoHandler
95          * @return      $dbInstance                             An instance of LocalFileDatabase
96          */
97         public final static function createLocalFileDatabase ($savePath, FileIoHandler $ioInstance) {
98                 // Get an instance
99                 $dbInstance = new LocalFileDatabase();
100
101                 // Set save path and IO instance
102                 $dbInstance->setSavePath($savePath);
103                 $dbInstance->setFileIoInstance($ioInstance);
104
105                 // "Connect" to the database
106                 $dbInstance->connectToDatabase();
107
108                 // Return database instance
109                 return $dbInstance;
110         }
111
112         /**
113          * Setter for save path
114          *
115          * @param               $savePath               The local save path where we shall put our serialized classes
116          * @return      void
117          */
118         public final function setSavePath ($savePath) {
119                 // Secure string
120                 $savePath = (string) $savePath;
121
122                 // Set save path
123                 $this->savePath = $savePath;
124         }
125
126         /**
127          * Getter for save path
128          *
129          * @return      $savePath               The local save path where we shall put our serialized classes
130          */
131         public final function getSavePath () {
132                 return $this->savePath;
133         }
134
135         /**
136          * Getter for last error message
137          *
138          * @return      $lastError      Last error message
139          */
140         public final function getLastError () {
141                 return $this->lastError;
142         }
143
144         /**
145          * Getter for last exception
146          *
147          * @return      $lastException  Last thrown exception
148          */
149         public final function getLastException () {
150                 return $this->lastException;
151         }
152
153         /**
154          * Setter for the last read file
155          *
156          * @param               $fqfn   The FQFN of the last read file
157          * @return      void
158          */
159         private final function setLastFile ($fqfn) {
160                 // Cast string
161                 $fqfn = (string) $fqfn;
162                 $this->lastFile = $fqfn;
163         }
164
165         /**
166          * Reset the last error and exception instance. This should be done after
167          * a successfull "query"
168          *
169          * @return      void
170          */
171         private final function resetLastError () {
172                 $this->lastError = "";
173                 $this->lastException = null;
174         }
175
176         /**
177          * Getter for last read file
178          *
179          * @return      $lastFile               The last read file's name with full path
180          */
181         public final function getLastFile () {
182                 return $this->lastFile;
183         }
184
185         /**
186          * Setter for contents of the last read file
187          *
188          * @param               $contents               An array with header and data elements
189          * @return      void
190          */
191         private final function setLastFileContents ($contents) {
192                 // Cast array
193                 $contents = (array) $contents;
194                 $this->lastContents = $contents;
195         }
196
197         /**
198          * Getter for last read file's content as an array
199          *
200          * @return      $lastContent    The array with elements 'header' and 'data'.
201          */
202         public final function getLastContents () {
203                 return $this->lastContents;
204         }
205
206         /**
207          * Getter for file extension
208          *
209          * @return      $fileExtension  The array with elements 'header' and 'data'.
210          */
211         public final function getFileExtension () {
212                 return $this->fileExtension;
213         }
214
215         /**
216          * Reads a local data file  and returns it's contents in an array
217          *
218          * @param       $fqfn   The FQFN for the requested file
219          * @return      $dataArray
220          */
221         private function getDataArrayFromFile ($fqfn) {
222                 // Get a file pointer
223                 $fileInstance = FrameworkFileInputPointer::createFrameworkFileInputPointer($fqfn);
224
225                 // Get the raw data and BASE64-decode it
226                 $compressedData = base64_decode($fileInstance->readLinesFromFile());
227
228                 // Close the file and throw the instance away
229                 $fileInstance->closeFile();
230                 unset($fileInstance);
231
232                 // Decompress it
233                 $serializedData = $this->getCompressorChannel()->getCompressor()->decompressStream($compressedData);
234
235                 // Unserialize it
236                 $dataArray = unserialize($serializedData);
237
238                 // Finally return it
239                 return $dataArray;
240         }
241
242         /**
243          * Writes data array to local file
244          *
245          * @param       $fqfn           The FQFN of the local file
246          * @param       $dataArray      An array with all the data we shall write
247          * @return      void
248          */
249         private function writeDataArrayToFqfn ($fqfn, array $dataArray) {
250                 // Get a file pointer instance
251                 $fileInstance = FrameworkFileOutputPointer::createFrameworkFileOutputPointer($fqfn, 'w');
252
253                 // Serialize and compress it
254                 $compressedData = $this->getCompressorChannel()->getCompressor()->compressStream(serialize($dataArray));
255
256                 // Write this data BASE64 encoded to the file
257                 $fileInstance->writeToFile(base64_encode($compressedData));
258
259                 // Close the file pointer
260                 $fileInstance->closeFile();
261         }
262
263         /**
264          * Getter for table information file contents or an empty if the info file was not created
265          *
266          * @param       $dataSetInstance        An instance of a database set class
267          * @return      $infoArray                      An array with all table informations
268          */
269         private function getContentsFromTableInfoFile (StoreableCriteria $dataSetInstance) {
270                 // Default content is no data
271                 $infoArray = array();
272
273                 // Create FQFN for getting the table information file
274                 $fqfn = $this->getSavePath() . $dataSetInstance->getTableName() . '/info.' . $this->getFileExtension();
275
276                 // Get the file contents
277                 try {
278                         $infoArray = $this->getDataArrayFromFile($fqfn);
279                 } catch (FileNotFoundException $e) {
280                         // Not found, so ignore it here
281                 }
282
283                 // ... and return it
284                 return $infoArray;
285         }
286
287         /**
288          * Creates the table info file from given dataset instance
289          *
290          * @param       $dataSetInstance        An instance of a database set class
291          * @return      void
292          */
293         private function createTableInfoFile (StoreableCriteria $dataSetInstance) {
294                 // Create FQFN for creating the table information file
295                 $fqfn = $this->getSavePath() . $dataSetInstance->getTableName() . '/info.' . $this->getFileExtension();
296
297                 // Get the data out from dataset in a local array
298                 $this->tableInfo[$dataSetInstance->getTableName()] = array(
299                         'primary'      => $dataSetInstance->getPrimaryKey(),
300                         'created'      => time(),
301                         'last_updated' => time()
302                 );
303
304                 // Write the data to the file
305                 $this->writeDataArrayToFqfn($fqfn, $this->tableInfo[$dataSetInstance->getTableName()]);
306         }
307
308         /**
309          * Updates the primary key information or creates the table info file if not found
310          *
311          * @param       $dataSetInstance        An instance of a database set class
312          * @return      void
313          */
314         private function updatePrimaryKey (StoreableCriteria $dataSetInstance) {
315                 // Get the information array from lower method
316                 $infoArray = $this->getContentsFromTableInfoFile($dataSetInstance);
317
318                 // Is the primary key there?
319                 if (!isset($this->tableInfo['primary'])) {
320                         // Then create the info file
321                         $this->createTableInfoFile($dataSetInstance);
322                 } elseif (($this->getConfigInstance()->readConfig('db_update_primary_forced') === "Y") && ($dataSetInstance->getPrimaryKey() != $this->tableInfo['primary'])) {
323                         // Set the array element
324                         $this->tableInfo[$dataSetInstance->getTableName()]['primary'] = $dataSetInstance->getPrimaryKey();
325
326                         // Update the entry
327                         $this->updateTableInfoFile($dataSetInstance);
328                 }
329         }
330
331         /**
332          * Makes sure that the database connection is alive
333          *
334          * @return      void
335          * @todo        Do some checks on the database directory and files here
336          */
337         public function connectToDatabase () {
338         }
339
340         /**
341          * Starts a SELECT query on the database by given return type, table name
342          * and search criteria
343          *
344          * @param       $resultType             Result type ("array", "object" and "indexed" are valid)
345          * @param       $tableName              Name of the database table
346          * @param       $criteria               Local search criteria class
347          * @return      $resultData             Result data of the query
348          * @throws      UnsupportedCriteriaException    If the criteria is unsupported
349          * @throws      SqlException                                    If an "SQL error" occurs
350          */
351         public function querySelect ($resultType, $tableName, LocalSearchCriteria $criteriaInstance) {
352                 // The result is null by any errors
353                 $resultData = null;
354
355                 // Create full path name
356                 $pathName = $this->getSavePath() . $tableName . '/';
357
358                 // A "select" query is not that easy on local files, so first try to
359                 // find the "table" which is in fact a directory on the server
360                 try {
361                         // Get a directory pointer instance
362                         $directoryInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName);
363
364                         // Initialize the result data, this need to be rewritten e.g. if a local file cannot be read
365                         $resultData = array(
366                                 'status'        => "ok",
367                                 'rows'          => array()
368                         );
369
370                         // Initialize limit/skip
371                         $limitFound = 0;
372                         $skipFound = 0;
373
374                         // Read the directory with some exceptions
375                         while (($dataFile = $directoryInstance->readDirectoryExcept(array(".", "..", ".htaccess", ".svn", "info." . $this->getFileExtension()))) && ($limitFound < $criteriaInstance->getLimit())) {
376                                 // Does the extension match?
377                                 if (substr($dataFile, -(strlen($this->getFileExtension()))) !== $this->getFileExtension()) {
378                                         // Skip this file!
379                                         continue;
380                                 }
381
382                                 // Read the file
383                                 $dataArray = $this->getDataArrayFromFile($pathName . $dataFile);
384
385                                 // Is this an array?
386                                 if (is_array($dataArray)) {
387                                         // Search in the criteria with FMFW (First Matches, First Wins)
388                                         foreach ($dataArray as $key=>$value) {
389                                                 // Get criteria element
390                                                 $criteria = $criteriaInstance->getCriteriaElemnent($key);
391
392                                                 // Is the criteria met?
393                                                 if ((!is_null($criteria)) && ($criteria == $value))  {
394
395                                                         // Shall we skip this entry?
396                                                         if ($criteriaInstance->getSkip() > 0) {
397                                                                 // We shall skip some entries
398                                                                 if ($skipFound < $criteriaInstance->getSkip()) {
399                                                                         // Skip this entry
400                                                                         $skipFound++;
401                                                                         break;
402                                                                 } // END - if
403                                                         } // END - if
404
405                                                         // Entry found!
406                                                         $resultData['rows'][] = $dataArray;
407                                                         $limitFound++;
408                                                         break;
409                                                 } // END - if
410                                         } // END - foreach
411                                 } else {
412                                         // Throw an exception here
413                                         throw new SqlException(array($this, sprintf("File &#39;%s&#39; contains invalid data.", $dataFile), self::DB_CODE_DATA_FILE_CORRUPT), self::EXCEPTION_SQL_QUERY);
414                                 }
415                         } // END - while
416
417                         // Close directory and throw the instance away
418                         $directoryInstance->closeDirectory();
419                         unset($directoryInstance);
420
421                         // Reset last error message and exception
422                         $this->resetLastError();
423                 } catch (PathIsNoDirectoryException $e) {
424                         // Path not found means "table not found" for real databases...
425                         $this->lastException = $e;
426                         $this->lastError = $e->getMessage();
427
428                         // So throw an SqlException here with faked error message
429                         throw new SqlException (array($this, sprintf("Table &#39;%s&#39; not found", $tableName), self::DB_CODE_TABLE_MISSING), self::EXCEPTION_SQL_QUERY);
430                 } catch (FrameworkException $e) {
431                         // Catch all exceptions and store them in last error
432                         $this->lastException = $e;
433                         $this->lastError = $e->getMessage();
434                 }
435
436                 // Return the gathered result
437                 return $resultData;
438         }
439
440         /**
441          * "Inserts" a data set instance into a local file database folder
442          *
443          * @param       $dataSetInstance        A storeable data set
444          * @return      void
445          * @throws      SqlException    If an SQL error occurs
446          */
447         public function queryInsertDataSet (StoreableCriteria $dataSetInstance) {
448                 // Create full path name
449                 $fqfn = sprintf("%s%s/%s.%s",
450                         $this->getSavePath(),
451                         $dataSetInstance->getTableName(),
452                         md5($dataSetInstance->getUniqueValue()),
453                         $this->getFileExtension()
454                 );
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;", $tableName), 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->getSavePath() . $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;", $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 ?>