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