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 * Reads a local data file and returns it's contents in an array
307 * @param $fqfn The FQFN for the requested file
310 private function getDataArrayFromFile ($fqfn) {
311 // Get a file pointer
312 $fileInstance = FrameworkFileInputPointer::createFrameworkFileInputPointer($fqfn);
314 // Get the raw data and BASE64-decode it
315 $compressedData = base64_decode($fileInstance->readLinesFromFile());
317 // Close the file and throw the instance away
318 $fileInstance->closeFile();
319 unset($fileInstance);
322 $serializedData = $this->getCompressorChannel()->getCompressor()->decompressStream($compressedData);
325 $dataArray = unserialize($serializedData);
332 * Writes data array to local file
334 * @param $fqfn The FQFN of the local file
335 * @param $dataArray An array with all the data we shall write
338 private function writeDataArrayToFqfn ($fqfn, array $dataArray) {
339 // Get a file pointer instance
340 $fileInstance = FrameworkFileOutputPointer::createFrameworkFileOutputPointer($fqfn, 'w');
342 // Serialize and compress it
343 $compressedData = $this->getCompressorChannel()->getCompressor()->compressStream(serialize($dataArray));
345 // Write this data BASE64 encoded to the file
346 $fileInstance->writeToFile(base64_encode($compressedData));
348 // Close the file pointer
349 $fileInstance->closeFile();
353 * Makes sure that the database connection is alive
357 public function connectToDatabase () {
358 /* @todo Do some checks on the database directory and files here */
362 * Starts a SELECT query on the database by given return type, table name
363 * and search criteria
365 * @param $resultType Result type ("array", "object" and "indexed" are valid)
366 * @param $tableName Name of the database table
367 * @param $criteria Local search criteria class
368 * @return $resultData Result data of the query
369 * @throws UnsupportedCriteriaException If the criteria is unsupported
370 * @throws SqlException If an "SQL error" occurs
372 public function querySelect ($resultType, $tableName, LocalSearchCriteria $criteriaInstance) {
373 // The result is null by any errors
376 // Create full path name
377 $pathName = $this->getSavePath() . $tableName . '/';
379 // A "select" query is not that easy on local files, so first try to
380 // find the "table" which is in fact a directory on the server
382 // Get a directory pointer instance
383 $directoryInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName);
385 // Initialize the result data, this need to be rewritten e.g. if a local file cannot be read
391 // Initialize limit/skip
392 $limitFound = 0; $skipFound = 0;
394 // Read the directory with some exceptions
395 while (($dataFile = $directoryInstance->readDirectoryExcept(array(".", "..", ".htaccess", ".svn"))) && ($limitFound < $criteriaInstance->getLimit())) {
397 $dataArray = $this->getDataArrayFromFile($pathName . $dataFile);
400 if (is_array($dataArray)) {
401 // Search in the criteria with FMFW (First Matches, First Wins)
402 foreach ($dataArray as $key=>$value) {
403 // Get criteria element
404 $criteria = $criteriaInstance->getCriteriaElemnent($key);
406 // Is the criteria met?
407 if ((!is_null($criteria)) && ($criteria == $value)) {
409 // Shall we skip this entry?
410 if ($criteriaInstance->getSkip() > 0) {
411 // We shall skip some entries
412 if ($skipFound < $criteriaInstance->getSkip()) {
420 $resultData['rows'][] = $dataArray;
426 // Throw an exception here
427 throw new SqlException(sprintf("File '%s' contains invalid data.", $dataFile), self::DB_CODE_DATA_FILE_CORRUPT);
431 // Close directory and throw the instance away
432 $directoryInstance->closeDirectory();
433 unset($directoryInstance);
435 // Reset last error message and exception
436 $this->resetLastError();
437 } catch (PathIsNoDirectoryException $e) {
438 // Path not found means "table not found" for real databases...
439 $this->lastException = $e;
440 $this->lastError = $e->getMessage();
442 // So throw an SqlException here with faked error message
443 throw new SqlException (array($this, sprintf("Table '%s' not found", $tableName), self::DB_CODE_TABLE_MISSING), self::EXCEPTION_SQL_QUERY);
444 } catch (FrameworkException $e) {
445 // Catch all exceptions and store them in last error
446 $this->lastException = $e;
447 $this->lastError = $e->getMessage();
450 // Return the gathered result
455 * "Inserts" a data set instance into a local file database folder
457 * @param $dataSetInstance A storeable data set
459 * @throws SqlException If an SQL error occurs
461 public function queryInsertDataSet (StoreableCriteria $dataSetInstance) {
462 // Create full path name
463 $fqfn = sprintf("%s%s/%s.%s",
464 $this->getSavePath(),
465 $dataSetInstance->getTableName(),
466 md5($dataSetInstance->getUniqueValue()),
467 $this->getFileExtension()
470 // Try to save the request away
472 // Write the data away
473 $this->writeDataArrayToFqfn($fqfn, $dataSetInstance->getCriteriaArray());
475 // Reset last error message and exception
476 $this->resetLastError();
477 } catch (FrameworkException $e) {
478 // Catch all exceptions and store them in last error
479 $this->lastException = $e;
480 $this->lastError = $e->getMessage();
482 // Throw an SQL exception
483 throw new SqlException (array($this, sprintf("Cannot write data to table '%s'", $tableName), self::DB_CODE_TABLE_UNWRITEABLE), self::EXCEPTION_SQL_QUERY);
488 * "Updates" a data set instance with a database layer
490 * @param $dataSetInstance A storeable data set
492 * @throws SqlException If an SQL error occurs
494 public function queryUpdateDataSet (StoreableCriteria $dataSetInstance) {
495 // Create full path name
496 $pathName = $this->getSavePath() . $dataSetInstance->getTableName() . '/';
498 // Try all the requests
500 // Get a file pointer instance
501 $directoryInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName);
503 // Initialize limit/skip
504 $limitFound = 0; $skipFound = 0;
506 // Get the criteria array from the dataset
507 $criteriaArray = $dataSetInstance->getCriteriaArray();
509 // Get search criteria
510 $searchInstance = $dataSetInstance->getSearchInstance();
512 // Read the directory with some exceptions
513 while (($dataFile = $directoryInstance->readDirectoryExcept(array(".", "..", ".htaccess", ".svn"))) && ($limitFound < $searchInstance->getLimit())) {
514 // Open this file for reading
515 $dataArray = $this->getDataArrayFromFile($pathName . $dataFile);
518 if (is_array($dataArray)) {
519 // Search in the criteria with FMFW (First Matches, First Wins)
520 foreach ($dataArray as $key=>$value) {
521 // Get criteria element
522 $criteria = $searchInstance->getCriteriaElemnent($key);
524 // Is the criteria met?
525 if ((!is_null($criteria)) && ($criteria == $value)) {
527 // Shall we skip this entry?
528 if ($searchInstance->getSkip() > 0) {
529 // We shall skip some entries
530 if ($skipFound < $searchInstance->getSkip()) {
537 // Entry found, so update it
538 foreach ($criteriaArray as $criteriaKey=>$criteriaValue) {
539 $dataArray[$criteriaKey] = $criteriaValue;
542 // Write the data to a local file
543 $this->writeDataArrayToFqfn($pathName . $dataFile, $dataArray);
553 // Close the file pointer
554 $directoryInstance->closeDirectory();
556 // Reset last error message and exception
557 $this->resetLastError();
558 } catch (FrameworkException $e) {
559 // Catch all exceptions and store them in last error
560 $this->lastException = $e;
561 $this->lastError = $e->getMessage();
563 // Throw an SQL exception
564 throw new SqlException (array($this, sprintf("Cannot write data to table '%s'", $tableName), self::DB_CODE_TABLE_UNWRITEABLE), self::EXCEPTION_SQL_QUERY);