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