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