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