Further fixes for installation phase and endless loop
[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()).'/'.(is_writeable($this->fqfn)).'/'.($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                         // Mark it as no longer readable
118                         $this->markCacheAsUnreadable();
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         // Mark the cache as unreadable
133         function markCacheAsUnreadable () {
134                 unset($this->readable[$this->name]);
135                 unset($GLOBALS['file_readable'][$this->fqfn]);
136         }
137
138         function addRow ($data) {
139                 // Is the pointe rvalid?
140                 if (is_resource($this->pointer)) {
141                         // Write every array element to cache file
142                         foreach ($data as $k => $v) {
143                                 // Write global cache array for immediate access
144                                 if ((substr($k, 0, 4) == 'ext_') && (isset($data['ext_name'])) && (isset($data['ext_id']))) {
145                                         if ($k == 'ext_name') {
146                                                 $GLOBALS['cache_array']['extension'][$k][$data['ext_id']] = $v;
147                                         } else {
148                                                 $GLOBALS['cache_array']['extension'][$k][$data['ext_name']] = $v;
149                                         }
150                                         if (($k == 'ext_keep') && ($v == 'Y')) {
151                                                 $GLOBALS['cache_array']['active_extensions'][$data['ext_name']] = $v;
152                                         } // END - if
153                                 } elseif (is_array($v)) {
154                                         // Serialize and BASE64-encode the array
155                                         $v = base64_encode(serialize($v));
156                                 }
157
158                                 // Write cache line to file
159                                 fwrite($this->pointer, $this->rewriteEntry($k, $v));
160                         }
161                 } else {
162                         // Cannot create file
163                         addFatalMessage(__METHOD__, __LINE__, "(<font color=\"#0000aa\">".__LINE__."</font>): ".getMessage('CACHE_PROBLEMS_DETECTED'));
164                 }
165         }
166
167         function finalize () {
168                 // Quit function when no pointer is set
169                 if (is_resource($this->pointer)) {
170                         // Add default depency
171                         $this->storeExtensionVersion('cache');
172
173                         // Write footer
174                         fwrite($this->pointer, "?>\n");
175
176                         // Close file add destroy handler
177                         fclose($this->pointer);
178
179                         // Set rights
180                         if ($this->isCacheReadable()) changeMode($this->fqfn, 0666);
181
182                         // Remove pointer and status
183                         unset($this->status[$this->name]);
184                         $this->pointer = false;
185                         //* DEBUG: */ outputHtml(__METHOD__."(<font color=\"#0000aa\">".__LINE__."</font>): {$this->name} - FINALIZED!<br />");
186                 } // END - if
187         }
188
189         function getArrayFromCache () {
190                 // Is the cache already loaded?
191                 if (isset($this->data[$this->name])) {
192                         // Return it's content!
193                         return $this->data[$this->name];
194                 } // END - if
195
196                 // Is the cache file there?
197                 if ($this->isCacheReadable()) {
198                         // Load cache file
199                         require($this->fqfn);
200
201                         // Is there an array?
202                         if (isset($this->data[$this->name])) {
203                                 // Cache version found?
204                                 if (isset($this->version[$this->name])) {
205                                         // Check it here if cache matches ext-cache version
206                                         if (!$this->extensionVersionMatches('cache')) {
207                                                 // Invalid
208                                                 logDebugMessage(__METHOD__, __LINE__, 'Invalid cache data ' . $this->name . ' detected.');
209                                                 $this->removeCacheFile();
210                                         } // END - if
211                                 } // END - if
212
213                                 // Return cache if detected
214                                 if (isset($this->data[$this->name])) {
215                                         return $this->data[$this->name];
216                                 } else {
217                                         // Damaged!
218                                         logDebugMessage(__METHOD__, __LINE__, 'Possible damaged cache ' . $this->name . ' detected.');
219                                         $this->removeCacheFile();
220                                 }
221                         } // END - if
222                 } else {
223                         // Cache file not found or not readable
224                         addFatalMessage(__METHOD__, __LINE__, "(<font color=\"#0000aa\">".__LINE__."</font>): ".sprintf(getMessage('CACHE_CANNOT_LOAD'), $this->fqfn));
225
226                         // Try to remove it
227                         $this->removeCacheFile();
228                 }
229         }
230
231         // Destroy an existing cache file
232         function removeCacheFile ($removeArray = false, $force = false) {
233                 // Remove cached value of readable cache
234                 $this->markCacheAsUnreadable();
235
236                 // Debug message
237                 /* DEBUG: */ logDebugMessage(__METHOD__, __LINE__, sprintf("%s should be removed.", $this->name));
238
239                 // Is the cache file not yet rebuilt?
240                 if ((!isset($this->rebuilt[$this->name])) && ($this->isCacheReadable())) {
241                         // Only run in regular output mode
242                         if ((getOutputMode() != 0) && ($force === false)) {
243                                 // Debug message if allowed
244                                 if (isDebugModeEnabled()) {
245                                         // Debug message
246                                         debug_report_bug('Not removing cache ' . $this->name . ' in output_mode=' . getOutputMode());
247                                 } // END - if
248
249                                 // Abort here
250                                 return;
251                         } // END - if
252
253                         // Close cache
254                         $this->finalize();
255
256                         // Debug-mode enabled?
257                         if (isDebugModeEnabled()) {
258                                 // Log removal of cache
259                                 logDebugMessage(__METHOD__, __LINE__, 'removing cache: ' . $this->name);
260                         } // END - if
261
262                         // Remove cache file from system
263                         removeFile($this->fqfn);
264
265                         // Shall we remove the array from memory?
266                         if ($removeArray === true) {
267                                 // Debug message if allowed
268                                 if (isDebugModeEnabled()) {
269                                         // Debug message
270                                         logDebugMessage(__METHOD__, __LINE__, 'removing array!');
271                                 } // END - if
272
273                                 // Remove it from memory
274                                 unset($GLOBALS['cache_array'][$this->name]);
275                         } // END - if
276
277                         // Is the file there?
278                         if (!$this->isCacheReadable()) {
279                                 // The cache does no longer exist so kill the content
280                                 unset($this->data[$this->name]);
281                                 unset($this->version[$this->name]);
282                                 $this->rebuilt[$this->name] = true;
283                         } else {
284                                 // Not removed!
285                                 addFatalMessage(__METHOD__, __LINE__, "(<font color=\"#0000aa\">".__LINE__."</font>): ".sprintf(getMessage('CACHE_CANNOT_UNLINK'), $this->fqfn));
286                         }
287                 } // END - if
288         }
289
290         // Unused method:
291         function removeEntry ($search, $data, $array) {
292                 if ($this->status[$this->name] == $this->statusDone) {
293                         // Load cache into dummy array
294                         $dummy = $this->getArrayFromCache();
295
296                         // Search for key in array
297                         $key = array_search($data, $dummy[$search]);
298                         if (!empty($key)) {
299                                 // Key (hopefully) found?
300                                 foreach ($array as $a) {
301                                         // So we can remove all elements as requested
302                                         unset($dummy[$a][$key]);
303                                 } // END - foreach
304
305                                 // Flush array to cache file
306                                 $this->init();
307
308                                 // Write array out
309                                 $this->writeArray($dummy);
310
311                                 // Close cache file
312                                 $this->finalize();
313                         }
314                 } else {
315                         // Cannot write to cache!
316                         addFatalMessage(__METHOD__, __LINE__, "(<font color=\"#0000aa\">".__LINE__."</font>): ".getMessage('CACHE_PROBLEMS_DETECTED'));
317                 }
318         }
319
320         function writeArray ($array) {
321                 if (is_resource($this->pointer)) {
322                         foreach ($array as $k => $v) {
323                                 if (is_array($v)) {
324                                         // Multi line(s) found
325                                         $LINE = '';
326                                         foreach($v as $k2 => $v2) {
327                                                 // Put every array element in a row...
328                                                 $LINE .= $this->rewriteEntry($k, $v2);
329                                         }
330                                 } else {
331                                         // Single line found
332                                         $LINE = $this->rewriteEntry($k, $v);
333                                 }
334
335                                 // Write line(s)
336                                 fwrite($this->pointer, $LINE);
337                         } // END - foreach
338                 } else {
339                         // Cannot write array!
340                         addFatalMessage(__METHOD__, __LINE__, "(<font color=\"#0000aa\">".__LINE__."</font>): ".getMessage('CACHE_PROBLEMS_DETECTED'));
341                 }
342         }
343
344         // Unused method
345         function replaceEntry ($search, $replace, $search_key, $array) {
346                 if ($this->status[$this->name] == $this->statusDone) {
347                         // Load cache into dummy array
348                         $dummy = $this->getArrayFromCache();
349
350                         // Check if $dummy is valid (prevents some errors)
351                         if ((is_array($dummy)) && (isset($dummy[$search])) && (is_array($dummy[$search]))) {
352                                 // Search for key in array
353                                 $key_found = array_key_exists($search_key, $dummy[$search]);
354                                 if ($key_found == true) {
355                                         $key = $search_key;
356                                         // Key (hopefully) found?
357                                         foreach ($dummy as $a => $v) {
358                                                 // So we can update all entries
359                                                 if ($a == $search) {
360                                                         // Update now...
361                                                         $dummy[$a][$search_key] = $replace;
362                                                 } // END - if
363                                         } // END - foreach
364
365                                         // Flush array to cache file
366                                         $this->init();
367
368                                         // Write array out
369                                         $this->writeArray($dummy);
370
371                                         // Close cache file
372                                         $this->finalize();
373                                 } // END - if
374                         } // END - if
375                 } else {
376                         // Cannot write to cache!
377                         addFatalMessage(__METHOD__, __LINE__, "(<font color=\"#0000aa\">".__LINE__."</font>): ".getMessage('CACHE_PROBLEMS_DETECTED'));
378                 }
379         }
380
381         // Writes the version of given extension to the cache file
382         function storeExtensionVersion ($ext_name) {
383                 // Valid cache pointer?
384                 if (is_resource($this->pointer)) {
385                         // Write only if extension is installed
386                         if (isExtensionInstalled($ext_name)) {
387                                 // Get extension version
388                                 $ext_ver = getExtensionVersion($ext_name);
389
390                                 // Write cache line to file
391                                 fwrite($this->pointer, $this->rewriteEntry($ext_name, $ext_ver, 'version', true));
392
393                                 // Add the extension version to object (DO NOT REMOVE IT! Endless loop...)
394                                 $this->version[$this->name][$ext_name] = $ext_ver;
395                         } // END - if
396                         //* DEBUG: */ outputHtml(__METHOD__."(<font color=\"#0000aa\">".__LINE__."</font>): {$this->name} - {$ext_name}={$ext_ver}<br />");
397                 } else {
398                         // Cannot create file
399                         addFatalMessage(__METHOD__, __LINE__, "(<font color=\"#0000aa\">".__LINE__."</font>): ".getMessage('CACHE_PROBLEMS_DETECTED'));
400                 }
401         }
402
403         // Checks wether versions from cache and extension matches
404         function extensionVersionMatches ($ext_name) {
405                 // Default is not matching
406                 $matches = false;
407
408                 // Compare only if installed
409                 if (isExtensionInstalled($ext_name)) {
410                         // Get extension version
411                         $ext_ver = getExtensionVersion($ext_name);
412
413                         // Debug messages
414                         if (isset($this->version[$this->name][$ext_name])) {
415                                 // Does it match?
416                                 $matches = ((isset($this->version[$this->name][$ext_name])) && ($this->version[$this->name][$ext_name] == $ext_ver));
417                         } elseif ($this->isCacheReadable()) {
418                                 // No cache version found!
419                                 logDebugMessage(__METHOD__, __LINE__, "Cache {$this->name} has missing version entry for extension {$ext_name}! Purging cache...");
420
421                                 // Remove the cache file
422                                 $this->removeCacheFile(false, true);
423                         }
424                 } else {
425                         // Not installed, does always match
426                         $matches = true;
427                 }
428
429                 // Compare both
430                 return $matches;
431         }
432
433         // Rewrit the entry so it can be stored in cache file
434         // @TODO Add support for more types which break in last else-block
435         function rewriteEntry ($key, $value, $prefix = 'data', $single = false) {
436                 // Default is not single entry
437                 $extender = '[]';
438
439                 // Add only for single array entry?
440                 if ($single === true) $extender = '';
441
442                 // Init line
443                 $line = '';
444
445                 // String or non-string? ;-)
446                 if (is_string($value)) {
447                         // String...
448                         $line = '$this->' . $prefix . "['".$this->name."']['" . $key . "']" . $extender . " = '" . smartAddSlashes($value) . "';\n";
449                 } elseif (is_null($value)) {
450                         // Null
451                         $line = '$this->' . $prefix . "['".$this->name."']['" . $key . "']" . $extender . " = null;\n";
452                 } elseif (is_bool($value)) {
453                         // Boolean value
454                         if ($value === true) {
455                                 // True
456                                 $line = '$this->' . $prefix . "['".$this->name."']['" . $key . "']" . $extender . " = true;\n";
457                         } else {
458                                 // False
459                                 $line = '$this->' . $prefix . "['".$this->name."']['" . $key . "']" . $extender . " = false;\n";
460                         }
461                 } else {
462                         // Non-string
463                         $line = '$this->' . $prefix . "['".$this->name."']['" . $key . "']" . $extender . " = " . $value . ";\n";
464                 }
465
466                 // Return line
467                 return $line;
468         }
469
470         // Getter for cache status
471         function getStatus () {
472                 return $this->ret;
473         }
474
475         // Checks wether the current cache file is readable
476         function isCacheReadable () {
477                 // Array entry found?
478                 if (!isset($this->readable[$this->name])) {
479                         // Not found, so create it
480                         $this->readable[$this->name] = isFileReadable($this->fqfn);
481                 } // END - if
482
483                 // Return result
484                 return $this->readable[$this->name];
485         }
486
487 } // END - class
488
489 // [EOF]
490 ?>