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