3 * Database backend class for storing objects in locally created files.
5 * This class serializes objects and saves them to local files.
7 * @author Roland Haeder <webmaster@ship-simu.org>
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
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.
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.
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/>.
26 class LocalFileDatabase extends BaseDatabaseFrontend implements DatabaseFrontendInterface {
28 // Constants for MySQL backward-compatiblity (PLEASE FIX THEM!)
29 const DB_CODE_TABLE_MISSING = 0x010;
30 const DB_CODE_TABLE_UNWRITEABLE = 0x011;
31 const DB_CODE_DATA_FILE_CORRUPT = 0x012;
34 * Save path for "file database"
36 private $savePath = "";
39 * The file's extension
41 private $fileExtension = "serialized";
44 * The last read file's name
46 private $lastFile = "";
49 * The last read file's content including header information
51 private $lastContents = array();
54 * Wether the "connection is already up
56 private $alreadyConnected = false;
61 private $lastError = "";
66 private $lastException = null;
69 * The protected constructor. Do never instance from outside! You need to
70 * set a local file path. The class will then validate it.
74 protected function __construct() {
75 // Call parent constructor
76 parent::__construct(__CLASS__);
79 $this->setObjectDescription("Class for local file databases");
82 $this->generateUniqueId();
85 $this->removeSystemArray();
89 * Create an object of LocalFileDatabase and set the save path for local files.
90 * This method also validates the given file path.
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
97 public final static function createLocalFileDatabase ($savePath, FileIoHandler $ioInstance) {
99 $dbInstance = new LocalFileDatabase();
101 // Set save path and IO instance
102 $dbInstance->setSavePath($savePath);
103 $dbInstance->setFileIoInstance($ioInstance);
105 // "Connect" to the database
106 $dbInstance->connectToDatabase();
108 // Return database instance
113 * Setter for save path
115 * @param $savePath The local save path where we shall put our serialized classes
118 public final function setSavePath ($savePath) {
120 $savePath = (string) $savePath;
123 $this->savePath = $savePath;
127 * Getter for save path
129 * @return $savePath The local save path where we shall put our serialized classes
131 public final function getSavePath () {
132 return $this->savePath;
136 * Getter for last error message
138 * @return $lastError Last error message
140 public final function getLastError () {
141 return $this->lastError;
145 * Getter for last exception
147 * @return $lastException Last thrown exception
149 public final function getLastException () {
150 return $this->lastException;
154 * Analyses if a unique ID has already been used or not by search in the
155 * local database folder.
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
167 public function isUniqueIdUsed ($uniqueID, $inConstructor = false) {
168 // Currently not used... ;-)
171 // Split the unique ID up in path and file name
172 $pathFile = explode("@", $uniqueID);
174 // Are there two elements? Index 0 is the path, 1 the file name + global extension
175 if (!is_array($pathFile)) {
177 if ($inConstructor) {
180 throw new NoArrayCreatedException(array($this, "pathFile"), self::EXCEPTION_ARRAY_EXPECTED);
182 } elseif (count($pathFile) != 2) {
183 // Invalid ID returned!
184 if ($inConstructor) {
187 throw new InvalidArrayCountException(array($this, "pathFile", count($pathFile), 2), self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
191 // Create full path name
192 $pathName = $this->getSavePath() . $pathFile[0];
194 // Check if the file is there with a file handler
195 if ($inConstructor) {
196 // No exceptions in constructors and destructors!
197 $dirInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName, true);
199 // Has an object being created?
200 if (!is_object($dirInstance)) return false;
202 // Outside a constructor
204 $dirInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName);
205 } catch (PathIsNoDirectoryException $e) {
206 // Okay, path not found
211 // Initialize the search loop
213 while ($dataFile = $dirInstance->readDirectoryExcept(array(".", "..", ".htaccess", ".svn"))) {
214 // Generate FQFN for testing
215 $fqfn = sprintf("%s/%s", $pathName, $dataFile);
216 $this->setLastFile($fqfn);
218 // Get instance for file handler
219 $inputHandler = $this->getFileIoInstance();
221 // Try to read from it. This makes it sure that the file is
222 // readable and a valid database file
223 $this->setLastFileContents($inputHandler->loadFileContents($fqfn));
225 // Extract filename (= unique ID) from it
226 $ID = substr(basename($fqfn), 0, -(strlen($this->getFileExtension()) + 1));
228 // Is this the required unique ID?
229 if ($ID == $pathFile[1]) {
230 // Okay, already in use!
235 // Close the directory handler
236 $dirInstance->closeDirectory();
238 // Now the same for the file...
243 * Setter for the last read file
245 * @param $fqfn The FQFN of the last read file
248 private final function setLastFile ($fqfn) {
250 $fqfn = (string) $fqfn;
251 $this->lastFile = $fqfn;
255 * Reset the last error and exception instance. This should be done after
256 * a successfull "query"
260 private final function resetLastError () {
261 $this->lastError = "";
262 $this->lastException = null;
266 * Getter for last read file
268 * @return $lastFile The last read file's name with full path
270 public final function getLastFile () {
271 return $this->lastFile;
275 * Setter for contents of the last read file
277 * @param $contents An array with header and data elements
280 private final function setLastFileContents ($contents) {
282 $contents = (array) $contents;
283 $this->lastContents = $contents;
287 * Getter for last read file's content as an array
289 * @return $lastContent The array with elements 'header' and 'data'.
291 public final function getLastContents () {
292 return $this->lastContents;
296 * Getter for file extension
298 * @return $fileExtension The array with elements 'header' and 'data'.
300 public final function getFileExtension () {
301 return $this->fileExtension;
305 * Get cached (last fetched) data from the local file database
307 * @param $uniqueID The ID number for looking up the data
308 * @return $object The restored object from the maybe compressed
310 * @throws MismatchingCompressorsException If the compressor from
312 * mismatches with the
314 * @throws NullPointerException If the restored object
316 * @throws NoObjectException If the restored "object"
317 * is not an object instance
318 * @throws MissingMethodException If the required method
319 * toString() is missing
322 public final function getObjectFromCachedData ($uniqueID) {
323 // Get instance for file handler
324 $inputHandler = $this->getFileIoInstance();
326 // Get last file's name and contents
327 $fqfn = $this->repairFQFN($this->getLastFile(), $uniqueID);
328 $contents = $this->repairContents($this->getLastContents(), $fqfn);
330 // Let's decompress it. First we need the instance
331 $compressInstance = $this->getCompressorChannel();
333 // Is the compressor's extension the same as the one from the data?
334 if ($compressInstance->getCompressorExtension() != $contents['header'][0]) {
336 * @todo For now we abort here but later we need to make this a little more dynamic.
338 throw new MismatchingCompressorsException(array($this, $contents['header'][0], $fqfn, $compressInstance->getCompressorExtension()), self::EXCEPTION_MISMATCHING_COMPRESSORS);
341 // Decompress the data now
342 $serialized = $compressInstance->getCompressor()->decompressStream($contents['data']);
344 // And unserialize it...
345 $object = unserialize($serialized);
347 // This must become a valid object, so let's check it...
348 if (is_null($object)) {
349 // Is null, throw exception
350 throw new NullPointerException($object, self::EXCEPTION_IS_NULL_POINTER);
351 } elseif (!is_object($object)) {
352 // Is not an object, throw exception
353 throw new NoObjectException($object, self::EXCEPTION_IS_NO_OBJECT);
354 } elseif (!$object instanceof FrameworkInterface) {
355 // A highly required method was not found... :-(
356 throw new MissingMethodException(array($object, '__toString'), self::EXCEPTION_MISSING_METHOD);
359 // And return the object
364 * Private method for re-gathering (repairing) the FQFN
366 * @param $fqfn The current FQFN we shall validate
367 * @param $uniqueID The unique ID number
368 * @return $fqfn The repaired FQFN when it is empty
369 * @throws NoArrayCreatedException If explode() has not
371 * @throws InvalidArrayCountException If the array count is not
375 private function repairFQFN ($fqfn, $uniqueID) {
377 $fqfn = (string) $fqfn;
378 $uniqueID = (string) $uniqueID;
380 // Is there pre-cached data available?
382 // Split the unique ID up in path and file name
383 $pathFile = explode("@", $uniqueID);
385 // Are there two elements? Index 0 is the path, 1 the file name + global extension
386 if (!is_array($pathFile)) {
388 throw new NoArrayCreatedException(array($this, "pathFile"), self::EXCEPTION_ARRAY_EXPECTED);
389 } elseif (count($pathFile) != 2) {
390 // Invalid ID returned!
391 throw new InvalidArrayCountException(array($this, "pathFile", count($pathFile), 2), self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
394 // Create full path name
395 $pathName = $this->getSavePath() . $pathFile[0];
397 // Nothing cached, so let's create a FQFN first
398 $fqfn = sprintf("%s/%s.%s", $pathName, $pathFile[1], $this->getFileExtension());
399 $this->setLastFile($fqfn);
402 // Return repaired FQFN
407 * Private method for re-gathering the contents of a given file
409 * @param $contents The (maybe) already cached contents as an array
410 * @param $fqfn The current FQFN we shall validate
411 * @return $contents The repaired contents from the given file
414 private function repairContents ($contents, $fqfn) {
415 // Is there some content and header (2 indexes) in?
416 if ((!is_array($contents)) || (count($contents) != 2) || (!isset($contents['header'])) || (!isset($contents['data']))) {
417 // No content found so load the file again
418 $contents = $inputHandler->loadFileContents($fqfn);
420 // And remember all data for later usage
421 $this->setLastContents($contents);
424 // Return the repaired contents
429 * Reads a local data file and returns it's contents in an array
431 * @param $fqfn The FQFN for the requested file
434 private function getDataArrayFromFile ($fqfn) {
435 // Get a file pointer
436 $fileInstance = FrameworkFileInputPointer::createFrameworkFileInputPointer($fqfn);
438 // Get the raw data and BASE64-decode it
439 $compressedData = base64_decode($fileInstance->readLinesFromFile());
441 // Close the file and throw the instance away
442 $fileInstance->closeFile();
443 unset($fileInstance);
446 $serializedData = $this->getCompressorChannel()->getCompressor()->decompressStream($compressedData);
449 $dataArray = unserialize($serializedData);
456 * Writes data array to local file
458 * @param $fqfn The FQFN of the local file
459 * @param $dataArray An array with all the data we shall write
462 private function writeDataArrayToFqfn ($fqfn, array $dataArray) {
463 // Get a file pointer instance
464 $fileInstance = FrameworkFileOutputPointer::createFrameworkFileOutputPointer($fqfn, 'w');
466 // Serialize and compress it
467 $compressedData = $this->getCompressorChannel()->getCompressor()->compressStream(serialize($dataArray));
469 // Write this data BASE64 encoded to the file
470 $fileInstance->writeToFile(base64_encode($compressedData));
472 // Close the file pointer
473 $fileInstance->closeFile();
477 * Makes sure that the database connection is alive
481 public function connectToDatabase () {
482 /* @TODO Do some checks on the database directory and files here */
486 * Starts a SELECT query on the database by given return type, table name
487 * and search criteria
489 * @param $resultType Result type ("array", "object" and "indexed" are valid)
490 * @param $tableName Name of the database table
491 * @param $criteria Local search criteria class
492 * @return $resultData Result data of the query
493 * @throws UnsupportedCriteriaException If the criteria is unsupported
494 * @throws SqlException If an "SQL error" occurs
496 public function querySelect ($resultType, $tableName, LocalSearchCriteria $criteriaInstance) {
497 // The result is null by any errors
500 // Create full path name
501 $pathName = $this->getSavePath() . $tableName . '/';
503 // A "select" query is not that easy on local files, so first try to
504 // find the "table" which is in fact a directory on the server
506 // Get a directory pointer instance
507 $directoryInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName);
509 // Initialize the result data, this need to be rewritten e.g. if a local file cannot be read
515 // Initialize limit/skip
516 $limitFound = 0; $skipFound = 0;
518 // Read the directory with some exceptions
519 while (($dataFile = $directoryInstance->readDirectoryExcept(array(".", "..", ".htaccess", ".svn"))) && ($limitFound < $criteriaInstance->getLimit())) {
521 $dataArray = $this->getDataArrayFromFile($pathName . $dataFile);
524 if (is_array($dataArray)) {
525 // Search in the criteria with FMFW (First Matches, First Wins)
526 foreach ($dataArray as $key=>$value) {
527 // Get criteria element
528 $criteria = $criteriaInstance->getCriteriaElemnent($key);
530 // Is the criteria met?
531 if ((!is_null($criteria)) && ($criteria == $value)) {
533 // Shall we skip this entry?
534 if ($criteriaInstance->getSkip() > 0) {
535 // We shall skip some entries
536 if ($skipFound < $criteriaInstance->getSkip()) {
544 $resultData['rows'][] = $dataArray;
550 // Throw an exception here
551 throw new SqlException(sprintf("File '%s' contains invalid data.", $dataFile), self::DB_CODE_DATA_FILE_CORRUPT);
555 // Close directory and throw the instance away
556 $directoryInstance->closeDirectory();
557 unset($directoryInstance);
559 // Reset last error message and exception
560 $this->resetLastError();
561 } catch (PathIsNoDirectoryException $e) {
562 // Path not found means "table not found" for real databases...
563 $this->lastException = $e;
564 $this->lastError = $e->getMessage();
566 // So throw an SqlException here with faked error message
567 throw new SqlException (array($this, sprintf("Table '%s' not found", $tableName), self::DB_CODE_TABLE_MISSING), self::EXCEPTION_SQL_QUERY);
568 } catch (FrameworkException $e) {
569 // Catch all exceptions and store them in last error
570 $this->lastException = $e;
571 $this->lastError = $e->getMessage();
574 // Return the gathered result
579 * "Inserts" a data set instance into a local file database folder
581 * @param $dataSetInstance A storeable data set
583 * @throws SqlException If an SQL error occurs
585 public function queryInsertDataSet (StoreableCriteria $dataSetInstance) {
586 // Create full path name
587 $fqfn = sprintf("%s%s/%s.%s",
588 $this->getSavePath(),
589 $dataSetInstance->getTableName(),
590 md5($dataSetInstance->getUniqueValue()),
591 $this->getFileExtension()
594 // Try to save the request away
596 // Write the data away
597 $this->writeDataArrayToFqfn($fqfn, $dataSetInstance->getCriteriaArray());
599 // Reset last error message and exception
600 $this->resetLastError();
601 } catch (FrameworkException $e) {
602 // Catch all exceptions and store them in last error
603 $this->lastException = $e;
604 $this->lastError = $e->getMessage();
606 // Throw an SQL exception
607 throw new SqlException (array($this, sprintf("Cannot write data to table '%s'", $tableName), self::DB_CODE_TABLE_UNWRITEABLE), self::EXCEPTION_SQL_QUERY);
612 * "Updates" a data set instance with a database layer
614 * @param $dataSetInstance A storeable data set
616 * @throws SqlException If an SQL error occurs
618 public function queryUpdateDataSet (StoreableCriteria $dataSetInstance) {
619 // Create full path name
620 $pathName = $this->getSavePath() . $dataSetInstance->getTableName() . '/';
622 // Try all the requests
624 // Get a file pointer instance
625 $directoryInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName);
627 // Initialize limit/skip
628 $limitFound = 0; $skipFound = 0;
630 // Get the criteria array from the dataset
631 $criteriaArray = $dataSetInstance->getCriteriaArray();
633 // Get search criteria
634 $searchInstance = $dataSetInstance->getSearchInstance();
636 // Read the directory with some exceptions
637 while (($dataFile = $directoryInstance->readDirectoryExcept(array(".", "..", ".htaccess", ".svn"))) && ($limitFound < $searchInstance->getLimit())) {
638 // Open this file for reading
639 $dataArray = $this->getDataArrayFromFile($pathName . $dataFile);
642 if (is_array($dataArray)) {
643 // Search in the criteria with FMFW (First Matches, First Wins)
644 foreach ($dataArray as $key=>$value) {
645 // Get criteria element
646 $criteria = $searchInstance->getCriteriaElemnent($key);
648 // Is the criteria met?
649 if ((!is_null($criteria)) && ($criteria == $value)) {
651 // Shall we skip this entry?
652 if ($searchInstance->getSkip() > 0) {
653 // We shall skip some entries
654 if ($skipFound < $searchInstance->getSkip()) {
661 // Entry found, so update it
662 foreach ($criteriaArray as $criteriaKey=>$criteriaValue) {
663 $dataArray[$criteriaKey] = $criteriaValue;
666 // Write the data to a local file
667 $this->writeDataArrayToFqfn($pathName . $dataFile, $dataArray);
677 // Close the file pointer
678 $directoryInstance->closeDirectory();
680 // Reset last error message and exception
681 $this->resetLastError();
682 } catch (FrameworkException $e) {
683 // Catch all exceptions and store them in last error
684 $this->lastException = $e;
685 $this->lastError = $e->getMessage();
687 // Throw an SQL exception
688 throw new SqlException (array($this, sprintf("Cannot write data to table '%s'", $tableName), self::DB_CODE_TABLE_UNWRITEABLE), self::EXCEPTION_SQL_QUERY);