4c23235ac20812d568c89b9d06066dcd36354f5e
[mailer.git] / inc / classes / cachesystem.class.php
1 <?php
2 /************************************************************************
3  * Mailer v0.2.1-FINAL                                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                         // Is there a .htaccess file?
69                         if (isFileReadable(getConfig('CACHE_PATH') . '.htaccess')) {
70                                 // All done!
71                                 $this->ret = $this->statusDone;
72                         } else {
73                                 // Stop! Set a .htaccess file first
74                                 $this->ret = 'htaccess';
75                         }
76                 } // END - if
77         }
78
79         // Checks validity of cache file and if content is given
80         function loadCacheFile ($cacheName) {
81                 // Remember cache file
82                 $this->name = $cacheName;
83
84                 // Construct FQFN (full qualified file name)
85                 $this->fqfn = getConfig('CACHE_PATH') . $cacheName . $this->extension;
86
87                 // Check if file exists and if version matches
88                 if (!isset($this->status[$cacheName])) {
89                         // Pre-fetch cache here if found
90                         if ($this->isCacheReadable()) $this->getArrayFromCache();
91
92                         //* DEBUG: */ print($cacheName.'='.intval($this->isCacheReadable()).'/'.intval(is_writeable($this->fqfn)).'/'.intval($this->extensionVersionMatches('cache')).'<br />');
93                         $this->status[$cacheName] = ($this->isCacheReadable() && (is_writeable($this->fqfn)) && ($this->extensionVersionMatches('cache')));
94                 } // END - if
95                 //* DEBUG: */ print($cacheName.'='.intval($this->status[$cacheName]).'<br />');
96
97                 // Return status
98                 return $this->status[$cacheName];
99         }
100
101         // Initializes the cache file
102         function init () {
103                 // This will destory an existing cache file!
104                 if ($this->ret == $this->statusDone) {
105                         // Reset read status
106                         $this->resetCacheReadStatus();
107
108                         // Create file
109                         if ($this->isCacheReadable()) changeMode($this->fqfn, 0666);
110                         $this->pointer = fopen($this->fqfn, 'w') or app_die(__METHOD__, __LINE__, "Cannot write to cache ".$this->fqfn." !");
111
112                         // Add open PHP tag
113                         fwrite($this->pointer, "<?php\n");
114                 } else {
115                         // Cannot create file
116                         addFatalMessage(__METHOD__, __LINE__, "(<font color=\"#0000aa\">".__LINE__."</font>): ".getMessage('CACHE_PROBLEMS_DETECTED'));
117                 }
118         }
119
120         // Reset the read status
121         function resetCacheReadStatus () {
122                 unset($this->readable[$this->name]);
123                 unset($GLOBALS['file_readable'][$this->fqfn]);
124                 unset($this->status[$this->name]);
125         }
126
127         function addRow ($data) {
128                 // Is the pointe rvalid?
129                 if (is_resource($this->pointer)) {
130                         // Write every array element to cache file
131                         foreach ($data as $k => $v) {
132                                 // Write global cache array for immediate access
133                                 if ((substr($k, 0, 4) == 'ext_') && (isset($data['ext_name'])) && (isset($data['ext_id']))) {
134                                         if ($k == 'ext_name') {
135                                                 $GLOBALS['cache_array']['extension'][$k][$data['ext_id']] = $v;
136                                         } else {
137                                                 $GLOBALS['cache_array']['extension'][$k][$data['ext_name']] = $v;
138                                         }
139                                         if (($k == 'ext_keep') && ($v == 'Y')) {
140                                                 $GLOBALS['cache_array']['always_active'][$data['ext_name']] = $v;
141                                         } // END - if
142                                 } elseif (is_array($v)) {
143                                         // Serialize and BASE64-encode the array
144                                         $v = base64_encode(serialize($v));
145                                 } elseif ($this->name == 'config') {
146                                         // Configuration
147                                         $GLOBALS['cache_array']['config'][$data['config']][$k] = $v;
148                                 } elseif ($this->name == 'filter') {
149                                         // Filter
150                                         $GLOBALS['cache_array']['filter']['chains'][$data['filter_name']][$data['filter_function']] = $data['filter_active'];
151                                         $GLOBALS['cache_array']['filter']['counter'][$data['filter_name']][$data['filter_function']] = $data['filter_counter'];
152                                         $GLOBALS['cache_array']['filter']['loaded'][$data['filter_name']][$data['filter_function']] = true;
153                                 } elseif ($this->name == 'modules') {
154                                         // Modules
155                                         $GLOBALS['cache_array']['modules'][$k][$data['module']] = $v;
156                                 } elseif ($this->name == 'admin') {
157                                         // Modules
158                                         if ($k == 'login') {
159                                                 $GLOBALS['cache_array']['admin'][$k][$data['admin_id']] = $v;
160                                         } else {
161                                                 $GLOBALS['cache_array']['admin'][$k][$data['login']] = $v;
162                                         }
163                                 } elseif ($this->name == 'refdepths') {
164                                         // Referal levels
165                                         $GLOBALS['cache_array']['refdepths'][$k][$data['id']] = $v;
166                                 } elseif ($this->name == 'refsystem') {
167                                         // Referal system
168                                         $GLOBALS['cache_array']['refsystem'][$k][$data['id']] = $v;
169                                 } elseif ($this->name == 'revision') {
170                                         // Revision data
171                                         $GLOBALS['cache_array']['revision'][$k] = $v;
172                                 } elseif ($this->name == 'themes') {
173                                         // Themes
174                                         if ($k == 'theme_path') {
175                                                 $GLOBALS['cache_array']['themes'][$k][$data['id']] = $v;
176                                         } else {
177                                                 $GLOBALS['cache_array']['themes'][$k][$data['theme_path']] = $v;
178                                         }
179                                 } elseif ($this->name == 'imprint') {
180                                         // Imprint
181                                         $GLOBALS['cache_array']['imprint'][$k][$data['imprint_id']] = $v;
182                                 } else {
183                                         // Finialize the cache and close it
184                                         $this->finalize();
185
186                                         // Remove cache
187                                         $this->removeCacheFile(true);
188
189                                         // Unsupported cache found!
190                                         debug_report_bug('Unsupported cache ' . $this->name . ' detected.');
191                                 }
192
193                                 // Write cache line to file
194                                 fwrite($this->pointer, $this->rewriteEntry($k, $v));
195                         } // END - foreach
196                 } else {
197                         // Cannot create file
198                         addFatalMessage(__METHOD__, __LINE__, "(<font color=\"#0000aa\">".__LINE__."</font>): ".getMessage('CACHE_PROBLEMS_DETECTED'));
199                 }
200         }
201
202         function finalize () {
203                 // Quit function when no pointer is set
204                 if (is_resource($this->pointer)) {
205                         // Add default depency
206                         $this->storeExtensionVersion('cache');
207
208                         // Write footer
209                         fwrite($this->pointer, "?>\n");
210
211                         // Close file add destroy handler
212                         fclose($this->pointer);
213
214                         // Reset readable status
215                         $this->resetCacheReadStatus();
216
217                         // Set rights
218                         if ($this->isCacheReadable()) changeMode($this->fqfn, 0666);
219
220                         // Remove pointer and status
221                         unset($this->status[$this->name]);
222                         $this->pointer = false;
223                         //* DEBUG: */ outputHtml(__METHOD__."(<font color=\"#0000aa\">".__LINE__."</font>): {$this->name} - FINALIZED!<br />");
224                 } // END - if
225         }
226
227         function getArrayFromCache () {
228                 // Is the cache already loaded?
229                 if (isset($this->data[$this->name])) {
230                         // Return it's content!
231                         return $this->data[$this->name];
232                 } // END - if
233
234                 // Is the cache file there?
235                 if ($this->isCacheReadable()) {
236                         // Load cache file
237                         include($this->fqfn);
238
239                         // Is there an array?
240                         if (isset($this->data[$this->name])) {
241                                 // Cache version found?
242                                 if (isset($this->version[$this->name])) {
243                                         // Check it here if cache matches ext-cache version
244                                         if (!$this->extensionVersionMatches('cache')) {
245                                                 // Invalid
246                                                 logDebugMessage(__METHOD__, __LINE__, 'Invalid cache data ' . $this->name . ' detected.');
247                                                 $this->removeCacheFile();
248                                         } // END - if
249                                 } // END - if
250
251                                 // Return cache if detected
252                                 if (isset($this->data[$this->name])) {
253                                         return $this->data[$this->name];
254                                 } else {
255                                         // Damaged!
256                                         logDebugMessage(__METHOD__, __LINE__, 'Possible damaged cache ' . $this->name . ' detected.');
257                                         $this->removeCacheFile();
258                                 }
259                         } // END - if
260                 } else {
261                         // Cache file not found or not readable
262                         debug_report_bug($this->name);
263                         addFatalMessage(__METHOD__, __LINE__, "(<font color=\"#0000aa\">".__LINE__."</font>): ".getMaskedMessage('CACHE_CANNOT_LOAD', $this->fqfn));
264
265                         // Try to remove it
266                         $this->removeCacheFile();
267                 }
268
269                 // Always return an empty array if we have trouble or no data
270                 return array();
271         }
272
273         // Destroy an existing cache file
274         function removeCacheFile ($force = false) {
275                 // Reset read status
276                 $this->resetCacheReadStatus();
277
278                 // Debug message
279                 /* DEBUG: */ logDebugMessage(__METHOD__, __LINE__, sprintf("%s should be removed.", $this->name));
280
281                 // Is the cache file not yet rebuilt?
282                 if ((!isset($this->rebuilt[$this->name])) && ($this->isCacheReadable())) {
283                         // Only run in regular output mode
284                         if ((getOutputMode() != 0) && ($force === false)) {
285                                 // Debug message if allowed
286                                 if (isDebugModeEnabled()) {
287                                         // Debug message
288                                         logDebugMessage(__METHOD__, __LINE__, 'Not removing cache ' . $this->name . ' in output_mode=' . getOutputMode());
289                                 } // END - if
290
291                                 // Abort here
292                                 return;
293                         } // END - if
294
295                         // Close cache
296                         $this->finalize();
297
298                         // Debug-mode enabled?
299                         if (isDebugModeEnabled()) {
300                                 // Log removal of cache
301                                 logDebugMessage(__METHOD__, __LINE__, 'removing cache: ' . $this->name);
302                         } // END - if
303
304                         // Remove cache file from system
305                         removeFile($this->fqfn);
306
307                         // Reset read status
308                         $this->resetCacheReadStatus();
309
310                         // Is the file there?
311                         if (!$this->isCacheReadable()) {
312                                 // The cache does no longer exist so kill the content
313                                 unset($this->data[$this->name]);
314                                 unset($this->version[$this->name]);
315                                 $this->rebuilt[$this->name] = true;
316                         } else {
317                                 // Not removed!
318                                 addFatalMessage(__METHOD__, __LINE__, "(<font color=\"#0000aa\">".__LINE__."</font>): ".getMaskedMessage('CACHE_CANNOT_UNLINK', $this->fqfn));
319                         }
320                 } // END - if
321         }
322
323         // Unused method:
324         function removeEntry ($search, $data, $array) {
325                 if ($this->status[$this->name] == $this->statusDone) {
326                         // Load cache into dummy array
327                         $dummy = $this->getArrayFromCache();
328
329                         // Search for key in array
330                         $key = array_search($data, $dummy[$search]);
331                         if (!empty($key)) {
332                                 // Key (hopefully) found?
333                                 foreach ($array as $a) {
334                                         // So we can remove all elements as requested
335                                         unset($dummy[$a][$key]);
336                                 } // END - foreach
337
338                                 // Flush array to cache file
339                                 $this->init();
340
341                                 // Write array out
342                                 $this->writeArray($dummy);
343
344                                 // Close cache file
345                                 $this->finalize();
346                         }
347                 } else {
348                         // Cannot write to cache!
349                         addFatalMessage(__METHOD__, __LINE__, "(<font color=\"#0000aa\">".__LINE__."</font>): ".getMessage('CACHE_PROBLEMS_DETECTED'));
350                 }
351         }
352
353         function writeArray ($array) {
354                 if (is_resource($this->pointer)) {
355                         foreach ($array as $k => $v) {
356                                 if (is_array($v)) {
357                                         // Multi line(s) found
358                                         $LINE = '';
359                                         foreach($v as $k2 => $v2) {
360                                                 // Put every array element in a row...
361                                                 $LINE .= $this->rewriteEntry($k, $v2);
362                                         }
363                                 } else {
364                                         // Single line found
365                                         $LINE = $this->rewriteEntry($k, $v);
366                                 }
367
368                                 // Write line(s)
369                                 fwrite($this->pointer, $LINE);
370                         } // END - foreach
371                 } else {
372                         // Cannot write array!
373                         addFatalMessage(__METHOD__, __LINE__, "(<font color=\"#0000aa\">".__LINE__."</font>): ".getMessage('CACHE_PROBLEMS_DETECTED'));
374                 }
375         }
376
377         // Unused method
378         function replaceEntry ($search, $replace, $search_key, $array) {
379                 if ($this->status[$this->name] == $this->statusDone) {
380                         // Load cache into dummy array
381                         $dummy = $this->getArrayFromCache();
382
383                         // Check if $dummy is valid (prevents some errors)
384                         if ((is_array($dummy)) && (isset($dummy[$search])) && (is_array($dummy[$search]))) {
385                                 // Search for key in array
386                                 $key_found = array_key_exists($search_key, $dummy[$search]);
387                                 if ($key_found == true) {
388                                         $key = $search_key;
389                                         // Key (hopefully) found?
390                                         foreach ($dummy as $a => $v) {
391                                                 // So we can update all entries
392                                                 if ($a == $search) {
393                                                         // Update now...
394                                                         $dummy[$a][$search_key] = $replace;
395                                                 } // END - if
396                                         } // END - foreach
397
398                                         // Flush array to cache file
399                                         $this->init();
400
401                                         // Write array out
402                                         $this->writeArray($dummy);
403
404                                         // Close cache file
405                                         $this->finalize();
406                                 } // END - if
407                         } // END - if
408                 } else {
409                         // Cannot write to cache!
410                         addFatalMessage(__METHOD__, __LINE__, "(<font color=\"#0000aa\">".__LINE__."</font>): ".getMessage('CACHE_PROBLEMS_DETECTED'));
411                 }
412         }
413
414         // Writes the version of given extension to the cache file
415         function storeExtensionVersion ($ext_name) {
416                 // Valid cache pointer?
417                 if (is_resource($this->pointer)) {
418                         // Write only if extension is installed
419                         if (isExtensionInstalled($ext_name)) {
420                                 // Get extension version
421                                 $ext_ver = getExtensionVersion($ext_name);
422
423                                 // Add the extension version to object (DO NOT REMOVE IT! Endless loop...)
424                                 $this->version[$this->name][$ext_name] = $ext_ver;
425
426                                 // Write cache line to file
427                                 fwrite($this->pointer, $this->rewriteEntry($ext_name, $ext_ver, 'version', true));
428                         } // END - if
429                         //* DEBUG: */ outputHtml(__METHOD__."(<font color=\"#0000aa\">".__LINE__."</font>): {$this->name} - {$ext_name}={$ext_ver}<br />");
430                 } else {
431                         // Cannot create file
432                         addFatalMessage(__METHOD__, __LINE__, "(<font color=\"#0000aa\">".__LINE__."</font>): ".getMessage('CACHE_PROBLEMS_DETECTED'));
433                 }
434         }
435
436         // Checks wether versions from cache and extension matches
437         function extensionVersionMatches ($ext_name) {
438                 // Default is not matching
439                 $matches = false;
440
441                 // Compare only if installed
442                 if (isExtensionInstalled($ext_name)) {
443                         // Get extension version
444                         $ext_ver = getExtensionVersion($ext_name);
445
446                         // Debug messages
447                         if (isset($this->version[$this->name][$ext_name])) {
448                                 // Does it match?
449                                 $matches = ((isset($this->version[$this->name][$ext_name])) && ($this->version[$this->name][$ext_name] == $ext_ver));
450                         } elseif ($this->isCacheReadable()) {
451                                 // No cache version found!
452                                 logDebugMessage(__METHOD__, __LINE__, "Cache {$this->name} has missing version entry for extension {$ext_name}! Purging cache...");
453
454                                 // Remove the cache file
455                                 $this->removeCacheFile(true);
456                         }
457                 } else {
458                         // Not installed, does always match
459                         $matches = true;
460                 }
461
462                 // Compare both
463                 return $matches;
464         }
465
466         // Rewrit the entry so it can be stored in cache file
467         // @TODO Add support for more types which break in last else-block
468         function rewriteEntry ($key, $value, $prefix = 'data', $single = false) {
469                 // Default is not single entry
470                 $extender = '[]';
471
472                 // Add only for single array entry?
473                 if ($single === true) $extender = '';
474
475                 // Init line
476                 $line = '';
477
478                 // String or non-string? ;-)
479                 if (is_string($value)) {
480                         // String...
481                         $line = '$this->' . $prefix . "['".$this->name."']['" . $key . "']" . $extender . " = '" . escapeQuotes($value) . "';\n";
482                 } elseif (is_null($value)) {
483                         // Null
484                         $line = '$this->' . $prefix . "['".$this->name."']['" . $key . "']" . $extender . " = null;\n";
485                 } elseif (is_bool($value)) {
486                         // Boolean value
487                         if ($value === true) {
488                                 // True
489                                 $line = '$this->' . $prefix . "['".$this->name."']['" . $key . "']" . $extender . " = true;\n";
490                         } else {
491                                 // False
492                                 $line = '$this->' . $prefix . "['".$this->name."']['" . $key . "']" . $extender . " = false;\n";
493                         }
494                 } else {
495                         // Non-string
496                         $line = '$this->' . $prefix . "['".$this->name."']['" . $key . "']" . $extender . " = " . $value . ";\n";
497                 }
498
499                 // Return line
500                 return $line;
501         }
502
503         // Getter for cache status
504         function getStatus () {
505                 return $this->ret;
506         }
507
508         // Checks wether the current cache file is readable
509         function isCacheReadable () {
510                 // Array entry found?
511                 if (!isset($this->readable[$this->name])) {
512                         // Not found, so create it
513                         $this->readable[$this->name] = isFileReadable($this->fqfn);
514                 } // END - if
515
516                 // Return result
517                 return $this->readable[$this->name];
518         }
519
520 } // END - class
521
522 // [EOF]
523 ?>