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