Code merge from latest Ship-Simu code
[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          * Save path for "file database"
29          */
30         private $savePath = "";
31
32         /**
33          * The file's extension
34          */
35         private $fileExtension = "serialized";
36
37         /**
38          * The last read file's name
39          */
40         private $lastFile = "";
41
42         /**
43          * The last read file's content including header information
44          */
45         private $lastContents = array();
46
47         /**
48          * Wether the "connection is already up
49          */
50         private $alreadyConnected = false;
51
52         /**
53          * The private constructor. Do never instance from outside!
54          * You need to set a local file path. The class will then validate it.
55          *
56          * @return      void
57          */
58         protected function __construct() {
59                 // Call parent constructor
60                 parent::__construct(__CLASS__);
61
62                 // Set description
63                 $this->setObjectDescription("Class for local file databases");
64
65                 // Create unique ID
66                 $this->createUniqueID();
67
68                 // Clean up a little
69                 $this->removeSystemArray();
70         }
71
72         /**
73          * Create an object of LocalFileDatabase and set the save path for local files.
74          * This method also validates the given file path.
75          *
76          * @param               $savePath                                       The local file path string
77          * @param               $ioInstance                             The input/output handler. This
78          *                                                                      should be FileIoHandler
79          * @return      $dbInstance                             An instance of LocalFileDatabase
80          */
81         public final static function createLocalFileDatabase ($savePath, FileIoHandler $ioInstance) {
82                 // Get an instance
83                 $dbInstance = new LocalFileDatabase();
84
85                 // Set save path and IO instance
86                 $dbInstance->setSavePath($savePath);
87                 $dbInstance->setFileIoInstance($ioInstance);
88
89                 // "Connect" to the database
90                 $dbInstance->connectToDatabase();
91
92                 // Return database instance
93                 return $dbInstance;
94         }
95
96         /**
97          * Setter for save path
98          *
99          * @param               $savePath               The local save path where we shall put our serialized classes
100          * @return      void
101          */
102         public final function setSavePath ($savePath) {
103                 // Secure string
104                 $savePath = (string) $savePath;
105
106                 // Set save path
107                 $this->savePath = $savePath;
108         }
109
110         /**
111          * Getter for save path
112          *
113          * @return      $savePath               The local save path where we shall put our serialized classes
114          */
115         public final function getSavePath () {
116                 return $this->savePath;
117         }
118
119         /**
120          * Saves a given object to the local file system by serializing and
121          * transparently compressing it
122          *
123          * @param               $object                         The object we shall save to the local file system
124          * @return      void
125          * @throws      NullPointerException    If the object instance is null
126          * @throws      NoObjectException               If the parameter $object is not
127          *                                                              an object
128          */
129         public final function saveObject ($object) {
130                 // Some tests on the parameter...
131                 if (is_null($object)) {
132                         // Is null, throw exception
133                         throw new NullPointerException($object, self::EXCEPTION_IS_NULL_POINTER);
134                 } elseif (!is_object($object)) {
135                         // Is not an object, throw exception
136                         throw new NoObjectException($object, self::EXCEPTION_IS_NO_OBJECT);
137                 } elseif (!method_exists($object, '__toString')) {
138                         // A highly required method was not found... :-(
139                         throw new MissingMethodException(array($object, '__toString'), self::EXCEPTION_MISSING_METHOD);
140                 }
141
142                 // Get a string containing the serialized object. We cannot exchange
143                 // $this and $object here because $object does not need to worry
144                 // about it's limitations... ;-)
145                 $serialized = $this->serializeObject($object);
146
147                 // Get a path name plus file name and append the extension
148                 $fqfn = $this->getSavePath() . $object->getPathFileNameFromObject() . "." . $this->getFileExtension();
149
150                 // Save the file to disc we don't care here if the path is there,
151                 // this must be done in later methods.
152                 $this->getFileIoInstance()->saveFile($fqfn, array($this->getCompressorChannel()->getCompressorExtension(), $serialized));
153         }
154
155         /**
156          * Get a serialized string from the given object
157          *
158          * @param               $object         The object we want to serialize and transparently
159          *                                              compress
160          * @return      $serialized     A string containing the serialzed/compressed object
161          * @see         ObjectLimits    An object holding limition information
162          * @see         SerializationContainer  A special container class for e.g.
163          *                                                              attributes from limited objects
164          */
165         private function serializeObject ($object) {
166                 // If there is no limiter instance we serialize the whole object
167                 // otherwise only in the limiter object (ObjectLimits) specified
168                 // attributes summarized in a special container class
169                 if ($this->getLimitInstance() === null) {
170                         // Serialize the whole object. This tribble call is the reason
171                         // why we need a fall-back implementation in CompressorChannel
172                         // of the methods compressStream() and decompressStream().
173                         $serialized = $this->getCompressorChannel()->getCompressor()->compressStream(serialize($object));
174                 } else {
175                         // Serialize only given attributes in a special container
176                         $container = SerializationContainer::createSerializationContainer($this->getLimitInstance(), $object);
177
178                         // Serialize the container
179                         $serialized = $this->getCompressorChannel()->getCompressor()->compressStream(serialize($container));
180                 }
181
182                 // Return the serialized object string
183                 return $serialized;
184         }
185
186         /**
187          * Analyses if a unique ID has already been used or not by search in the
188          * local database folder.
189          *
190          * @param               $uniqueID               A unique ID number which shall be checked
191          *                                              before it will be used
192          * @param               $inConstructor  If we got called in a de/con-structor or
193          *                                              from somewhere else
194          * @return      $isUnused               true    = The unique ID was not found in the database,
195          *                                              false = It is already in use by an other object
196          * @throws      NoArrayCreatedException If explode() fails to create an array
197          * @throws      InvalidArrayCountException      If the array contains less or
198          *                                                                      more than two elements
199          */
200         public function isUniqueIdUsed ($uniqueID, $inConstructor = false) {
201                 // Currently not used... ;-)
202                 $isUsed = false;
203
204                 // Split the unique ID up in path and file name
205                 $pathFile = explode("@", $uniqueID);
206
207                 // Are there two elements? Index 0 is the path, 1 the file name + global extension
208                 if (!is_array($pathFile)) {
209                         // No array found
210                         if ($inConstructor) {
211                                 return false;
212                         } else {
213                                 throw new NoArrayCreatedException(array($this, "pathFile"), self::EXCEPTION_ARRAY_EXPECTED);
214                         }
215                 } elseif (count($pathFile) != 2) {
216                         // Invalid ID returned!
217                         if ($inConstructor) {
218                                 return false;
219                         } else {
220                                 throw new InvalidArrayCountException(array($this, "pathFile", count($pathFile), 2), self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
221                         }
222                 }
223
224                 // Create full path name
225                 $pathName = $this->getSavePath() . $pathFile[0];
226
227                 // Check if the file is there with a file handler
228                 if ($inConstructor) {
229                         // No exceptions in constructors and destructors!
230                         $dirInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName, true);
231
232                         // Has an object being created?
233                         if (!is_object($dirInstance)) return false;
234                 } else {
235                         // Outside a constructor
236                         try {
237                                 $dirInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName);
238                         } catch (PathIsNoDirectoryException $e) {
239                                 // Okay, path not found
240                                 return false;
241                         }
242                 }
243
244                 // Initialize the search loop
245                 $isValid = false;
246                 while ($dataFile = $dirInstance->readDirectoryExcept(array(".", ".."))) {
247                         // Generate FQFN for testing
248                         $fqfn = sprintf("%s/%s", $pathName, $dataFile);
249                         $this->setLastFile($fqfn);
250
251                         // Get instance for file handler
252                         $inputHandler = $this->getFileIoInstance();
253
254                         // Try to read from it. This makes it sure that the file is
255                         // readable and a valid database file
256                         $this->setLastFileContents($inputHandler->loadFileContents($fqfn));
257
258                         // Extract filename (= unique ID) from it
259                         $ID = substr(basename($fqfn), 0, -(strlen($this->getFileExtension()) + 1));
260
261                         // Is this the required unique ID?
262                         if ($ID == $pathFile[1]) {
263                                 // Okay, already in use!
264                                 $isUsed = true;
265                         }
266                 }
267
268                 // Close the directory handler
269                 $dirInstance->closeDirectory();
270
271                 // Now the same for the file...
272                 return $isUsed;
273         }
274
275         /**
276          * Setter for the last read file
277          *
278          * @param               $fqfn   The FQFN of the last read file
279          * @return      void
280          */
281         private final function setLastFile ($fqfn) {
282                 // Cast string
283                 $fqfn = (string) $fqfn;
284                 $this->lastFile = $fqfn;
285         }
286
287         /**
288          * Getter for last read file
289          *
290          * @return      $lastFile               The last read file's name with full path
291          */
292         public final function getLastFile () {
293                 return $this->lastFile;
294         }
295
296         /**
297          * Setter for contents of the last read file
298          *
299          * @param               $contents               An array with header and data elements
300          * @return      void
301          */
302         private final function setLastFileContents ($contents) {
303                 // Cast array
304                 $contents = (array) $contents;
305                 $this->lastContents = $contents;
306         }
307
308         /**
309          * Getter for last read file's content as an array
310          *
311          * @return      $lastContent    The array with elements 'header' and 'data'.
312          */
313         public final function getLastContents () {
314                 return $this->lastContents;
315         }
316
317         /**
318          * Getter for file extension
319          *
320          * @return      $fileExtension  The array with elements 'header' and 'data'.
321          */
322         public final function getFileExtension () {
323                 return $this->fileExtension;
324         }
325
326         /**
327          * Get cached (last fetched) data from the local file database
328          *
329          * @param       $uniqueID       The ID number for looking up the data
330          * @return      $object         The restored object from the maybe compressed
331          *                                              serialized data
332          * @throws      MismatchingCompressorsException         If the compressor from
333          *                                                                      the loaded file
334          *                                                                      mismatches with the
335          *                                                                      current used one.
336          * @throws      NullPointerException    If the restored object
337          *                                                                      is null
338          * @throws      NoObjectException               If the restored "object"
339          *                                                                      is not an object instance
340          * @throws      MissingMethodException  If the required method
341          *                                                                      toString() is missing
342          */
343         public final function getObjectFromCachedData ($uniqueID) {
344                 // Get instance for file handler
345                 $inputHandler = $this->getFileIoInstance();
346
347                 // Get last file's name and contents
348                 $fqfn = $this->repairFQFN($this->getLastFile(), $uniqueID);
349                 $contents = $this->repairContents($this->getLastContents(), $fqfn);
350
351                 // Let's decompress it. First we need the instance
352                 $compressInstance = $this->getCompressorChannel();
353
354                 // Is the compressor's extension the same as the one from the data?
355                 if ($compressInstance->getCompressorExtension() != $contents['header'][0]) {
356                         /**
357                          * @todo        For now we abort here but later we need to make this a little more dynamic.
358                          */
359                         throw new MismatchingCompressorsException(array($this, $contents['header'][0], $fqfn, $compressInstance->getCompressorExtension()), self::EXCEPTION_MISMATCHING_COMPRESSORS);
360                 }
361
362                 // Decompress the data now
363                 $serialized = $compressInstance->getCompressor()->decompressStream($contents['data']);
364
365                 // And unserialize it...
366                 $object = unserialize($serialized);
367
368                 // This must become a valid object, so let's check it...
369                 if (is_null($object)) {
370                         // Is null, throw exception
371                         throw new NullPointerException($object, self::EXCEPTION_IS_NULL_POINTER);
372                 } elseif (!is_object($object)) {
373                         // Is not an object, throw exception
374                         throw new NoObjectException($object, self::EXCEPTION_IS_NO_OBJECT);
375                 } elseif (!$object instanceof FrameworkInterface) {
376                         // A highly required method was not found... :-(
377                         throw new MissingMethodException(array($object, '__toString'), self::EXCEPTION_MISSING_METHOD);
378                 }
379
380                 // And return the object
381                 return $object;
382         }
383
384         /**
385          * Private method for re-gathering (repairing) the FQFN
386          *
387          * @param               $fqfn           The current FQFN we shall validate
388          * @param               $uniqueID               The unique ID number
389          * @return      $fqfn           The repaired FQFN when it is empty
390          * @throws      NoArrayCreatedException         If explode() has not
391          *                                                                      created an array
392          * @throws      InvalidArrayCountException      If the array count is not
393          *                                                                      as the expected
394          */
395         private function repairFQFN ($fqfn, $uniqueID) {
396                 // Cast both strings
397                 $fqfn     = (string) $fqfn;
398                 $uniqueID = (string) $uniqueID;
399
400                 // Is there pre-cached data available?
401                 if (empty($fqfn)) {
402                         // Split the unique ID up in path and file name
403                         $pathFile = explode("@", $uniqueID);
404
405                         // Are there two elements? Index 0 is the path, 1 the file name + global extension
406                         if (!is_array($pathFile)) {
407                                 // No array found
408                                 throw new NoArrayCreatedException(array($this, "pathFile"), self::EXCEPTION_ARRAY_EXPECTED);
409                         } elseif (count($pathFile) != 2) {
410                                 // Invalid ID returned!
411                                 throw new InvalidArrayCountException(array($this, "pathFile", count($pathFile), 2), self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
412                         }
413
414                         // Create full path name
415                         $pathName = $this->getSavePath() . $pathFile[0];
416
417                         // Nothing cached, so let's create a FQFN first
418                         $fqfn = sprintf("%s/%s.%s", $pathName, $pathFile[1], $this->getFileExtension());
419                         $this->setLastFile($fqfn);
420                 }
421
422                 // Return repaired FQFN
423                 return $fqfn;
424         }
425
426         /**
427          * Private method for re-gathering the contents of a given file
428          *
429          * @param               $contents               The (maybe) already cached contents as an array
430          * @param               $fqfn           The current FQFN we shall validate
431          * @return      $contents               The repaired contents from the given file
432          */
433         private function repairContents ($contents, $fqfn) {
434                 // Is there some content and header (2 indexes) in?
435                 if ((!is_array($contents)) || (count($contents) != 2) || (!isset($contents['header'])) || (!isset($contents['data']))) {
436                         // No content found so load the file again
437                         $contents = $inputHandler->loadFileContents($fqfn);
438
439                         // And remember all data for later usage
440                         $this->setLastContents($contents);
441                 }
442
443                 // Return the repaired contents
444                 return $contents;
445         }
446
447         /**
448          * Makes sure that the database connection is alive
449          *
450          * @return      void
451          */
452         public function connectToDatabase () {
453                 // @TODO Do some checks on the database directory and files here
454         }
455
456         /**
457          * Loads data saved with saveObject from the database and re-creates a
458          * full object from it.
459          * If limitObject() was called before a new object ObjectContainer with
460          * all requested attributes will be returned instead.
461          *
462          * @return      Object  The fully re-created object or instance to
463          *                                      ObjectContainer
464          * @throws      SavePathIsEmptyException                If the given save path is an
465          *                                                                                      empty string
466          * @throws      SavePathIsNoDirectoryException  If the save path is no
467          *                                                                                      path (e.g. a file)
468          * @throws      SavePathReadProtectedException  If the save path is read-
469          *                                                                                      protected
470          * @throws      SavePathWriteProtectedException If the save path is write-
471          *                                                                                      protected
472          */
473         public function loadObject () {
474                 // Already connected? Then abort here
475                 if ($this->alreadyConnected === true) return true;
476
477                 // Get the save path
478                 $savePath = $this->getSavePath();
479
480                 if (empty($savePath)) {
481                         // Empty string
482                         throw new SavePathIsEmptyException($dbInstance, self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
483                 } elseif (!is_dir($savePath)) {
484                         // Is not a dir
485                         throw new SavePathIsNoDirectoryException($savePath, self::EXCEPTION_INVALID_PATH_NAME);
486                 } elseif (!is_readable($savePath)) {
487                         // Path not readable
488                         throw new SavePathReadProtectedException($savePath, self::EXCEPTION_READ_PROTECED_PATH);
489                 } elseif (!is_writeable($savePath)) {
490                         // Path not writeable
491                         throw new SavePathWriteProtectedException($savePath, self::EXCEPTION_WRITE_PROTECED_PATH);
492                 }
493
494                 // "Connection" established... ;-)
495                 $this->alreadyConnected = true;
496         }
497
498         /**
499          * Starts a SELECT query on the database by given return type, table name
500          * and search criteria
501          *
502          * @param       $resultType             Result type ("array", "object" and "indexed" are valid)
503          * @param       $tableName              Name of the database table
504          * @param       $criteria               Local search criteria class
505          * @return      $resultData             Result data of the query
506          * @throws      UnsupportedCriteriaException    If the criteria is unsupported
507          */
508         public function querySelect ($resultType, $tableName, Criteria $criteriaInstance) {
509                 // Is this criteria supported?
510                 if (!$criteriaInstance instanceof LocalCriteria) {
511                         // Not supported by this database layer
512                         throw new UnsupportedCriteriaException(array($this, $criteriaInstance), self::EXCEPTION_REQUIRED_INTERFACE_MISSING);
513                 }
514
515                 // A "select" query on local files is not that easy, so begin slowly with it...
516                 $this->partialStub(sprintf("type=%s,table=%s,criteria=%s", $resultType, $tableName, $criteriaInstance));
517         }
518 }
519
520 // [EOF]
521 ?>