Fixes for typos and cache problems
[mailer.git] / inc / classes / cachesystem.class.php
1 <?php
2 /************************************************************************
3  * MXChange v0.2.1                                    Start: 10/22/2009 *
4  * ===============                              Last change: 10/22/2009 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : cachesystem.class.php                            *
8  * -------------------------------------------------------------------- *
9  * Short description : CacheSystem class                                *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : CacheSystem-Klasse                               *
12  * -------------------------------------------------------------------- *
13  * $Revision::                                                        $ *
14  * $Date::                                                            $ *
15  * $Tag:: 0.2.1-FINAL                                                 $ *
16  * $Author::                                                          $ *
17  * Needs to be in all Files and every File needs "svn propset           *
18  * svn:keywords Date Revision" (autoprobset!) at least!!!!!!            *
19  * -------------------------------------------------------------------- *
20  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
21  * For more information visit: http://www.mxchange.org                  *
22  *                                                                      *
23  * This program is free software; you can redistribute it and/or modify *
24  * it under the terms of the GNU General Public License as published by *
25  * the Free Software Foundation; either version 2 of the License, or    *
26  * (at your option) any later version.                                  *
27  *                                                                      *
28  * This program is distributed in the hope that it will be useful,      *
29  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
30  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
31  * GNU General Public License for more details.                         *
32  *                                                                      *
33  * You should have received a copy of the GNU General Public License    *
34  * along with this program; if not, write to the Free Software          *
35  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
36  * MA  02110-1301  USA                                                  *
37  ************************************************************************/
38
39 // Some security stuff...
40 if (!defined('__SECURITY')) {
41         die();
42 } // END - if
43
44 // Caching class
45 class CacheSystem {
46         // Define variables
47         var $ret = 'init';
48         var $fqfn = '';
49         var $pointer = false;
50         var $data = array();
51         var $version = array();
52         var $name = '';
53         var $rebuilt = array();
54         var $extension = '.cache';
55         var $statusDone = 'done';
56         var $status = array();
57         var $readable = array();
58
59         // Constructor
60         function CacheSystem () {
61                 // Failed is the default
62                 $this->ret = 'failed';
63
64                 // Remeber path
65
66                 // Check if path exists
67                 if (isDirectory(getConfig('CACHE_PATH'))) {
68                         // Make FQFN for dummy file
69                         $FQFN = getConfig('CACHE_PATH') . 'dummy.tmp';
70
71                         // Check if we can create a file inside the path
72                         touch($FQFN, 'w');
73
74                         // Is the file there?
75                         if (isFileReadable($FQFN)) {
76                                 // Yes, we can do. So let's remove it
77                                 removeFile($FQFN);
78
79                                 // Is there a .htaccess file?
80                                 if (isFileReadable(getConfig('CACHE_PATH') . '.htaccess')) {
81                                         // All done!
82                                         $this->ret = $this->statusDone;
83                                 } else {
84                                         // Stop! Set a .htaccess file first
85                                         $this->ret = 'htaccess';
86                                 }
87                         } // END - if
88                 } // END - if
89         }
90
91         // Checks validity of cache file and if content is given
92         function loadCacheFile ($cacheName) {
93                 // Remember cache file
94                 $this->name = $cacheName;
95
96                 // Construct FQFN (full qualified file name)
97                 $this->fqfn = getConfig('CACHE_PATH') . $cacheName . $this->extension;
98
99                 // Check if file exists and if version matches
100                 if (!isset($this->status[$cacheName])) {
101                         // Pre-fetch cache here if found
102                         if ($this->isCacheReadable()) $this->getArrayFromCache();
103
104                         //* DEBUG: */ print($cacheName.'='.intval($this->isCacheReadable()).'/'.intval(is_writeable($this->fqfn)).'/'.intval($this->extensionVersionMatches('cache')).'<br />');
105                         $this->status[$cacheName] = ($this->isCacheReadable() && (is_writeable($this->fqfn)) && ($this->extensionVersionMatches('cache')));
106                 } // END - if
107                 //* DEBUG: */ print($cacheName.'='.intval($this->status[$cacheName]).'<br />');
108
109                 // Return status
110                 return $this->status[$cacheName];
111         }
112
113         // Initializes the cache file
114         function init () {
115                 // This will destory an existing cache file!
116                 if ($this->ret == $this->statusDone) {
117                         // Reset read status
118                         $this->resetCacheReadStatus();
119
120                         // Create file
121                         if ($this->isCacheReadable()) changeMode($this->fqfn, 0666);
122                         $this->pointer = fopen($this->fqfn, 'w') or app_die(__METHOD__, __LINE__, "Cannot write to cache ".$this->fqfn." !");
123
124                         // Add open PHP tag
125                         fwrite($this->pointer, "<?php\n");
126                 } else {
127                         // Cannot create file
128                         addFatalMessage(__METHOD__, __LINE__, "(<font color=\"#0000aa\">".__LINE__."</font>): ".getMessage('CACHE_PROBLEMS_DETECTED'));
129                 }
130         }
131
132         // Reset the read status
133         function resetCacheReadStatus () {
134                 unset($this->readable[$this->name]);
135                 unset($GLOBALS['file_readable'][$this->fqfn]);
136                 unset($this->status[$this->name]);
137         }
138
139         function addRow ($data) {
140                 // Is the pointe rvalid?
141                 if (is_resource($this->pointer)) {
142                         // Write every array element to cache file
143                         foreach ($data as $k => $v) {
144                                 // Write global cache array for immediate access
145                                 if ((substr($k, 0, 4) == 'ext_') && (isset($data['ext_name'])) && (isset($data['ext_id']))) {
146                                         if ($k == 'ext_name') {
147                                                 $GLOBALS['cache_array']['extension'][$k][$data['ext_id']] = $v;
148                                         } else {
149                                                 $GLOBALS['cache_array']['extension'][$k][$data['ext_name']] = $v;
150                                         }
151                                         if (($k == 'ext_keep') && ($v == 'Y')) {
152                                                 $GLOBALS['cache_array']['active_extensions'][$data['ext_name']] = $v;
153                                         } // END - if
154                                 } elseif (is_array($v)) {
155                                         // Serialize and BASE64-encode the array
156                                         $v = base64_encode(serialize($v));
157                                 }
158
159                                 // Write cache line to file
160                                 fwrite($this->pointer, $this->rewriteEntry($k, $v));
161                         }
162                 } else {
163                         // Cannot create file
164                         addFatalMessage(__METHOD__, __LINE__, "(<font color=\"#0000aa\">".__LINE__."</font>): ".getMessage('CACHE_PROBLEMS_DETECTED'));
165                 }
166         }
167
168         function finalize () {
169                 // Quit function when no pointer is set
170                 if (is_resource($this->pointer)) {
171                         // Add default depency
172                         $this->storeExtensionVersion('cache');
173
174                         // Write footer
175                         fwrite($this->pointer, "?>\n");
176
177                         // Close file add destroy handler
178                         fclose($this->pointer);
179
180                         // Reset readable status
181                         $this->resetCacheReadStatus();
182
183                         // Set rights
184                         if ($this->isCacheReadable()) changeMode($this->fqfn, 0666);
185
186                         // Remove pointer and status
187                         unset($this->status[$this->name]);
188                         $this->pointer = false;
189                         //* DEBUG: */ outputHtml(__METHOD__."(<font color=\"#0000aa\">".__LINE__."</font>): {$this->name} - FINALIZED!<br />");
190                 } // END - if
191         }
192
193         function getArrayFromCache () {
194                 // Is the cache already loaded?
195                 if (isset($this->data[$this->name])) {
196                         // Return it's content!
197                         return $this->data[$this->name];
198                 } // END - if
199
200                 // Is the cache file there?
201                 if ($this->isCacheReadable()) {
202                         // Load cache file
203                         require($this->fqfn);
204
205                         // Is there an array?
206                         if (isset($this->data[$this->name])) {
207                                 // Cache version found?
208                                 if (isset($this->version[$this->name])) {
209                                         // Check it here if cache matches ext-cache version
210                                         if (!$this->extensionVersionMatches('cache')) {
211                                                 // Invalid
212                                                 logDebugMessage(__METHOD__, __LINE__, 'Invalid cache data ' . $this->name . ' detected.');
213                                                 $this->removeCacheFile();
214                                         } // END - if
215                                 } // END - if
216
217                                 // Return cache if detected
218                                 if (isset($this->data[$this->name])) {
219                                         return $this->data[$this->name];
220                                 } else {
221                                         // Damaged!
222                                         logDebugMessage(__METHOD__, __LINE__, 'Possible damaged cache ' . $this->name . ' detected.');
223                                         $this->removeCacheFile();
224                                 }
225                         } // END - if
226                 } else {
227                         // Cache file not found or not readable
228                         debug_report_bug($this->name);
229                         addFatalMessage(__METHOD__, __LINE__, "(<font color=\"#0000aa\">".__LINE__."</font>): ".sprintf(getMessage('CACHE_CANNOT_LOAD'), $this->fqfn));
230
231                         // Try to remove it
232                         $this->removeCacheFile();
233                 }
234
235                 // Always return an empty array if we have trouble or no data
236                 return array();
237         }
238
239         // Destroy an existing cache file
240         function removeCacheFile ($removeArray = false, $force = false) {
241                 // Reset read status
242                 $this->resetCacheReadStatus();
243
244                 // Debug message
245                 /* DEBUG: */ logDebugMessage(__METHOD__, __LINE__, sprintf("%s should be removed.", $this->name));
246
247                 // Is the cache file not yet rebuilt?
248                 if ((!isset($this->rebuilt[$this->name])) && ($this->isCacheReadable())) {
249                         // Only run in regular output mode
250                         if ((getOutputMode() != 0) && ($force === false)) {
251                                 // Debug message if allowed
252                                 if (isDebugModeEnabled()) {
253                                         // Debug message
254                                         debug_report_bug('Not removing cache ' . $this->name . ' in output_mode=' . getOutputMode());
255                                 } // END - if
256
257                                 // Abort here
258                                 return;
259                         } // END - if
260
261                         // Close cache
262                         $this->finalize();
263
264                         // Debug-mode enabled?
265                         if (isDebugModeEnabled()) {
266                                 // Log removal of cache
267                                 logDebugMessage(__METHOD__, __LINE__, 'removing cache: ' . $this->name);
268                         } // END - if
269
270                         // Remove cache file from system
271                         removeFile($this->fqfn);
272
273                         // Reset read status
274                         $this->resetCacheReadStatus();
275
276                         // Shall we remove the array from memory?
277                         if ($removeArray === true) {
278                                 // Debug message if allowed
279                                 if (isDebugModeEnabled()) {
280                                         // Debug message
281                                         logDebugMessage(__METHOD__, __LINE__, 'removing array!');
282                                 } // END - if
283
284                                 // Remove it from memory
285                                 unset($GLOBALS['cache_array'][$this->name]);
286                         } // END - if
287
288                         // Is the file there?
289                         if (!$this->isCacheReadable()) {
290                                 // The cache does no longer exist so kill the content
291                                 unset($this->data[$this->name]);
292                                 unset($this->version[$this->name]);
293                                 $this->rebuilt[$this->name] = true;
294                         } else {
295                                 // Not removed!
296                                 addFatalMessage(__METHOD__, __LINE__, "(<font color=\"#0000aa\">".__LINE__."</font>): ".sprintf(getMessage('CACHE_CANNOT_UNLINK'), $this->fqfn));
297                         }
298                 } // END - if
299         }
300
301         // Unused method:
302         function removeEntry ($search, $data, $array) {
303                 if ($this->status[$this->name] == $this->statusDone) {
304                         // Load cache into dummy array
305                         $dummy = $this->getArrayFromCache();
306
307                         // Search for key in array
308                         $key = array_search($data, $dummy[$search]);
309                         if (!empty($key)) {
310                                 // Key (hopefully) found?
311                                 foreach ($array as $a) {
312                                         // So we can remove all elements as requested
313                                         unset($dummy[$a][$key]);
314                                 } // END - foreach
315
316                                 // Flush array to cache file
317                                 $this->init();
318
319                                 // Write array out
320                                 $this->writeArray($dummy);
321
322                                 // Close cache file
323                                 $this->finalize();
324                         }
325                 } else {
326                         // Cannot write to cache!
327                         addFatalMessage(__METHOD__, __LINE__, "(<font color=\"#0000aa\">".__LINE__."</font>): ".getMessage('CACHE_PROBLEMS_DETECTED'));
328                 }
329         }
330
331         function writeArray ($array) {
332                 if (is_resource($this->pointer)) {
333                         foreach ($array as $k => $v) {
334                                 if (is_array($v)) {
335                                         // Multi line(s) found
336                                         $LINE = '';
337                                         foreach($v as $k2 => $v2) {
338                                                 // Put every array element in a row...
339                                                 $LINE .= $this->rewriteEntry($k, $v2);
340                                         }
341                                 } else {
342                                         // Single line found
343                                         $LINE = $this->rewriteEntry($k, $v);
344                                 }
345
346                                 // Write line(s)
347                                 fwrite($this->pointer, $LINE);
348                         } // END - foreach
349                 } else {
350                         // Cannot write array!
351                         addFatalMessage(__METHOD__, __LINE__, "(<font color=\"#0000aa\">".__LINE__."</font>): ".getMessage('CACHE_PROBLEMS_DETECTED'));
352                 }
353         }
354
355         // Unused method
356         function replaceEntry ($search, $replace, $search_key, $array) {
357                 if ($this->status[$this->name] == $this->statusDone) {
358                         // Load cache into dummy array
359                         $dummy = $this->getArrayFromCache();
360
361                         // Check if $dummy is valid (prevents some errors)
362                         if ((is_array($dummy)) && (isset($dummy[$search])) && (is_array($dummy[$search]))) {
363                                 // Search for key in array
364                                 $key_found = array_key_exists($search_key, $dummy[$search]);
365                                 if ($key_found == true) {
366                                         $key = $search_key;
367                                         // Key (hopefully) found?
368                                         foreach ($dummy as $a => $v) {
369                                                 // So we can update all entries
370                                                 if ($a == $search) {
371                                                         // Update now...
372                                                         $dummy[$a][$search_key] = $replace;
373                                                 } // END - if
374                                         } // END - foreach
375
376                                         // Flush array to cache file
377                                         $this->init();
378
379                                         // Write array out
380                                         $this->writeArray($dummy);
381
382                                         // Close cache file
383                                         $this->finalize();
384                                 } // END - if
385                         } // END - if
386                 } else {
387                         // Cannot write to cache!
388                         addFatalMessage(__METHOD__, __LINE__, "(<font color=\"#0000aa\">".__LINE__."</font>): ".getMessage('CACHE_PROBLEMS_DETECTED'));
389                 }
390         }
391
392         // Writes the version of given extension to the cache file
393         function storeExtensionVersion ($ext_name) {
394                 // Valid cache pointer?
395                 if (is_resource($this->pointer)) {
396                         // Write only if extension is installed
397                         if (isExtensionInstalled($ext_name)) {
398                                 // Get extension version
399                                 $ext_ver = getExtensionVersion($ext_name);
400
401                                 // Write cache line to file
402                                 fwrite($this->pointer, $this->rewriteEntry($ext_name, $ext_ver, 'version', true));
403
404                                 // Add the extension version to object (DO NOT REMOVE IT! Endless loop...)
405                                 $this->version[$this->name][$ext_name] = $ext_ver;
406                         } // END - if
407                         //* DEBUG: */ outputHtml(__METHOD__."(<font color=\"#0000aa\">".__LINE__."</font>): {$this->name} - {$ext_name}={$ext_ver}<br />");
408                 } else {
409                         // Cannot create file
410                         addFatalMessage(__METHOD__, __LINE__, "(<font color=\"#0000aa\">".__LINE__."</font>): ".getMessage('CACHE_PROBLEMS_DETECTED'));
411                 }
412         }
413
414         // Checks wether versions from cache and extension matches
415         function extensionVersionMatches ($ext_name) {
416                 // Default is not matching
417                 $matches = false;
418
419                 // Compare only if installed
420                 if (isExtensionInstalled($ext_name)) {
421                         // Get extension version
422                         $ext_ver = getExtensionVersion($ext_name);
423
424                         // Debug messages
425                         if (isset($this->version[$this->name][$ext_name])) {
426                                 // Does it match?
427                                 $matches = ((isset($this->version[$this->name][$ext_name])) && ($this->version[$this->name][$ext_name] == $ext_ver));
428                         } elseif ($this->isCacheReadable()) {
429                                 // No cache version found!
430                                 logDebugMessage(__METHOD__, __LINE__, "Cache {$this->name} has missing version entry for extension {$ext_name}! Purging cache...");
431
432                                 // Remove the cache file
433                                 $this->removeCacheFile(false, true);
434                         }
435                 } else {
436                         // Not installed, does always match
437                         $matches = true;
438                 }
439
440                 // Compare both
441                 return $matches;
442         }
443
444         // Rewrit the entry so it can be stored in cache file
445         // @TODO Add support for more types which break in last else-block
446         function rewriteEntry ($key, $value, $prefix = 'data', $single = false) {
447                 // Default is not single entry
448                 $extender = '[]';
449
450                 // Add only for single array entry?
451                 if ($single === true) $extender = '';
452
453                 // Init line
454                 $line = '';
455
456                 // String or non-string? ;-)
457                 if (is_string($value)) {
458                         // String...
459                         $line = '$this->' . $prefix . "['".$this->name."']['" . $key . "']" . $extender . " = '" . smartAddSlashes($value) . "';\n";
460                 } elseif (is_null($value)) {
461                         // Null
462                         $line = '$this->' . $prefix . "['".$this->name."']['" . $key . "']" . $extender . " = null;\n";
463                 } elseif (is_bool($value)) {
464                         // Boolean value
465                         if ($value === true) {
466                                 // True
467                                 $line = '$this->' . $prefix . "['".$this->name."']['" . $key . "']" . $extender . " = true;\n";
468                         } else {
469                                 // False
470                                 $line = '$this->' . $prefix . "['".$this->name."']['" . $key . "']" . $extender . " = false;\n";
471                         }
472                 } else {
473                         // Non-string
474                         $line = '$this->' . $prefix . "['".$this->name."']['" . $key . "']" . $extender . " = " . $value . ";\n";
475                 }
476
477                 // Return line
478                 return $line;
479         }
480
481         // Getter for cache status
482         function getStatus () {
483                 return $this->ret;
484         }
485
486         // Checks wether the current cache file is readable
487         function isCacheReadable () {
488                 // Array entry found?
489                 if (!isset($this->readable[$this->name])) {
490                         // Not found, so create it
491                         $this->readable[$this->name] = isFileReadable($this->fqfn);
492                 } // END - if
493
494                 // Return result
495                 return $this->readable[$this->name];
496         }
497
498 } // END - class
499
500 // [EOF]
501 ?>