]> git.mxchange.org Git - mailer.git/blob - inc/classes/cachesystem.class.php
Added cache loader for table 'points_data'
[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 - 2011 by Mailer Developer Team                   *
20  * For more information visit: http://www.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 debug_report_bug(__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                         debug_report_bug(__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 . "\n");
142                 } else {
143                         // Something bad happened
144                         debug_report_bug(__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         function addRow ($data) {
156                 // Is the pointe rvalid?
157                 if (is_resource($this->pointer)) {
158                         // Write every array element to cache file
159                         foreach ($data as $k => $v) {
160                                 // Write global cache array for immediate access
161                                 if ((substr($k, 0, 4) == 'ext_') && (isset($data['ext_name'])) && (isset($data['ext_id']))) {
162                                         if ($k == 'ext_name') {
163                                                 $GLOBALS['cache_array']['extension'][$k][$data['ext_id']] = $v;
164                                         } else {
165                                                 $GLOBALS['cache_array']['extension'][$k][$data['ext_name']] = $v;
166                                         }
167                                         if (($k == 'ext_keep') && ($v == 'Y')) {
168                                                 $GLOBALS['cache_array']['always_active'][$data['ext_name']] = $v;
169                                         } // END - if
170                                 } elseif ($this->name == 'config') {
171                                         // Configuration
172                                         $GLOBALS['cache_array']['config'][$data['config']][$k] = $v;
173                                 } elseif ($this->name == 'filter') {
174                                         // Filter
175                                         $GLOBALS['cache_array']['filter']['chains'][$data['filter_name']][$data['filter_function']] = $data['filter_active'];
176                                         $GLOBALS['cache_array']['filter']['counter'][$data['filter_name']][$data['filter_function']] = $data['filter_counter'];
177                                         $GLOBALS['cache_array']['filter']['loaded'][$data['filter_name']][$data['filter_function']] = true;
178                                 } elseif ($this->name == 'modules') {
179                                         // Modules
180                                         $GLOBALS['cache_array']['modules'][$k][$data['module']] = $v;
181                                 } elseif ($this->name == 'admin') {
182                                         // Admin logins
183                                         if ($k == 'admin_id') {
184                                                 $GLOBALS['cache_array']['admin'][$k][$data['login']] = $v;
185                                         } else {
186                                                 $GLOBALS['cache_array']['admin'][$k][$data['admin_id']] = $v;
187                                         }
188                                 } elseif ($this->name == 'admin_acls') {
189                                         // Access control lines
190                                         $GLOBALS['cache_array']['admin_acls'][$k][$data['admin_id']][] = $v;
191                                 } elseif ($this->name == 'refdepths') {
192                                         // Referal levels
193                                         $GLOBALS['cache_array']['refdepths'][$k][$data['id']] = $v;
194                                 } elseif ($this->name == 'refsystem') {
195                                         // Referal system
196                                         $GLOBALS['cache_array']['refsystem'][$k][$data['id']] = $v;
197                                 } elseif ($this->name == 'revision') {
198                                         // Revision data
199                                         $GLOBALS['cache_array']['revision'][$k][0] = $v;
200                                 } elseif ($this->name == 'themes') {
201                                         // Themes
202                                         if ($k == 'theme_path') {
203                                                 $GLOBALS['cache_array']['themes'][$k][$data['id']] = $v;
204                                         } else {
205                                                 $GLOBALS['cache_array']['themes'][$k][$data['theme_path']] = $v;
206                                         }
207                                 } elseif ($this->name == 'imprint') {
208                                         // Imprint
209                                         $GLOBALS['cache_array']['imprint'][$k][$data['imprint_id']] = $v;
210                                 } elseif ($this->name == 'points_data') {
211                                         // Table 'points_data'
212                                         $GLOBALS['cache_array']['points_data'][$k][$data['id']] = $v;
213                                 } elseif (is_array($v)) {
214                                         // Serialize and BASE64-encode the array
215                                         $v = base64_encode(serialize($v));
216                                 } else {
217                                         // Finialize the cache and close it
218                                         $this->finalize();
219
220                                         // Remove cache
221                                         $this->removeCacheFile(true);
222
223                                         // Unsupported/unhandled cache detected
224                                         debug_report_bug(__METHOD__, __LINE__, 'Unsupported cache ' . $this->name . ' detected.');
225                                 }
226
227                                 // Write cache line to file
228                                 $this->writeLine($this->rewriteEntry($k, $v));
229                         } // END - foreach
230                 } else {
231                         // Cannot create file
232                         debug_report_bug(__METHOD__, __LINE__, 'Problem with cache detected, no resource! pointer[]=' . gettype($this->pointer));
233                 }
234         }
235
236         function finalize () {
237                 // Quit function when no pointer is set
238                 if (is_resource($this->pointer)) {
239                         // Add default depency
240                         $this->storeExtensionVersion('cache');
241
242                         // Write footer
243                         $this->writeLine('?>');
244
245                         // Close file add destroy handler
246                         fclose($this->pointer);
247
248                         // Reset readable status
249                         $this->resetCacheReadStatus();
250
251                         // Set rights
252                         if ($this->isCacheReadable()) changeMode($this->fqfn, 0666);
253
254                         // Remove pointer and status
255                         unset($this->status[$this->name]);
256                         $this->pointer = false;
257                         //* DEBUG: */ logDebugMessage(__METHOD__, __LINE__, 'name=' . $this->name . ' - FINALIZED!');
258                 } // END - if
259         }
260
261         function getArrayFromCache () {
262                 // Is the cache already loaded?
263                 if (isset($this->data[$this->name])) {
264                         // Return it's content!
265                         return $this->data[$this->name];
266                 } // END - if
267
268                 // Is the cache file there?
269                 if ($this->isCacheReadable()) {
270                         // Load cache file
271                         include($this->fqfn);
272
273                         // Is there an array?
274                         if (isset($this->data[$this->name])) {
275                                 // Cache version found?
276                                 if (isset($this->version[$this->name])) {
277                                         // Check it here if cache matches ext-cache version
278                                         if (!$this->extensionVersionMatches('cache')) {
279                                                 // Invalid
280                                                 logDebugMessage(__METHOD__, __LINE__, 'Invalid cache data ' . $this->name . ' detected.');
281                                                 $this->removeCacheFile();
282                                         } // END - if
283                                 } // END - if
284
285                                 // Return cache if detected
286                                 if (isset($this->data[$this->name])) {
287                                         return $this->data[$this->name];
288                                 } else {
289                                         // Damaged!
290                                         logDebugMessage(__METHOD__, __LINE__, 'Possible damaged cache ' . $this->name . ' detected.');
291                                         $this->removeCacheFile();
292                                 }
293                         } // END - if
294                 } else {
295                         // Cache file not found or not readable
296                         debug_report_bug(__METHOD__, __LINE__, '{%message,CACHE_CANNOT_LOAD=' . $this->name . '%}');
297
298                         // Try to remove it
299                         $this->removeCacheFile();
300                 }
301
302                 // Always return an empty array if we have trouble or no data
303                 return array();
304         }
305
306         // Destroy an existing cache file
307         function removeCacheFile ($force = false) {
308                 // Reset read status
309                 $this->resetCacheReadStatus();
310
311                 // Debug message
312                 //* DEBUG: */ logDebugMessage(__METHOD__, __LINE__, sprintf("%s should be removed.", $this->name));
313
314                 // Is the cache file not yet rebuilt?
315                 if ((!isset($this->rebuilt[$this->name])) && ($this->isCacheReadable())) {
316                         // Only run in regular output mode
317                         if ((!isHtmlOutputMode()) && ($force === false)) {
318                                 // Debug message if allowed
319                                 if (isDebugModeEnabled()) {
320                                         // Debug message
321                                         logDebugMessage(__METHOD__, __LINE__, 'Not removing cache ' . $this->name . ' in output_mode=' . getScriptOutputMode());
322                                 } // END - if
323
324                                 // Abort here
325                                 return;
326                         } // END - if
327
328                         // Close cache
329                         $this->finalize();
330
331                         // Debug-mode enabled?
332                         if (isDebugModeEnabled()) {
333                                 // Log removal of cache
334                                 logDebugMessage(__METHOD__, __LINE__, 'removing cache: ' . $this->name);
335                         } // END - if
336
337                         // Remove cache file from system
338                         //* DEBUG: */ debug_report_bug(__METHOD__, __LINE__, 'About to remove ' . basename($this->fqfn) . '!');
339                         removeFile($this->fqfn);
340
341                         // Reset read status
342                         $this->resetCacheReadStatus();
343
344                         // Is the file there?
345                         if (!$this->isCacheReadable()) {
346                                 // The cache does no longer exist so kill the content
347                                 unset($this->data[$this->name]);
348                                 unset($this->version[$this->name]);
349                                 $this->rebuilt[$this->name] = true;
350                         } else {
351                                 // Not removed!
352                                 debug_report_bug(__METHOD__, __LINE__, '{%message,CACHE_CANNOT_UNLINK=' . $this->name . '%}');
353                         }
354                 } // END - if
355         }
356
357         // Unused method:
358         function removeEntry ($search, $data, $array) {
359                 if ($this->status[$this->name] == 'done') {
360                         // Load cache into dummy array
361                         $dummy = $this->getArrayFromCache();
362
363                         // Search for key in array
364                         $key = array_search($data, $dummy[$search]);
365                         if (!empty($key)) {
366                                 // Key (hopefully) found?
367                                 foreach ($array as $a) {
368                                         // So we can remove all elements as requested
369                                         unset($dummy[$a][$key]);
370                                 } // END - foreach
371
372                                 // Flush array to cache file
373                                 $this->init();
374
375                                 // Write array out
376                                 $this->writeArray($dummy);
377
378                                 // Close cache file
379                                 $this->finalize();
380                         } // END - if
381                 } else {
382                         // Cannot write to cache!
383                         debug_report_bug(__METHOD__, __LINE__, 'Problem with cache detected: Unexpected status ' . $this->status[$this->name]);
384                 }
385         }
386
387         function writeArray ($array) {
388                 if (is_resource($this->pointer)) {
389                         foreach ($array as $k => $v) {
390                                 if (is_array($v)) {
391                                         // Multi line(s) found
392                                         $LINE = '';
393                                         foreach ($v as $k2 => $v2) {
394                                                 // Put every array element in a row...
395                                                 $LINE .= $this->rewriteEntry($k, $v2);
396                                         } // END - foreach
397                                 } else {
398                                         // Single line found
399                                         $LINE = $this->rewriteEntry($k, $v);
400                                 }
401
402                                 // Write line(s)
403                                 $this->writeLine($LINE);
404                         } // END - foreach
405                 } else {
406                         // Cannot write array!
407                         debug_report_bug(__METHOD__, __LINE__, 'Problem with cache detected: pointer is not resource! pointer[]=' . gettype($this->pointer));
408                 }
409         }
410
411         // Unused method
412         function replaceEntry ($search, $replace, $search_key, $array) {
413                 if ($this->status[$this->name] == 'done') {
414                         // Load cache into dummy array
415                         $dummy = $this->getArrayFromCache();
416
417                         // Check if $dummy is valid (prevents some errors)
418                         if ((is_array($dummy)) && (isset($dummy[$search])) && (is_array($dummy[$search]))) {
419                                 // Search for key in array
420                                 $key_found = array_key_exists($search_key, $dummy[$search]);
421                                 if ($key_found == true) {
422                                         $key = $search_key;
423                                         // Key (hopefully) found?
424                                         foreach ($dummy as $a => $v) {
425                                                 // So we can update all entries
426                                                 if ($a == $search) {
427                                                         // Update now...
428                                                         $dummy[$a][$search_key] = $replace;
429                                                 } // END - if
430                                         } // END - foreach
431
432                                         // Flush array to cache file
433                                         $this->init();
434
435                                         // Write array out
436                                         $this->writeArray($dummy);
437
438                                         // Close cache file
439                                         $this->finalize();
440                                 } // END - if
441                         } // END - if
442                 } else {
443                         // Cannot write to cache!
444                         debug_report_bug(__METHOD__, __LINE__, 'Problem with cache detected: Unexpected status ' . $this->status[$this->name]);
445                 }
446         }
447
448         // Writes the version of given extension to the cache file
449         function storeExtensionVersion ($ext_name) {
450                 // Valid cache pointer?
451                 if (is_resource($this->pointer)) {
452                         // Write only if extension is installed
453                         if (isExtensionInstalled($ext_name)) {
454                                 // Get extension version
455                                 $ext_ver = getExtensionVersion($ext_name);
456
457                                 // Add the extension version to object (DO NOT REMOVE IT! Endless loop...)
458                                 $this->version[$this->name][$ext_name] = $ext_ver;
459
460                                 // Write cache line to file
461                                 $this->writeLine($this->rewriteEntry($ext_name, $ext_ver, 'version', true));
462                         } // END - if
463                         //* DEBUG: */ logDebugMessage(__METHOD__, __LINE__, 'name=' . $this->name . ',ext_name=' . $ext_name . ',ext_ver=' . $ext_ver);
464                 } else {
465                         // Cannot create file
466                         debug_report_bug(__METHOD__, __LINE__, 'Problem with cache detected: pointer is not resource! pointer[]=' . gettype($this->pointer));
467                 }
468         }
469
470         // Checks wether versions from cache and extension matches
471         function extensionVersionMatches ($ext_name) {
472                 // Check cache
473                 if (!isset($GLOBALS[__METHOD__][$ext_name])) {
474                         // Does never match by default
475                         $GLOBALS[__METHOD__][$ext_name] = false;
476
477                         // Compare only if installed
478                         if (isExtensionInstalled($ext_name)) {
479                                 // Get extension version
480                                 $ext_ver = getExtensionVersion($ext_name);
481
482                                 // Debug messages
483                                 if (isset($this->version[$this->name][$ext_name])) {
484                                         // Does it match?
485                                         $GLOBALS[__METHOD__][$ext_name] = ((isset($this->version[$this->name][$ext_name])) && ($this->version[$this->name][$ext_name] == $ext_ver));
486                                 } elseif ($this->isCacheReadable()) {
487                                         // No cache version found
488                                         logDebugMessage(__METHOD__, __LINE__, 'Cache ' . $this->name . ' has missing version entry for extension ' . $ext_name . '! Purging cache...');
489         
490                                         // Remove the cache file
491                                         $this->removeCacheFile(true);
492                                 }
493                         } else {
494                                 // Not installed, does always match
495                                 $GLOBALS[__METHOD__][$ext_name] = true;
496                         }
497                 } else {
498                         // Cache entry found, log debug message
499                         //* DEBUG: */ logDebugMessage(__METHOD__, __LINE__, 'ext_name=' . $ext_name . ', matches=' . intval($GLOBALS[__METHOD__][$ext_name]));
500                 }
501
502                 // Compare both
503                 return $GLOBALS[__METHOD__][$ext_name];
504         }
505
506         // Rewrit the entry so it can be stored in cache file
507         // @TODO Add support for more types which break in last else-block
508         function rewriteEntry ($key, $value, $prefix = 'data', $single = false) {
509                 // Default is not single entry
510                 $extender = '[]';
511
512                 // Add only for single array entry?
513                 if ($single === true) {
514                         $extender = '';
515                 } // END - if
516
517                 // Init line
518                 $line = '';
519
520                 // String or non-string? ;-)
521                 if (is_string($value)) {
522                         // String...
523                         $line = '$this->' . $prefix . "['" . $this->name . "']['" . $key . "']" . $extender . " = '" . escapeQuotes($value) . "';";
524                 } elseif (is_null($value)) {
525                         // Null
526                         $line = '$this->' . $prefix . "['" . $this->name . "']['" . $key . "']" . $extender . ' = NULL;';
527                 } elseif (is_bool($value)) {
528                         // Boolean value
529                         if ($value === true) {
530                                 // True
531                                 $line = '$this->' . $prefix . "['" . $this->name . "']['" . $key . "']" . $extender . ' = true;';
532                         } else {
533                                 // False
534                                 $line = '$this->' . $prefix . "['" . $this->name . "']['" . $key . "']" . $extender . ' = false;';
535                         }
536                 } elseif (isset($value[0])) {
537                         // These lines needs fixing
538                         debug_report_bug(__METHOD__, __LINE__, 'Invalid entry with [0] found. key=' . $key);
539                 } else {
540                         // Non-string
541                         $line = '$this->' . $prefix . "['" . $this->name . "']['" . $key . "']" . $extender . ' = ' . $value . ';';
542                 }
543
544                 // Return line
545                 return $line;
546         }
547
548         // Getter for cache status code
549         function getStatusCode () {
550                 return $this->statusCode;
551         }
552
553         // Setter for cache status code
554         function setStatusCode ($status) {
555                 $this->statusCode = $status;
556         }
557
558         // Checks wether the current cache file is readable
559         function isCacheReadable () {
560                 // Array entry found?
561                 if (!isset($this->readable[$this->name])) {
562                         // Not found, so create it
563                         $this->readable[$this->name] = isFileReadable($this->fqfn);
564                 } // END - if
565
566                 // Return result
567                 return $this->readable[$this->name];
568         }
569
570         // Cloning not allowed
571         function __clone () {
572                 // Please do not clone this class
573                 debug_report_bug(__METHOD__, __LINE__, 'Cloning of this class is not allowed.');
574         }
575 } // END - class
576
577 // [EOF]
578 ?>