095187b53146b4684399f46477c887c3b718b5a6
[mailer.git] / inc / classes / cachesystem.class.php
1 <?php
2 /************************************************************************
3  * Mailer v0.2.1-FINAL                                Start: 10/22/2009 *
4  * ===================                          Last change: 10/22/2009 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : cachesystem.class.php                            *
8  * -------------------------------------------------------------------- *
9  * Short description : CacheSystem class                                *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : CacheSystem-Klasse                               *
12  * -------------------------------------------------------------------- *
13  * $Revision::                                                        $ *
14  * $Date::                                                            $ *
15  * $Tag:: 0.2.1-FINAL                                                 $ *
16  * $Author::                                                          $ *
17  * -------------------------------------------------------------------- *
18  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
19  * Copyright (c) 2009 - 2012 by Mailer Developer Team                   *
20  * For more information visit: http://mxchange.org                      *
21  *                                                                      *
22  * This program is free software; you can redistribute it and/or modify *
23  * it under the terms of the GNU General Public License as published by *
24  * the Free Software Foundation; either version 2 of the License, or    *
25  * (at your option) any later version.                                  *
26  *                                                                      *
27  * This program is distributed in the hope that it will be useful,      *
28  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
29  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
30  * GNU General Public License for more details.                         *
31  *                                                                      *
32  * You should have received a copy of the GNU General Public License    *
33  * along with this program; if not, write to the Free Software          *
34  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
35  * MA  02110-1301  USA                                                  *
36  ************************************************************************/
37
38 // Some security stuff...
39 if (!defined('__SECURITY')) {
40         die();
41 } // END - if
42
43 // Caching class
44 class CacheSystem {
45         // Status code
46         var $statusCode = 'init';
47
48         // Full-qualified filename
49         var $fqfn = '';
50
51         // Resource to cache file
52         var $pointer = FALSE;
53
54         // Data array from cache
55         var $data = array();
56
57         // Version data from cache
58         var $version = array();
59
60         // Cache name
61         var $name = '';
62         var $rebuilt = array();
63
64         // File extension
65         var $extension = '.cache';
66         var $status = array();
67         var $readable = array();
68         var $fullPath = '';
69
70         // Constructor
71         function CacheSystem () {
72                 // Construct full path
73                 $this->fullPath = getPath() . getCachePath();
74
75                 // Failed is the default
76                 $this->setStatusCode('failed');
77
78                 // Check if path exists
79                 if (isDirectory($this->fullPath)) {
80                         // Is there a .htaccess file?
81                         if (isFileReadable($this->fullPath . '.htaccess')) {
82                                 // All done!
83                                 $this->setStatusCode('done');
84                         } else {
85                                 // Stop! Set a .htaccess file first
86                                 $this->setStatusCode('htaccess');
87                         }
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 = $this->fullPath . $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: */ debugOutput('cacheName='.$cacheName.',isCacheReadable='.intval($this->isCacheReadable()).',is_writeable='.intval(is_writeable($this->fqfn)).',extensionMatches='.intval($this->extensionVersionMatches('cache')));
105                         $this->status[$cacheName] = ($this->isCacheReadable() && (is_writeable($this->fqfn)) && ($this->extensionVersionMatches('cache')));
106                 } // END - if
107                 //* DEBUG: */ debugOutput('cacheName='.$cacheName.',status='.intval($this->status[$cacheName]));
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->getStatusCode() == 'done') {
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 reportBug(__METHOD__, __LINE__, 'Cannot write to cache ' . $this->fqfn . ' !');
123
124                         // Add open PHP tag
125                         $this->writeLine('<?php');
126                 } else {
127                         // Cannot create file
128                         reportBug(__METHOD__, __LINE__, 'Problems with cache directory detected, getStatusCode()=' . $this->getStatusCode());
129                 }
130         }
131
132         /**
133          * Writes a line to the pointer and adds a \n (new-line) to the end
134          *
135          * @access private
136          */
137         function writeLine ($line) {
138                 // Is the pointer a valid resource?
139                 if (is_resource($this->pointer)) {
140                         // Write the line
141                         fwrite($this->pointer, $line . chr(10));
142                 } else {
143                         // Something bad happened
144                         reportBug(__METHOD__, __LINE__, 'Pointer type is ' . gettype($this->pointer) . ', expected is resource.');
145                 }
146         }
147
148         // Reset the read status
149         function resetCacheReadStatus () {
150                 unset($this->readable[$this->name]);
151                 unset($GLOBALS['file_readable'][$this->fqfn]);
152                 unset($this->status[$this->name]);
153         }
154
155         // Adds a data row (array) to cache file and global cache array
156         function addRow ($data) {
157                 // Is the pointe rvalid?
158                 if (is_resource($this->pointer)) {
159                         // Write every array element to cache file
160                         foreach ($data as $k => $v) {
161                                 // Write global cache array for immediate access
162                                 if ((substr($k, 0, 4) == 'ext_') && (isset($data['ext_name'])) && (isset($data['ext_id']))) {
163                                         if ($k == 'ext_name') {
164                                                 $GLOBALS['cache_array']['extension'][$k][$data['ext_id']] = $v;
165                                         } else {
166                                                 $GLOBALS['cache_array']['extension'][$k][$data['ext_name']] = $v;
167                                         }
168                                         if (($k == 'ext_keep') && ($v == 'Y')) {
169                                                 $GLOBALS['cache_array']['always_active'][$data['ext_name']] = $v;
170                                         } // END - if
171                                 } elseif ($this->name == 'config') {
172                                         // Configuration
173                                         $GLOBALS['cache_array']['config'][$data['config']][$k] = $v;
174                                 } elseif ($this->name == 'filter') {
175                                         // Filter
176                                         $GLOBALS['cache_array']['filter']['chains'][$data['filter_name']][$data['filter_function']] = $data['filter_active'];
177                                         $GLOBALS['cache_array']['filter']['counter'][$data['filter_name']][$data['filter_function']] = $data['filter_counter'];
178                                         $GLOBALS['cache_array']['filter']['loaded'][$data['filter_name']][$data['filter_function']] = TRUE;
179                                 } elseif ($this->name == 'modules') {
180                                         // Modules
181                                         $GLOBALS['cache_array']['modules'][$k][$data['module']] = $v;
182                                 } elseif ($this->name == 'admin') {
183                                         // Admin logins
184                                         if ($k == 'admin_id') {
185                                                 $GLOBALS['cache_array']['admin'][$k][$data['login']] = $v;
186                                         } else {
187                                                 $GLOBALS['cache_array']['admin'][$k][$data['admin_id']] = $v;
188                                         }
189                                 } elseif ($this->name == 'admin_acls') {
190                                         // Access control lines
191                                         array_push($GLOBALS['cache_array']['admin_acls'][$k][$data['admin_id']], $v);
192                                 } elseif ($this->name == 'refdepths') {
193                                         // Referral levels
194                                         $GLOBALS['cache_array']['refdepths'][$k][$data['id']] = $v;
195                                 } elseif ($this->name == 'refsystem') {
196                                         // Referral system
197                                         $GLOBALS['cache_array']['refsystem'][$k][$data['id']] = $v;
198                                 } elseif ($this->name == 'revision') {
199                                         // Revision data
200                                         $GLOBALS['cache_array']['revision'][$k][0] = $v;
201                                 } elseif ($this->name == 'themes') {
202                                         // Themes
203                                         if ($k == 'theme_path') {
204                                                 $GLOBALS['cache_array']['themes'][$k][$data['id']] = $v;
205                                         } else {
206                                                 $GLOBALS['cache_array']['themes'][$k][$data['theme_path']] = $v;
207                                         }
208                                 } elseif ($this->name == 'imprint') {
209                                         // Imprint
210                                         $GLOBALS['cache_array']['imprint'][$k][$data['imprint_id']] = $v;
211                                 } elseif ($this->name == 'points_data') {
212                                         // Table 'points_data'
213                                         $GLOBALS['cache_array']['points_data'][$k][$data['id']] = $v;
214                                 } elseif ($this->name == 'earning') {
215                                         // Table 'earning'
216                                         $GLOBALS['cache_array']['earning'][$k][$data['earning_id']] = $v;
217                                 } elseif ($this->name == 'payments') {
218                                         // Table 'payments'
219                                         $GLOBALS['cache_array']['payments'][$k][$data['id']] = $v;
220                                 } elseif (is_array($v)) {
221                                         // Serialize and BASE64-encode the array
222                                         $v = base64_encode(serialize($v));
223                                 } else {
224                                         // Finialize the cache and close it
225                                         $this->finalize();
226
227                                         // Remove cache
228                                         $this->removeCacheFile(TRUE);
229
230                                         // Unsupported/unhandled cache detected
231                                         reportBug(__METHOD__, __LINE__, 'Unsupported cache ' . $this->name . ' detected, data=' . print_r($data, TRUE) . ',k=' . $k . ',v=' . $v);
232                                 }
233
234                                 // Write cache line to file
235                                 $this->writeLine($this->rewriteEntry($k, $v));
236                         } // END - foreach
237                 } else {
238                         // Cannot create file
239                         reportBug(__METHOD__, __LINE__, 'Problem with cache detected, no resource! pointer[]=' . gettype($this->pointer));
240                 }
241         }
242
243         // Closes cache file with closing PHP tag
244         function finalize () {
245                 // Quit function when no pointer is set
246                 if (is_resource($this->pointer)) {
247                         // Add default depency
248                         $this->storeExtensionVersion('cache');
249
250                         // Write footer
251                         $this->writeLine('?>');
252
253                         // Close file add destroy handler
254                         fclose($this->pointer);
255
256                         // Reset readable status
257                         $this->resetCacheReadStatus();
258
259                         // Set rights
260                         if ($this->isCacheReadable()) changeMode($this->fqfn, 0666);
261
262                         // Remove pointer and status
263                         unset($this->status[$this->name]);
264                         $this->pointer = FALSE;
265                         //* DEBUG: */ logDebugMessage(__METHOD__, __LINE__, 'name=' . $this->name . ' - FINALIZED!');
266                 } // END - if
267         }
268
269         // Loads cache file and returns an array of the cached data
270         function getArrayFromCache () {
271                 // Is the cache already loaded?
272                 if (isset($this->data[$this->name])) {
273                         // Return it's content!
274                         return $this->data[$this->name];
275                 } // END - if
276
277                 // Is the cache file there?
278                 if ($this->isCacheReadable()) {
279                         // Load cache file
280                         include($this->fqfn);
281
282                         // Is there an array?
283                         if (isset($this->data[$this->name])) {
284                                 // Cache version found?
285                                 if (isset($this->version[$this->name])) {
286                                         // Check it here if cache matches ext-cache version
287                                         if (!$this->extensionVersionMatches('cache')) {
288                                                 // Invalid
289                                                 logDebugMessage(__METHOD__, __LINE__, 'Invalid cache data ' . $this->name . ' detected.');
290                                                 $this->removeCacheFile();
291                                         } // END - if
292                                 } // END - if
293
294                                 // Return cache if detected
295                                 if (isset($this->data[$this->name])) {
296                                         return $this->data[$this->name];
297                                 } else {
298                                         // Damaged!
299                                         logDebugMessage(__METHOD__, __LINE__, 'Possible damaged cache ' . $this->name . ' detected.');
300                                         $this->removeCacheFile();
301                                 }
302                         } // END - if
303                 } else {
304                         // Cache file not found or not readable
305                         reportBug(__METHOD__, __LINE__, '{%message,CACHE_CANNOT_LOAD=' . $this->name . '%}');
306
307                         // Try to remove it
308                         $this->removeCacheFile();
309                 }
310
311                 // Always return an empty array if we have trouble or no data
312                 return array();
313         }
314
315         // Destroy an existing cache file
316         function removeCacheFile ($force = FALSE) {
317                 // Reset read status
318                 $this->resetCacheReadStatus();
319
320                 // Debug message
321                 //* DEBUG: */ logDebugMessage(__METHOD__, __LINE__, sprintf("%s should be removed.", $this->name));
322
323                 // Is the cache file not yet rebuilt?
324                 if ((!isset($this->rebuilt[$this->name])) && ($this->isCacheReadable())) {
325                         // Only run in regular output mode
326                         if ((!isHtmlOutputMode()) && ($force === FALSE)) {
327                                 // Debug message if allowed
328                                 if (isDebugModeEnabled()) {
329                                         // Debug message
330                                         logDebugMessage(__METHOD__, __LINE__, 'Not removing cache ' . $this->name . ' in output_mode=' . getScriptOutputMode());
331                                 } // END - if
332
333                                 // Abort here
334                                 return;
335                         } // END - if
336
337                         // Close cache
338                         $this->finalize();
339
340                         // Debug-mode enabled?
341                         if (isDebugModeEnabled()) {
342                                 // Log removal of cache
343                                 logDebugMessage(__METHOD__, __LINE__, 'removing cache: ' . $this->name);
344                         } // END - if
345
346                         // Remove cache file from system
347                         //* DEBUG: */ reportBug(__METHOD__, __LINE__, 'About to remove ' . basename($this->fqfn) . '!');
348                         removeFile($this->fqfn);
349
350                         // Reset read status
351                         $this->resetCacheReadStatus();
352
353                         // Is the file there?
354                         if (!$this->isCacheReadable()) {
355                                 // The cache does no longer exist so kill the content
356                                 unset($this->data[$this->name]);
357                                 unset($this->version[$this->name]);
358                                 $this->rebuilt[$this->name] = TRUE;
359                         } else {
360                                 // Not removed!
361                                 reportBug(__METHOD__, __LINE__, '{%message,CACHE_CANNOT_UNLINK=' . $this->name . '%}');
362                         }
363                 } // END - if
364         }
365
366         // Unused method:
367         function removeEntry ($search, $data, $array) {
368                 if ($this->status[$this->name] == 'done') {
369                         // Load cache into dummy array
370                         $dummy = $this->getArrayFromCache();
371
372                         // Search for key in array
373                         $key = array_search($data, $dummy[$search]);
374                         if (!empty($key)) {
375                                 // Key (hopefully) found?
376                                 foreach ($array as $a) {
377                                         // So we can remove all elements as requested
378                                         unset($dummy[$a][$key]);
379                                 } // END - foreach
380
381                                 // Flush array to cache file
382                                 $this->init();
383
384                                 // Write array out
385                                 $this->writeArray($dummy);
386
387                                 // Close cache file
388                                 $this->finalize();
389                         } // END - if
390                 } else {
391                         // Cannot write to cache!
392                         reportBug(__METHOD__, __LINE__, 'Problem with cache detected: Unexpected status ' . $this->status[$this->name]);
393                 }
394         }
395
396         function writeArray ($array) {
397                 if (is_resource($this->pointer)) {
398                         foreach ($array as $k => $v) {
399                                 if (is_array($v)) {
400                                         // Multi line(s) found
401                                         $LINE = '';
402                                         foreach ($v as $k2 => $v2) {
403                                                 // Put every array element in a row...
404                                                 $LINE .= $this->rewriteEntry($k, $v2);
405                                         } // END - foreach
406                                 } else {
407                                         // Single line found
408                                         $LINE = $this->rewriteEntry($k, $v);
409                                 }
410
411                                 // Write line(s)
412                                 $this->writeLine($LINE);
413                         } // END - foreach
414                 } else {
415                         // Cannot write array!
416                         reportBug(__METHOD__, __LINE__, 'Problem with cache detected: pointer is not resource! pointer[]=' . gettype($this->pointer));
417                 }
418         }
419
420         // Unused method
421         function replaceEntry ($search, $replace, $search_key, $array) {
422                 if ($this->status[$this->name] == 'done') {
423                         // Load cache into dummy array
424                         $dummy = $this->getArrayFromCache();
425
426                         // Check if $dummy is valid (prevents some errors)
427                         if ((is_array($dummy)) && (isset($dummy[$search])) && (is_array($dummy[$search]))) {
428                                 // Search for key in array
429                                 $key_found = array_key_exists($search_key, $dummy[$search]);
430                                 if ($key_found == TRUE) {
431                                         $key = $search_key;
432                                         // Key (hopefully) found?
433                                         foreach ($dummy as $a => $v) {
434                                                 // So we can update all entries
435                                                 if ($a == $search) {
436                                                         // Update now...
437                                                         $dummy[$a][$search_key] = $replace;
438                                                 } // END - if
439                                         } // END - foreach
440
441                                         // Flush array to cache file
442                                         $this->init();
443
444                                         // Write array out
445                                         $this->writeArray($dummy);
446
447                                         // Close cache file
448                                         $this->finalize();
449                                 } // END - if
450                         } // END - if
451                 } else {
452                         // Cannot write to cache!
453                         reportBug(__METHOD__, __LINE__, 'Problem with cache detected: Unexpected status ' . $this->status[$this->name]);
454                 }
455         }
456
457         // Writes the version of given extension to the cache file
458         function storeExtensionVersion ($ext_name) {
459                 // Valid cache pointer?
460                 if (is_resource($this->pointer)) {
461                         // Write only if extension is installed
462                         if (isExtensionInstalled($ext_name)) {
463                                 // Get extension version
464                                 $ext_ver = getExtensionVersion($ext_name);
465
466                                 // Add the extension version to object (DO NOT REMOVE IT! Endless loop...)
467                                 $this->version[$this->name][$ext_name] = $ext_ver;
468
469                                 // Write cache line to file
470                                 $this->writeLine($this->rewriteEntry($ext_name, $ext_ver, 'version', TRUE));
471                         } // END - if
472                         //* DEBUG: */ logDebugMessage(__METHOD__, __LINE__, 'name=' . $this->name . ',ext_name=' . $ext_name . ',ext_ver=' . $ext_ver);
473                 } else {
474                         // Cannot create file
475                         reportBug(__METHOD__, __LINE__, 'Problem with cache detected: pointer is not resource! pointer[]=' . gettype($this->pointer));
476                 }
477         }
478
479         // Checks whether versions from cache and extension matches
480         function extensionVersionMatches ($ext_name) {
481                 // Check cache
482                 if (!isset($GLOBALS[__METHOD__][$ext_name])) {
483                         // Does never match by default
484                         $GLOBALS[__METHOD__][$ext_name] = FALSE;
485
486                         // Compare only if installed
487                         if (isExtensionInstalled($ext_name)) {
488                                 // Get extension version
489                                 $ext_ver = getExtensionVersion($ext_name);
490
491                                 // Debug messages
492                                 if (isset($this->version[$this->name][$ext_name])) {
493                                         // Does it match?
494                                         $GLOBALS[__METHOD__][$ext_name] = ((isset($this->version[$this->name][$ext_name])) && ($this->version[$this->name][$ext_name] == $ext_ver));
495                                 } elseif ($this->isCacheReadable()) {
496                                         // No cache version found
497                                         logDebugMessage(__METHOD__, __LINE__, 'Cache ' . $this->name . ' has missing version entry for extension ' . $ext_name . '! Purging cache...');
498         
499                                         // Remove the cache file
500                                         $this->removeCacheFile(TRUE);
501                                 }
502                         } else {
503                                 // Not installed, does always match
504                                 $GLOBALS[__METHOD__][$ext_name] = TRUE;
505                         }
506                 } else {
507                         // Cache entry found, log debug message
508                         //* DEBUG: */ logDebugMessage(__METHOD__, __LINE__, 'ext_name=' . $ext_name . ', matches=' . intval($GLOBALS[__METHOD__][$ext_name]));
509                 }
510
511                 // Compare both
512                 return $GLOBALS[__METHOD__][$ext_name];
513         }
514
515         // Rewrit the entry so it can be stored in cache file
516         // @TODO Add support for more types which break in last else-block
517         function rewriteEntry ($key, $value, $prefix = 'data', $single = FALSE) {
518                 // Default is not single entry
519                 $extender = '[]';
520
521                 // Add only for single array entry?
522                 if ($single === TRUE) {
523                         $extender = '';
524                 } // END - if
525
526                 // Init line
527                 $line = '';
528
529                 // String or non-string? ;-)
530                 if (is_string($value)) {
531                         // String...
532                         $line = '$this->' . $prefix . "['" . $this->name . "']['" . $key . "']" . $extender . " = '" . escapeQuotes($value) . "';";
533                 } elseif (is_null($value)) {
534                         // Null
535                         $line = '$this->' . $prefix . "['" . $this->name . "']['" . $key . "']" . $extender . ' = NULL;';
536                 } elseif (is_bool($value)) {
537                         // Boolean value
538                         if ($value === TRUE) {
539                                 // True
540                                 $line = '$this->' . $prefix . "['" . $this->name . "']['" . $key . "']" . $extender . ' = TRUE;';
541                         } else {
542                                 // False
543                                 $line = '$this->' . $prefix . "['" . $this->name . "']['" . $key . "']" . $extender . ' = FALSE;';
544                         }
545                 } elseif (isset($value[0])) {
546                         // These lines needs fixing
547                         reportBug(__METHOD__, __LINE__, 'Invalid entry with [0] found. key=' . $key);
548                 } else {
549                         // Non-string
550                         $line = '$this->' . $prefix . "['" . $this->name . "']['" . $key . "']" . $extender . ' = ' . $value . ';';
551                 }
552
553                 // Return line
554                 return $line;
555         }
556
557         // Getter for cache status code
558         function getStatusCode () {
559                 return $this->statusCode;
560         }
561
562         // Setter for cache status code
563         function setStatusCode ($status) {
564                 $this->statusCode = $status;
565         }
566
567         // Checks whether the current cache file is readable
568         function isCacheReadable () {
569                 // Array entry found?
570                 if (!isset($this->readable[$this->name])) {
571                         // Not found, so create it
572                         $this->readable[$this->name] = isFileReadable($this->fqfn);
573                 } // END - if
574
575                 // Return result
576                 return $this->readable[$this->name];
577         }
578
579         // Cloning not allowed
580         function __clone () {
581                 // Please do not clone this class
582                 reportBug(__METHOD__, __LINE__, 'Cloning of this class is not allowed.');
583         }
584 } // END - class
585
586 // [EOF]
587 ?>