2 /************************************************************************
3 * Mailer v0.2.1-FINAL Start: 10/22/2009 *
4 * =================== Last change: 10/22/2009 *
6 * -------------------------------------------------------------------- *
7 * File : cachesystem.class.php *
8 * -------------------------------------------------------------------- *
9 * Short description : CacheSystem class *
10 * -------------------------------------------------------------------- *
11 * Kurzbeschreibung : CacheSystem-Klasse *
12 * -------------------------------------------------------------------- *
15 * $Tag:: 0.2.1-FINAL $ *
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 *
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. *
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. *
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, *
36 ************************************************************************/
38 // Some security stuff...
39 if (!defined('__SECURITY')) {
46 var $statusCode = 'init';
48 // Full-qualified filename
51 // Resource to cache file
54 // Data array from cache
57 // Version data from cache
58 var $version = array();
62 var $rebuilt = array();
65 var $extension = '.cache';
66 var $status = array();
67 var $readable = array();
71 function CacheSystem () {
72 // Construct full path
73 $this->fullPath = getPath() . getCachePath();
75 // Failed is the default
76 $this->setStatusCode('failed');
78 // Check if path exists
79 if (isDirectory($this->fullPath)) {
80 // Is there a .htaccess file?
81 if (isFileReadable($this->fullPath . '.htaccess')) {
83 $this->setStatusCode('done');
85 // Stop! Set a .htaccess file first
86 $this->setStatusCode('htaccess');
91 // Checks validity of cache file and if content is given
92 function loadCacheFile ($cacheName) {
93 // Remember cache file
94 $this->name = $cacheName;
96 // Construct FQFN (full qualified file name)
97 $this->fqfn = $this->fullPath . $cacheName . $this->extension;
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();
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')));
107 //* DEBUG: */ debugOutput('cacheName='.$cacheName.',status='.intval($this->status[$cacheName]));
110 return $this->status[$cacheName];
113 // Initializes the cache file
115 // This will destory an existing cache file!
116 if ($this->getStatusCode() == 'done') {
118 $this->resetCacheReadStatus();
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 . ' !');
125 $this->writeLine('<?php');
127 // Cannot create file
128 debug_report_bug(__METHOD__, __LINE__, 'Problems with cache directory detected, getStatusCode()=' . $this->getStatusCode());
133 * Writes a line to the pointer and adds a \n (new-line) to the end
137 function writeLine ($line) {
138 // Is the pointer a valid resource?
139 if (is_resource($this->pointer)) {
141 fwrite($this->pointer, $line . "\n");
143 // Something bad happened
144 debug_report_bug(__METHOD__, __LINE__, 'Pointer type is ' . gettype($this->pointer) . ', expected is resource.');
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]);
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;
165 $GLOBALS['cache_array']['extension'][$k][$data['ext_name']] = $v;
167 if (($k == 'ext_keep') && ($v == 'Y')) {
168 $GLOBALS['cache_array']['always_active'][$data['ext_name']] = $v;
170 } elseif ($this->name == 'config') {
172 $GLOBALS['cache_array']['config'][$data['config']][$k] = $v;
173 } elseif ($this->name == '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') {
180 $GLOBALS['cache_array']['modules'][$k][$data['module']] = $v;
181 } elseif ($this->name == 'admin') {
183 if ($k == 'admin_id') {
184 $GLOBALS['cache_array']['admin'][$k][$data['login']] = $v;
186 $GLOBALS['cache_array']['admin'][$k][$data['admin_id']] = $v;
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') {
193 $GLOBALS['cache_array']['refdepths'][$k][$data['id']] = $v;
194 } elseif ($this->name == 'refsystem') {
196 $GLOBALS['cache_array']['refsystem'][$k][$data['id']] = $v;
197 } elseif ($this->name == 'revision') {
199 $GLOBALS['cache_array']['revision'][$k][0] = $v;
200 } elseif ($this->name == 'themes') {
202 if ($k == 'theme_path') {
203 $GLOBALS['cache_array']['themes'][$k][$data['id']] = $v;
205 $GLOBALS['cache_array']['themes'][$k][$data['theme_path']] = $v;
207 } elseif ($this->name == '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));
217 // Finialize the cache and close it
221 $this->removeCacheFile(true);
223 // Unsupported/unhandled cache detected
224 debug_report_bug(__METHOD__, __LINE__, 'Unsupported cache ' . $this->name . ' detected.');
227 // Write cache line to file
228 $this->writeLine($this->rewriteEntry($k, $v));
231 // Cannot create file
232 debug_report_bug(__METHOD__, __LINE__, 'Problem with cache detected, no resource! pointer[]=' . gettype($this->pointer));
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');
243 $this->writeLine('?>');
245 // Close file add destroy handler
246 fclose($this->pointer);
248 // Reset readable status
249 $this->resetCacheReadStatus();
252 if ($this->isCacheReadable()) changeMode($this->fqfn, 0666);
254 // Remove pointer and status
255 unset($this->status[$this->name]);
256 $this->pointer = false;
257 //* DEBUG: */ logDebugMessage(__METHOD__, __LINE__, 'name=' . $this->name . ' - FINALIZED!');
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];
268 // Is the cache file there?
269 if ($this->isCacheReadable()) {
271 include($this->fqfn);
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')) {
280 logDebugMessage(__METHOD__, __LINE__, 'Invalid cache data ' . $this->name . ' detected.');
281 $this->removeCacheFile();
285 // Return cache if detected
286 if (isset($this->data[$this->name])) {
287 return $this->data[$this->name];
290 logDebugMessage(__METHOD__, __LINE__, 'Possible damaged cache ' . $this->name . ' detected.');
291 $this->removeCacheFile();
295 // Cache file not found or not readable
296 debug_report_bug(__METHOD__, __LINE__, '{%message,CACHE_CANNOT_LOAD=' . $this->name . '%}');
299 $this->removeCacheFile();
302 // Always return an empty array if we have trouble or no data
306 // Destroy an existing cache file
307 function removeCacheFile ($force = false) {
309 $this->resetCacheReadStatus();
312 //* DEBUG: */ logDebugMessage(__METHOD__, __LINE__, sprintf("%s should be removed.", $this->name));
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()) {
321 logDebugMessage(__METHOD__, __LINE__, 'Not removing cache ' . $this->name . ' in output_mode=' . getScriptOutputMode());
331 // Debug-mode enabled?
332 if (isDebugModeEnabled()) {
333 // Log removal of cache
334 logDebugMessage(__METHOD__, __LINE__, 'removing cache: ' . $this->name);
337 // Remove cache file from system
338 //* DEBUG: */ debug_report_bug(__METHOD__, __LINE__, 'About to remove ' . basename($this->fqfn) . '!');
339 removeFile($this->fqfn);
342 $this->resetCacheReadStatus();
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;
352 debug_report_bug(__METHOD__, __LINE__, '{%message,CACHE_CANNOT_UNLINK=' . $this->name . '%}');
358 function removeEntry ($search, $data, $array) {
359 if ($this->status[$this->name] == 'done') {
360 // Load cache into dummy array
361 $dummy = $this->getArrayFromCache();
363 // Search for key in array
364 $key = array_search($data, $dummy[$search]);
366 // Key (hopefully) found?
367 foreach ($array as $a) {
368 // So we can remove all elements as requested
369 unset($dummy[$a][$key]);
372 // Flush array to cache file
376 $this->writeArray($dummy);
382 // Cannot write to cache!
383 debug_report_bug(__METHOD__, __LINE__, 'Problem with cache detected: Unexpected status ' . $this->status[$this->name]);
387 function writeArray ($array) {
388 if (is_resource($this->pointer)) {
389 foreach ($array as $k => $v) {
391 // Multi line(s) found
393 foreach ($v as $k2 => $v2) {
394 // Put every array element in a row...
395 $LINE .= $this->rewriteEntry($k, $v2);
399 $LINE = $this->rewriteEntry($k, $v);
403 $this->writeLine($LINE);
406 // Cannot write array!
407 debug_report_bug(__METHOD__, __LINE__, 'Problem with cache detected: pointer is not resource! pointer[]=' . gettype($this->pointer));
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();
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) {
423 // Key (hopefully) found?
424 foreach ($dummy as $a => $v) {
425 // So we can update all entries
428 $dummy[$a][$search_key] = $replace;
432 // Flush array to cache file
436 $this->writeArray($dummy);
443 // Cannot write to cache!
444 debug_report_bug(__METHOD__, __LINE__, 'Problem with cache detected: Unexpected status ' . $this->status[$this->name]);
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);
457 // Add the extension version to object (DO NOT REMOVE IT! Endless loop...)
458 $this->version[$this->name][$ext_name] = $ext_ver;
460 // Write cache line to file
461 $this->writeLine($this->rewriteEntry($ext_name, $ext_ver, 'version', true));
463 //* DEBUG: */ logDebugMessage(__METHOD__, __LINE__, 'name=' . $this->name . ',ext_name=' . $ext_name . ',ext_ver=' . $ext_ver);
465 // Cannot create file
466 debug_report_bug(__METHOD__, __LINE__, 'Problem with cache detected: pointer is not resource! pointer[]=' . gettype($this->pointer));
470 // Checks wether versions from cache and extension matches
471 function extensionVersionMatches ($ext_name) {
473 if (!isset($GLOBALS[__METHOD__][$ext_name])) {
474 // Does never match by default
475 $GLOBALS[__METHOD__][$ext_name] = false;
477 // Compare only if installed
478 if (isExtensionInstalled($ext_name)) {
479 // Get extension version
480 $ext_ver = getExtensionVersion($ext_name);
483 if (isset($this->version[$this->name][$ext_name])) {
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...');
490 // Remove the cache file
491 $this->removeCacheFile(true);
494 // Not installed, does always match
495 $GLOBALS[__METHOD__][$ext_name] = true;
498 // Cache entry found, log debug message
499 //* DEBUG: */ logDebugMessage(__METHOD__, __LINE__, 'ext_name=' . $ext_name . ', matches=' . intval($GLOBALS[__METHOD__][$ext_name]));
503 return $GLOBALS[__METHOD__][$ext_name];
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
512 // Add only for single array entry?
513 if ($single === true) {
520 // String or non-string? ;-)
521 if (is_string($value)) {
523 $line = '$this->' . $prefix . "['" . $this->name . "']['" . $key . "']" . $extender . " = '" . escapeQuotes($value) . "';";
524 } elseif (is_null($value)) {
526 $line = '$this->' . $prefix . "['" . $this->name . "']['" . $key . "']" . $extender . ' = NULL;';
527 } elseif (is_bool($value)) {
529 if ($value === true) {
531 $line = '$this->' . $prefix . "['" . $this->name . "']['" . $key . "']" . $extender . ' = true;';
534 $line = '$this->' . $prefix . "['" . $this->name . "']['" . $key . "']" . $extender . ' = false;';
536 } elseif (isset($value[0])) {
537 // These lines needs fixing
538 debug_report_bug(__METHOD__, __LINE__, 'Invalid entry with [0] found. key=' . $key);
541 $line = '$this->' . $prefix . "['" . $this->name . "']['" . $key . "']" . $extender . ' = ' . $value . ';';
548 // Getter for cache status code
549 function getStatusCode () {
550 return $this->statusCode;
553 // Setter for cache status code
554 function setStatusCode ($status) {
555 $this->statusCode = $status;
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);
567 return $this->readable[$this->name];
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.');