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;
33 * Save path for "file database"
35 private $savePath = "";
38 * The file's extension
40 private $fileExtension = "serialized";
43 * The last read file's name
45 private $lastFile = "";
48 * The last read file's content including header information
50 private $lastContents = array();
53 * Wether the "connection is already up
55 private $alreadyConnected = false;
60 private $lastError = "";
65 private $lastException = null;
68 * The protected constructor. Do never instance from outside! You need to
69 * set a local file path. The class will then validate it.
73 protected function __construct() {
74 // Call parent constructor
75 parent::__construct(__CLASS__);
78 $this->setObjectDescription("Class for local file databases");
81 $this->generateUniqueId();
84 $this->removeSystemArray();
88 * Create an object of LocalFileDatabase and set the save path for local files.
89 * This method also validates the given file path.
91 * @param $savePath The local file path string
92 * @param $ioInstance The input/output handler. This
93 * should be FileIoHandler
94 * @return $dbInstance An instance of LocalFileDatabase
96 public final static function createLocalFileDatabase ($savePath, FileIoHandler $ioInstance) {
98 $dbInstance = new LocalFileDatabase();
100 // Set save path and IO instance
101 $dbInstance->setSavePath($savePath);
102 $dbInstance->setFileIoInstance($ioInstance);
104 // "Connect" to the database
105 $dbInstance->connectToDatabase();
107 // Return database instance
112 * Setter for save path
114 * @param $savePath The local save path where we shall put our serialized classes
117 public final function setSavePath ($savePath) {
119 $savePath = (string) $savePath;
122 $this->savePath = $savePath;
126 * Getter for save path
128 * @return $savePath The local save path where we shall put our serialized classes
130 public final function getSavePath () {
131 return $this->savePath;
135 * Getter for last error message
137 * @return $lastError Last error message
139 public final function getLastError () {
140 return $this->lastError;
144 * Getter for last exception
146 * @return $lastException Last thrown exception
148 public final function getLastException () {
149 return $this->lastException;
153 * Saves a given object to the local file system by serializing and
154 * transparently compressing it
156 * @param $object The object we shall save to the local file system
159 public final function saveObject (FrameworkInterface $object) {
160 // Get a string containing the serialized object. We cannot exchange
161 // $this and $object here because $object does not need to worry
162 // about it's limitations... ;-)
163 $serialized = $this->serializeObject($object);
165 // Get a path name plus file name and append the extension
166 $fqfn = $this->getSavePath() . $object->getPathFileNameFromObject() . "." . $this->getFileExtension();
168 // Save the file to disc we don't care here if the path is there,
169 // this must be done in later methods.
170 $this->getFileIoInstance()->saveFile($fqfn, array($this->getCompressorChannel()->getCompressorExtension(), $serialized));
174 * Get a serialized string from the given object
176 * @param $object The object we want to serialize and transparently
178 * @return $serialized A string containing the serialzed/compressed object
179 * @see ObjectLimits An object holding limition information
180 * @see SerializationContainer A special container class for e.g.
181 * attributes from limited objects
183 private function serializeObject (FrameworkInterface $object) {
184 // If there is no limiter instance we serialize the whole object
185 // otherwise only in the limiter object (ObjectLimits) specified
186 // attributes summarized in a special container class
187 if ($this->getLimitInstance() === null) {
188 // Serialize the whole object. This tribble call is the reason
189 // why we need a fall-back implementation in CompressorChannel
190 // of the methods compressStream() and decompressStream().
191 $serialized = $this->getCompressorChannel()->getCompressor()->compressStream(serialize($object));
193 // Serialize only given attributes in a special container
194 $container = SerializationContainer::createSerializationContainer($this->getLimitInstance(), $object);
196 // Serialize the container
197 $serialized = $this->getCompressorChannel()->getCompressor()->compressStream(serialize($container));
200 // Return the serialized object string
205 * Analyses if a unique ID has already been used or not by search in the
206 * local database folder.
208 * @param $uniqueID A unique ID number which shall be checked
209 * before it will be used
210 * @param $inConstructor If we got called in a de/con-structor or
211 * from somewhere else
212 * @return $isUnused true = The unique ID was not found in the database,
213 * false = It is already in use by an other object
214 * @throws NoArrayCreatedException If explode() fails to create an array
215 * @throws InvalidArrayCountException If the array contains less or
216 * more than two elements
218 public function isUniqueIdUsed ($uniqueID, $inConstructor = false) {
219 // Currently not used... ;-)
222 // Split the unique ID up in path and file name
223 $pathFile = explode("@", $uniqueID);
225 // Are there two elements? Index 0 is the path, 1 the file name + global extension
226 if (!is_array($pathFile)) {
228 if ($inConstructor) {
231 throw new NoArrayCreatedException(array($this, "pathFile"), self::EXCEPTION_ARRAY_EXPECTED);
233 } elseif (count($pathFile) != 2) {
234 // Invalid ID returned!
235 if ($inConstructor) {
238 throw new InvalidArrayCountException(array($this, "pathFile", count($pathFile), 2), self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
242 // Create full path name
243 $pathName = $this->getSavePath() . $pathFile[0];
245 // Check if the file is there with a file handler
246 if ($inConstructor) {
247 // No exceptions in constructors and destructors!
248 $dirInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName, true);
250 // Has an object being created?
251 if (!is_object($dirInstance)) return false;
253 // Outside a constructor
255 $dirInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName);
256 } catch (PathIsNoDirectoryException $e) {
257 // Okay, path not found
262 // Initialize the search loop
264 while ($dataFile = $dirInstance->readDirectoryExcept(array(".", "..", ".htaccess", ".svn"))) {
265 // Generate FQFN for testing
266 $fqfn = sprintf("%s/%s", $pathName, $dataFile);
267 $this->setLastFile($fqfn);
269 // Get instance for file handler
270 $inputHandler = $this->getFileIoInstance();
272 // Try to read from it. This makes it sure that the file is
273 // readable and a valid database file
274 $this->setLastFileContents($inputHandler->loadFileContents($fqfn));
276 // Extract filename (= unique ID) from it
277 $ID = substr(basename($fqfn), 0, -(strlen($this->getFileExtension()) + 1));
279 // Is this the required unique ID?
280 if ($ID == $pathFile[1]) {
281 // Okay, already in use!
286 // Close the directory handler
287 $dirInstance->closeDirectory();
289 // Now the same for the file...
294 * Setter for the last read file
296 * @param $fqfn The FQFN of the last read file
299 private final function setLastFile ($fqfn) {
301 $fqfn = (string) $fqfn;
302 $this->lastFile = $fqfn;
306 * Reset the last error and exception instance. This should be done after
307 * a successfull "query"
311 private final function resetLastError () {
312 $this->lastError = "";
313 $this->lastException = null;
317 * Getter for last read file
319 * @return $lastFile The last read file's name with full path
321 public final function getLastFile () {
322 return $this->lastFile;
326 * Setter for contents of the last read file
328 * @param $contents An array with header and data elements
331 private final function setLastFileContents ($contents) {
333 $contents = (array) $contents;
334 $this->lastContents = $contents;
338 * Getter for last read file's content as an array
340 * @return $lastContent The array with elements 'header' and 'data'.
342 public final function getLastContents () {
343 return $this->lastContents;
347 * Getter for file extension
349 * @return $fileExtension The array with elements 'header' and 'data'.
351 public final function getFileExtension () {
352 return $this->fileExtension;
356 * Get cached (last fetched) data from the local file database
358 * @param $uniqueID The ID number for looking up the data
359 * @return $object The restored object from the maybe compressed
361 * @throws MismatchingCompressorsException If the compressor from
363 * mismatches with the
365 * @throws NullPointerException If the restored object
367 * @throws NoObjectException If the restored "object"
368 * is not an object instance
369 * @throws MissingMethodException If the required method
370 * toString() is missing
372 public final function getObjectFromCachedData ($uniqueID) {
373 // Get instance for file handler
374 $inputHandler = $this->getFileIoInstance();
376 // Get last file's name and contents
377 $fqfn = $this->repairFQFN($this->getLastFile(), $uniqueID);
378 $contents = $this->repairContents($this->getLastContents(), $fqfn);
380 // Let's decompress it. First we need the instance
381 $compressInstance = $this->getCompressorChannel();
383 // Is the compressor's extension the same as the one from the data?
384 if ($compressInstance->getCompressorExtension() != $contents['header'][0]) {
386 * @todo For now we abort here but later we need to make this a little more dynamic.
388 throw new MismatchingCompressorsException(array($this, $contents['header'][0], $fqfn, $compressInstance->getCompressorExtension()), self::EXCEPTION_MISMATCHING_COMPRESSORS);
391 // Decompress the data now
392 $serialized = $compressInstance->getCompressor()->decompressStream($contents['data']);
394 // And unserialize it...
395 $object = unserialize($serialized);
397 // This must become a valid object, so let's check it...
398 if (is_null($object)) {
399 // Is null, throw exception
400 throw new NullPointerException($object, self::EXCEPTION_IS_NULL_POINTER);
401 } elseif (!is_object($object)) {
402 // Is not an object, throw exception
403 throw new NoObjectException($object, self::EXCEPTION_IS_NO_OBJECT);
404 } elseif (!$object instanceof FrameworkInterface) {
405 // A highly required method was not found... :-(
406 throw new MissingMethodException(array($object, '__toString'), self::EXCEPTION_MISSING_METHOD);
409 // And return the object
414 * Private method for re-gathering (repairing) the FQFN
416 * @param $fqfn The current FQFN we shall validate
417 * @param $uniqueID The unique ID number
418 * @return $fqfn The repaired FQFN when it is empty
419 * @throws NoArrayCreatedException If explode() has not
421 * @throws InvalidArrayCountException If the array count is not
424 private function repairFQFN ($fqfn, $uniqueID) {
426 $fqfn = (string) $fqfn;
427 $uniqueID = (string) $uniqueID;
429 // Is there pre-cached data available?
431 // Split the unique ID up in path and file name
432 $pathFile = explode("@", $uniqueID);
434 // Are there two elements? Index 0 is the path, 1 the file name + global extension
435 if (!is_array($pathFile)) {
437 throw new NoArrayCreatedException(array($this, "pathFile"), self::EXCEPTION_ARRAY_EXPECTED);
438 } elseif (count($pathFile) != 2) {
439 // Invalid ID returned!
440 throw new InvalidArrayCountException(array($this, "pathFile", count($pathFile), 2), self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
443 // Create full path name
444 $pathName = $this->getSavePath() . $pathFile[0];
446 // Nothing cached, so let's create a FQFN first
447 $fqfn = sprintf("%s/%s.%s", $pathName, $pathFile[1], $this->getFileExtension());
448 $this->setLastFile($fqfn);
451 // Return repaired FQFN
456 * Private method for re-gathering the contents of a given file
458 * @param $contents The (maybe) already cached contents as an array
459 * @param $fqfn The current FQFN we shall validate
460 * @return $contents The repaired contents from the given file
462 private function repairContents ($contents, $fqfn) {
463 // Is there some content and header (2 indexes) in?
464 if ((!is_array($contents)) || (count($contents) != 2) || (!isset($contents['header'])) || (!isset($contents['data']))) {
465 // No content found so load the file again
466 $contents = $inputHandler->loadFileContents($fqfn);
468 // And remember all data for later usage
469 $this->setLastContents($contents);
472 // Return the repaired contents
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 * Loads data saved with saveObject from the database and re-creates a
487 * full object from it.
488 * If limitObject() was called before a new object ObjectContainer with
489 * all requested attributes will be returned instead.
491 * @return Object The fully re-created object or instance to
493 * @throws SavePathIsEmptyException If the given save path is an
495 * @throws SavePathIsNoDirectoryException If the save path is no
497 * @throws SavePathReadProtectedException If the save path is read-
499 * @throws SavePathWriteProtectedException If the save path is write-
502 public function loadObject () {
503 // Already connected? Then abort here
504 if ($this->alreadyConnected === true) return true;
507 $savePath = $this->getSavePath();
509 if (empty($savePath)) {
511 throw new SavePathIsEmptyException($dbInstance, self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
512 } elseif (!is_dir($savePath)) {
514 throw new SavePathIsNoDirectoryException($savePath, self::EXCEPTION_INVALID_PATH_NAME);
515 } elseif (!is_readable($savePath)) {
517 throw new SavePathReadProtectedException($savePath, self::EXCEPTION_READ_PROTECED_PATH);
518 } elseif (!is_writeable($savePath)) {
519 // Path not writeable
520 throw new SavePathWriteProtectedException($savePath, self::EXCEPTION_WRITE_PROTECED_PATH);
523 // "Connection" established... ;-)
524 $this->alreadyConnected = true;
528 * Starts a SELECT query on the database by given return type, table name
529 * and search criteria
531 * @param $resultType Result type ("array", "object" and "indexed" are valid)
532 * @param $tableName Name of the database table
533 * @param $criteria Local search criteria class
534 * @return $resultData Result data of the query
535 * @throws UnsupportedCriteriaException If the criteria is unsupported
536 * @throws SqlException If an "SQL error" occurs
538 public function querySelect ($resultType, $tableName, LocalSearchCriteria $criteriaInstance) {
539 // The result is null by any errors
542 // Create full path name
543 $pathName = $this->getSavePath() . $tableName . '/';
545 // A "select" query is not that easy on local files, so first try to
546 // find the "table" which is in fact a directory on the server
548 // Get a directory pointer instance
549 $directoryInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName);
551 // Initialize the result data, this need to be rewritten e.g. if a local file cannot be read
557 // Initialize limit/skip
558 $limitFound = 0; $skipFound = 0;
560 // Read the directory with some exceptions
561 while (($dataFile = $directoryInstance->readDirectoryExcept(array(".", "..", ".htaccess", ".svn"))) && ($limitFound < $criteriaInstance->getLimit())) {
562 // Open this file for reading
563 $filePointer = FrameworkFileInputPointer::createFrameworkFileInputPointer($pathName . $dataFile);
565 // Get the raw data and BASE64-decode it
566 $compressedData = base64_decode($filePointer->readLinesFromFile());
568 // Close the file and throw the instance away
569 $filePointer->closeFile();
573 $serializedData = $this->getCompressorChannel()->getCompressor()->decompressStream($compressedData);
576 $dataArray = unserialize($serializedData);
579 if (is_array($dataArray)) {
580 // Search in the criteria with FMFW (First Matches, First Wins)
581 foreach ($dataArray as $key=>$value) {
582 // Get criteria element
583 $criteria = $criteriaInstance->getCriteriaElemnent($key);
585 // Is the criteria met?
586 if ((!is_null($criteria)) && ($criteria == $value)) {
588 // Shall we skip this entry?
589 if ($criteriaInstance->getSkip() > 0) {
590 // We shall skip some entries
591 if ($skipFound < $criteriaInstance->getSkip()) {
599 $resultData['rows'][] = $dataArray;
607 // Close directory and throw the instance away
608 $directoryInstance->closeDirectory();
609 unset($directoryInstance);
611 // Reset last error message and exception
612 $this->resetLastError();
613 } catch (PathIsNoDirectoryException $e) {
614 // Path not found means "table not found" for real databases...
615 $this->lastException = $e;
616 $this->lastError = $e->getMessage();
618 // So throw an SqlException here with faked error message
619 throw new SqlException (array($this, sprintf("Table '%s' not found", $tableName), self::DB_CODE_TABLE_MISSING), self::EXCEPTION_SQL_QUERY);
620 } catch (FrameworkException $e) {
621 // Catch all exceptions and store them in last error
622 $this->lastException = $e;
623 $this->lastError = $e->getMessage();
626 // Return the gathered result
631 * "Inserts" a data set instance into a local file database folder
633 * @param $dataSetInstance A storeable data set
635 * @throws SqlException If an SQL error occurs
637 public function queryInsertDataSet (StoreableCriteria $dataSetInstance) {
638 // Create full path name
639 $fqfn = sprintf("%s%s/%s.%s",
640 $this->getSavePath(),
641 $dataSetInstance->getTableName(),
642 md5($dataSetInstance->getUniqueValue()),
643 $this->getFileExtension()
646 // Try to save the request away
648 // Get a file pointer instance
649 $filePointer = FrameworkFileOutputPointer::createFrameworkFileOutputPointer($fqfn, 'w');
651 // Get the criteria array from the dataset
652 $criteriaArray = $dataSetInstance->getCriteriaArray();
654 // Serialize and compress it
655 $compressedData = $this->getCompressorChannel()->getCompressor()->compressStream(serialize($criteriaArray));
657 // Write this data BASE64 encoded to the file
658 $filePointer->writeToFile(base64_encode($compressedData));
660 // Close the file pointer
661 $filePointer->closeFile();
663 // Reset last error message and exception
664 $this->resetLastError();
665 } catch (FrameworkException $e) {
666 // Catch all exceptions and store them in last error
667 $this->lastException = $e;
668 $this->lastError = $e->getMessage();
670 // Throw an SQL exception
671 throw new SqlException (array($this, sprintf("Cannot write data to table '%s'", $tableName), self::DB_CODE_TABLE_UNWRITEABLE), self::EXCEPTION_SQL_QUERY);