Code syncronized with shipsimu code base
[mailer.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          * Analyses if a unique ID has already been used or not by search in the
155          * local database folder.
156          *
157          * @param       $uniqueID               A unique ID number which shall be checked
158          *                                                      before it will be used
159          * @param       $inConstructor  If we got called in a de/con-structor or
160          *                                                      from somewhere else
161          * @return      $isUnused               true    = The unique ID was not found in the database,
162          *                                                      false = It is already in use by an other object
163          * @throws      NoArrayCreatedException         If explode() fails to create an array
164          * @throws      InvalidArrayCountException      If the array contains less or
165          *                                                                      more than two elements
166          * @deprecated
167          */
168         public function isUniqueIdUsed ($uniqueID, $inConstructor = false) {
169                 // Currently not used... ;-)
170                 $isUsed = false;
171
172                 // Split the unique ID up in path and file name
173                 $pathFile = explode("@", $uniqueID);
174
175                 // Are there two elements? Index 0 is the path, 1 the file name + global extension
176                 if (!is_array($pathFile)) {
177                         // No array found
178                         if ($inConstructor) {
179                                 return false;
180                         } else {
181                                 throw new NoArrayCreatedException(array($this, 'pathFile'), self::EXCEPTION_ARRAY_EXPECTED);
182                         }
183                 } elseif (count($pathFile) != 2) {
184                         // Invalid ID returned!
185                         if ($inConstructor) {
186                                 return false;
187                         } else {
188                                 throw new InvalidArrayCountException(array($this, 'pathFile', count($pathFile), 2), self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
189                         }
190                 }
191
192                 // Create full path name
193                 $pathName = $this->getSavePath() . $pathFile[0];
194
195                 // Check if the file is there with a file handler
196                 if ($inConstructor) {
197                         // No exceptions in constructors and destructors!
198                         $dirInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName, true);
199
200                         // Has an object being created?
201                         if (!is_object($dirInstance)) return false;
202                 } else {
203                         // Outside a constructor
204                         try {
205                                 $dirInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName);
206                         } catch (PathIsNoDirectoryException $e) {
207                                 // Okay, path not found
208                                 return false;
209                         }
210                 }
211
212                 // Initialize the search loop
213                 $isValid = false;
214                 while ($dataFile = $dirInstance->readDirectoryExcept(array(".", "..", ".htaccess", ".svn", "info." . $this->getFileExtension()))) {
215                         // Generate FQFN for testing
216                         $fqfn = sprintf("%s/%s", $pathName, $dataFile);
217                         $this->setLastFile($fqfn);
218
219                         // Get instance for file handler
220                         $inputHandler = $this->getFileIoInstance();
221
222                         // Try to read from it. This makes it sure that the file is
223                         // readable and a valid database file
224                         $this->setLastFileContents($inputHandler->loadFileContents($fqfn));
225
226                         // Extract filename (= unique ID) from it
227                         $ID = substr(basename($fqfn), 0, -(strlen($this->getFileExtension()) + 1));
228
229                         // Is this the required unique ID?
230                         if ($ID == $pathFile[1]) {
231                                 // Okay, already in use!
232                                 $isUsed = true;
233                         }
234                 }
235
236                 // Close the directory handler
237                 $dirInstance->closeDirectory();
238
239                 // Now the same for the file...
240                 return $isUsed;
241         }
242
243         /**
244          * Setter for the last read file
245          *
246          * @param               $fqfn   The FQFN of the last read file
247          * @return      void
248          */
249         private final function setLastFile ($fqfn) {
250                 // Cast string
251                 $fqfn = (string) $fqfn;
252                 $this->lastFile = $fqfn;
253         }
254
255         /**
256          * Reset the last error and exception instance. This should be done after
257          * a successfull "query"
258          *
259          * @return      void
260          */
261         private final function resetLastError () {
262                 $this->lastError = "";
263                 $this->lastException = null;
264         }
265
266         /**
267          * Getter for last read file
268          *
269          * @return      $lastFile               The last read file's name with full path
270          */
271         public final function getLastFile () {
272                 return $this->lastFile;
273         }
274
275         /**
276          * Setter for contents of the last read file
277          *
278          * @param               $contents               An array with header and data elements
279          * @return      void
280          */
281         private final function setLastFileContents ($contents) {
282                 // Cast array
283                 $contents = (array) $contents;
284                 $this->lastContents = $contents;
285         }
286
287         /**
288          * Getter for last read file's content as an array
289          *
290          * @return      $lastContent    The array with elements 'header' and 'data'.
291          */
292         public final function getLastContents () {
293                 return $this->lastContents;
294         }
295
296         /**
297          * Getter for file extension
298          *
299          * @return      $fileExtension  The array with elements 'header' and 'data'.
300          */
301         public final function getFileExtension () {
302                 return $this->fileExtension;
303         }
304
305         /**
306          * Reads a local data file  and returns it's contents in an array
307          *
308          * @param       $fqfn   The FQFN for the requested file
309          * @return      $dataArray
310          */
311         private function getDataArrayFromFile ($fqfn) {
312                 // Get a file pointer
313                 $fileInstance = FrameworkFileInputPointer::createFrameworkFileInputPointer($fqfn);
314
315                 // Get the raw data and BASE64-decode it
316                 $compressedData = base64_decode($fileInstance->readLinesFromFile());
317
318                 // Close the file and throw the instance away
319                 $fileInstance->closeFile();
320                 unset($fileInstance);
321
322                 // Decompress it
323                 $serializedData = $this->getCompressorChannel()->getCompressor()->decompressStream($compressedData);
324
325                 // Unserialize it
326                 $dataArray = unserialize($serializedData);
327
328                 // Finally return it
329                 return $dataArray;
330         }
331
332         /**
333          * Writes data array to local file
334          *
335          * @param       $fqfn           The FQFN of the local file
336          * @param       $dataArray      An array with all the data we shall write
337          * @return      void
338          */
339         private function writeDataArrayToFqfn ($fqfn, array $dataArray) {
340                 // Get a file pointer instance
341                 $fileInstance = FrameworkFileOutputPointer::createFrameworkFileOutputPointer($fqfn, 'w');
342
343                 // Serialize and compress it
344                 $compressedData = $this->getCompressorChannel()->getCompressor()->compressStream(serialize($dataArray));
345
346                 // Write this data BASE64 encoded to the file
347                 $fileInstance->writeToFile(base64_encode($compressedData));
348
349                 // Close the file pointer
350                 $fileInstance->closeFile();
351         }
352
353         /**
354          * Getter for table information file contents or an empty if the info file was not created
355          *
356          * @param       $dataSetInstance        An instance of a database set class
357          * @return      $infoArray                      An array with all table informations
358          */
359         private function getContentsFromTableInfoFile (StoreableCriteria $dataSetInstance) {
360                 // Default content is no data
361                 $infoArray = array();
362
363                 // Create FQFN for getting the table information file
364                 $fqfn = $this->getSavePath() . $dataSetInstance->getTableName() . '/info.' . $this->getFileExtension();
365
366                 // Get the file contents
367                 try {
368                         $infoArray = $this->getDataArrayFromFile($fqfn);
369                 } catch (FileNotFoundException $e) {
370                         // Not found, so ignore it here
371                 }
372
373                 // ... and return it
374                 return $infoArray;
375         }
376
377         /**
378          * Creates the table info file from given dataset instance
379          *
380          * @param       $dataSetInstance        An instance of a database set class
381          * @return      void
382          */
383         private function createTableInfoFile (StoreableCriteria $dataSetInstance) {
384                 // Create FQFN for creating the table information file
385                 $fqfn = $this->getSavePath() . $dataSetInstance->getTableName() . '/info.' . $this->getFileExtension();
386
387                 // Get the data out from dataset in a local array
388                 $this->tableInfo[$dataSetInstance->getTableName()] = array(
389                         'primary'      => $dataSetInstance->getPrimaryKey(),
390                         'created'      => time(),
391                         'last_updated' => time()
392                 );
393
394                 // Write the data to the file
395                 $this->writeDataArrayToFqfn($fqfn, $this->tableInfo[$dataSetInstance->getTableName()]);
396         }
397
398         /**
399          * Updates the primary key information or creates the table info file if not found
400          *
401          * @param       $dataSetInstance        An instance of a database set class
402          * @return      void
403          */
404         private function updatePrimaryKey (StoreableCriteria $dataSetInstance) {
405                 // Get the information array from lower method
406                 $infoArray = $this->getContentsFromTableInfoFile($dataSetInstance);
407
408                 // Is the primary key there?
409                 if (!isset($this->tableInfo['primary'])) {
410                         // Then create the info file
411                         $this->createTableInfoFile($dataSetInstance);
412                 } elseif (($this->getConfigInstance()->readConfig('db_update_primary_forced') === "Y") && ($dataSetInstance->getPrimaryKey() != $this->tableInfo['primary'])) {
413                         // Set the array element
414                         $this->tableInfo[$dataSetInstance->getTableName()]['primary'] = $dataSetInstance->getPrimaryKey();
415
416                         // Update the entry
417                         $this->updateTableInfoFile($dataSetInstance);
418                 }
419         }
420
421         /**
422          * Makes sure that the database connection is alive
423          *
424          * @return      void
425          * @todo        Do some checks on the database directory and files here
426          */
427         public function connectToDatabase () {
428         }
429
430         /**
431          * Starts a SELECT query on the database by given return type, table name
432          * and search criteria
433          *
434          * @param       $resultType             Result type ("array", "object" and "indexed" are valid)
435          * @param       $tableName              Name of the database table
436          * @param       $criteria               Local search criteria class
437          * @return      $resultData             Result data of the query
438          * @throws      UnsupportedCriteriaException    If the criteria is unsupported
439          * @throws      SqlException                                    If an "SQL error" occurs
440          */
441         public function querySelect ($resultType, $tableName, LocalSearchCriteria $criteriaInstance) {
442                 // The result is null by any errors
443                 $resultData = null;
444
445                 // Create full path name
446                 $pathName = $this->getSavePath() . $tableName . '/';
447
448                 // A "select" query is not that easy on local files, so first try to
449                 // find the "table" which is in fact a directory on the server
450                 try {
451                         // Get a directory pointer instance
452                         $directoryInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName);
453
454                         // Initialize the result data, this need to be rewritten e.g. if a local file cannot be read
455                         $resultData = array(
456                                 'status'        => "ok",
457                                 'rows'          => array()
458                         );
459
460                         // Initialize limit/skip
461                         $limitFound = 0;
462                         $skipFound = 0;
463
464                         // Read the directory with some exceptions
465                         while (($dataFile = $directoryInstance->readDirectoryExcept(array(".", "..", ".htaccess", ".svn", "info." . $this->getFileExtension()))) && ($limitFound < $criteriaInstance->getLimit())) {
466                                 // Does the extension match?
467                                 if (substr($dataFile, -(strlen($this->getFileExtension()))) !== $this->getFileExtension()) {
468                                         // Skip this file!
469                                         continue;
470                                 }
471
472                                 // Read the file
473                                 $dataArray = $this->getDataArrayFromFile($pathName . $dataFile);
474
475                                 // Is this an array?
476                                 if (is_array($dataArray)) {
477                                         // Search in the criteria with FMFW (First Matches, First Wins)
478                                         foreach ($dataArray as $key=>$value) {
479                                                 // Get criteria element
480                                                 $criteria = $criteriaInstance->getCriteriaElemnent($key);
481
482                                                 // Is the criteria met?
483                                                 if ((!is_null($criteria)) && ($criteria == $value))  {
484
485                                                         // Shall we skip this entry?
486                                                         if ($criteriaInstance->getSkip() > 0) {
487                                                                 // We shall skip some entries
488                                                                 if ($skipFound < $criteriaInstance->getSkip()) {
489                                                                         // Skip this entry
490                                                                         $skipFound++;
491                                                                         break;
492                                                                 } // END - if
493                                                         } // END - if
494
495                                                         // Entry found!
496                                                         $resultData['rows'][] = $dataArray;
497                                                         $limitFound++;
498                                                         break;
499                                                 } // END - if
500                                         } // END - foreach
501                                 } else {
502                                         // Throw an exception here
503                                         throw new SqlException(array($this, sprintf("File &#39;%s&#39; contains invalid data.", $dataFile), self::DB_CODE_DATA_FILE_CORRUPT), self::EXCEPTION_SQL_QUERY);
504                                 }
505                         } // END - while
506
507                         // Close directory and throw the instance away
508                         $directoryInstance->closeDirectory();
509                         unset($directoryInstance);
510
511                         // Reset last error message and exception
512                         $this->resetLastError();
513                 } catch (PathIsNoDirectoryException $e) {
514                         // Path not found means "table not found" for real databases...
515                         $this->lastException = $e;
516                         $this->lastError = $e->getMessage();
517
518                         // So throw an SqlException here with faked error message
519                         throw new SqlException (array($this, sprintf("Table &#39;%s&#39; not found", $tableName), self::DB_CODE_TABLE_MISSING), self::EXCEPTION_SQL_QUERY);
520                 } catch (FrameworkException $e) {
521                         // Catch all exceptions and store them in last error
522                         $this->lastException = $e;
523                         $this->lastError = $e->getMessage();
524                 }
525
526                 // Return the gathered result
527                 return $resultData;
528         }
529
530         /**
531          * "Inserts" a data set instance into a local file database folder
532          *
533          * @param       $dataSetInstance        A storeable data set
534          * @return      void
535          * @throws      SqlException    If an SQL error occurs
536          */
537         public function queryInsertDataSet (StoreableCriteria $dataSetInstance) {
538                 // Create full path name
539                 $fqfn = sprintf("%s%s/%s.%s",
540                         $this->getSavePath(),
541                         $dataSetInstance->getTableName(),
542                         md5($dataSetInstance->getUniqueValue()),
543                         $this->getFileExtension()
544                 );
545
546                 // Try to save the request away
547                 try {
548                         // Write the data away
549                         $this->writeDataArrayToFqfn($fqfn, $dataSetInstance->getCriteriaArray());
550
551                         // Update the primary key
552                         $this->updatePrimaryKey($dataSetInstance);
553
554                         // Reset last error message and exception
555                         $this->resetLastError();
556                 } catch (FrameworkException $e) {
557                         // Catch all exceptions and store them in last error
558                         $this->lastException = $e;
559                         $this->lastError = $e->getMessage();
560
561                         // Throw an SQL exception
562                         throw new SqlException (array($this, sprintf("Cannot write data to table &#39;%s&#39;", $tableName), self::DB_CODE_TABLE_UNWRITEABLE), self::EXCEPTION_SQL_QUERY);
563                 }
564         }
565
566         /**
567          * "Updates" a data set instance with a database layer
568          *
569          * @param       $dataSetInstance        A storeable data set
570          * @return      void
571          * @throws      SqlException    If an SQL error occurs
572          */
573         public function queryUpdateDataSet (StoreableCriteria $dataSetInstance) {
574                 // Create full path name
575                 $pathName = $this->getSavePath() . $dataSetInstance->getTableName() . '/';
576
577                 // Try all the requests
578                 try {
579                         // Get a file pointer instance
580                         $directoryInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName);
581
582                         // Initialize limit/skip
583                         $limitFound = 0;
584                         $skipFound = 0;
585
586                         // Get the criteria array from the dataset
587                         $criteriaArray = $dataSetInstance->getCriteriaArray();
588
589                         // Get search criteria
590                         $searchInstance = $dataSetInstance->getSearchInstance();
591
592                         // Read the directory with some exceptions
593                         while (($dataFile = $directoryInstance->readDirectoryExcept(array(".", "..", ".htaccess", ".svn", "info." . $this->getFileExtension()))) && ($limitFound < $searchInstance->getLimit())) {
594                                 // Does the extension match?
595                                 if (substr($dataFile, -(strlen($this->getFileExtension()))) !== $this->getFileExtension()) {
596                                         // Skip this file!
597                                         continue;
598                                 }
599
600                                 // Open this file for reading
601                                 $dataArray = $this->getDataArrayFromFile($pathName . $dataFile);
602
603                                 // Is this an array?
604                                 if (is_array($dataArray)) {
605                                         // Search in the criteria with FMFW (First Matches, First Wins)
606                                         foreach ($dataArray as $key=>$value) {
607                                                 // Get criteria element
608                                                 $criteria = $searchInstance->getCriteriaElemnent($key);
609
610                                                 // Is the criteria met?
611                                                 if ((!is_null($criteria)) && ($criteria == $value))  {
612
613                                                         // Shall we skip this entry?
614                                                         if ($searchInstance->getSkip() > 0) {
615                                                                 // We shall skip some entries
616                                                                 if ($skipFound < $searchInstance->getSkip()) {
617                                                                         // Skip this entry
618                                                                         $skipFound++;
619                                                                         break;
620                                                                 } // END - if
621                                                         } // END - if
622
623                                                         // Entry found, so update it
624                                                         foreach ($criteriaArray as $criteriaKey=>$criteriaValue) {
625                                                                 $dataArray[$criteriaKey] = $criteriaValue;
626                                                         } // END - foreach
627
628                                                         // Write the data to a local file
629                                                         $this->writeDataArrayToFqfn($pathName . $dataFile, $dataArray);
630
631                                                         // Count it
632                                                         $limitFound++;
633                                                         break;
634                                                 } // END - if
635                                         } // END - foreach
636                                 } // END - if
637                         } // END - while
638
639                         // Close the file pointer
640                         $directoryInstance->closeDirectory();
641
642                         // Update the primary key
643                         $this->updatePrimaryKey($dataSetInstance);
644
645                         // Reset last error message and exception
646                         $this->resetLastError();
647                 } catch (FrameworkException $e) {
648                         // Catch all exceptions and store them in last error
649                         $this->lastException = $e;
650                         $this->lastError = $e->getMessage();
651
652                         // Throw an SQL exception
653                         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);
654                 }
655         }
656
657         /**
658          * Getter for primary key of specified table or if not found null will be
659          * returned. This must be database-specific.
660          *
661          * @param       $tableName              Name of the table we need the primary key from
662          * @return      $primaryKey             Primary key column of the given table
663          */
664         public function getPrimaryKeyOfTable ($tableName) {
665                 // Default key is null
666                 $primaryKey = null;
667
668                 // Does the table information exist?
669                 if (isset($this->tableInfo[$tableName])) {
670                         // Then return the primary key
671                         $primaryKey = $this->tableInfo[$tableName]['primary'];
672                 } // END - if
673
674                 // Return the column
675                 return $primaryKey;
676         }
677 }
678
679 // [EOF]
680 ?>