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, 2010 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();
70 function CacheSystem () {
71 // Failed is the default
72 $this->setStatusCode('failed');
76 // Check if path exists
77 if (isDirectory(getCachePath())) {
78 // Is there a .htaccess file?
79 if (isFileReadable(getCachePath() . '.htaccess')) {
81 $this->setStatusCode('done');
83 // Stop! Set a .htaccess file first
84 $this->setStatusCode('htaccess');
89 // Checks validity of cache file and if content is given
90 function loadCacheFile ($cacheName) {
91 // Remember cache file
92 $this->name = $cacheName;
94 // Construct FQFN (full qualified file name)
95 $this->fqfn = getCachePath() . $cacheName . $this->extension;
97 // Check if file exists and if version matches
98 if (!isset($this->status[$cacheName])) {
99 // Pre-fetch cache here if found
100 if ($this->isCacheReadable()) $this->getArrayFromCache();
102 //* DEBUG: */ debugOutput('cacheName='.$cacheName.',isCacheReadable='.intval($this->isCacheReadable()).',is_writeable='.intval(is_writeable($this->fqfn)).',extensionMatches='.intval($this->extensionVersionMatches('cache')));
103 $this->status[$cacheName] = ($this->isCacheReadable() && (is_writeable($this->fqfn)) && ($this->extensionVersionMatches('cache')));
105 //* DEBUG: */ debugOutput('cacheName='.$cacheName.',status='.intval($this->status[$cacheName]));
108 return $this->status[$cacheName];
111 // Initializes the cache file
113 // This will destory an existing cache file!
114 if ($this->getStatusCode() == 'done') {
116 $this->resetCacheReadStatus();
119 if ($this->isCacheReadable()) changeMode($this->fqfn, 0666);
120 $this->pointer = fopen($this->fqfn, 'w') or debug_report_bug(__METHOD__, __LINE__, 'Cannot write to cache ' . $this->fqfn . ' !');
123 $this->writeLine('<?php');
125 // Cannot create file
126 addFatalMessage(__METHOD__, __LINE__, '(<font color="#0000aa">' . __LINE__ . '</font>): {--CACHE_PROBLEMS_DETECTED');
131 * Writes a line to the pointer and adds a \n (new-line) to the end
135 function writeLine ($line) {
136 // Is the pointer a valid resource?
137 if (is_resource($this->pointer)) {
139 fwrite($this->pointer, $line . "\n");
141 // Something bad happened
142 debug_report_bug(__METHOD__, __LINE__, 'Pointer type is ' . gettype($this->pointer) . ', expected is resource.');
146 // Reset the read status
147 function resetCacheReadStatus () {
148 unset($this->readable[$this->name]);
149 unset($GLOBALS['file_readable'][$this->fqfn]);
150 unset($this->status[$this->name]);
153 function addRow ($data) {
154 // Is the pointe rvalid?
155 if (is_resource($this->pointer)) {
156 // Write every array element to cache file
157 foreach ($data as $k => $v) {
158 // Write global cache array for immediate access
159 if ((substr($k, 0, 4) == 'ext_') && (isset($data['ext_name'])) && (isset($data['ext_id']))) {
160 if ($k == 'ext_name') {
161 $GLOBALS['cache_array']['extension'][$k][$data['ext_id']] = $v;
163 $GLOBALS['cache_array']['extension'][$k][$data['ext_name']] = $v;
165 if (($k == 'ext_keep') && ($v == 'Y')) {
166 $GLOBALS['cache_array']['always_active'][$data['ext_name']] = $v;
168 } elseif ($this->name == 'config') {
170 $GLOBALS['cache_array']['config'][$data['config']][$k] = $v;
171 } elseif ($this->name == 'filter') {
173 $GLOBALS['cache_array']['filter']['chains'][$data['filter_name']][$data['filter_function']] = $data['filter_active'];
174 $GLOBALS['cache_array']['filter']['counter'][$data['filter_name']][$data['filter_function']] = $data['filter_counter'];
175 $GLOBALS['cache_array']['filter']['loaded'][$data['filter_name']][$data['filter_function']] = true;
176 } elseif ($this->name == 'modules') {
178 $GLOBALS['cache_array']['modules'][$k][$data['module']] = $v;
179 } elseif ($this->name == 'admin') {
181 if ($k == 'admin_id') {
182 $GLOBALS['cache_array']['admin'][$k][$data['login']] = $v;
184 $GLOBALS['cache_array']['admin'][$k][$data['admin_id']] = $v;
186 } elseif ($this->name == 'refdepths') {
188 $GLOBALS['cache_array']['refdepths'][$k][$data['id']] = $v;
189 } elseif ($this->name == 'refsystem') {
191 $GLOBALS['cache_array']['refsystem'][$k][$data['id']] = $v;
192 } elseif ($this->name == 'revision') {
194 $GLOBALS['cache_array']['revision'][$k][0] = $v;
195 } elseif ($this->name == 'themes') {
197 if ($k == 'theme_path') {
198 $GLOBALS['cache_array']['themes'][$k][$data['id']] = $v;
200 $GLOBALS['cache_array']['themes'][$k][$data['theme_path']] = $v;
202 } elseif ($this->name == 'imprint') {
204 $GLOBALS['cache_array']['imprint'][$k][$data['imprint_id']] = $v;
205 } elseif (is_array($v)) {
206 // Serialize and BASE64-encode the array
207 $v = base64_encode(serialize($v));
209 // Finialize the cache and close it
213 $this->removeCacheFile(true);
215 // Unsupported cache found!
216 debug_report_bug(__METHOD__, __LINE__, 'Unsupported cache ' . $this->name . ' detected.');
219 // Write cache line to file
220 $this->writeLine($this->rewriteEntry($k, $v));
223 // Cannot create file
224 addFatalMessage(__METHOD__, __LINE__, '(<font color="#0000aa">' . __LINE__ . '</font>): {--CACHE_PROBLEMS_DETECTED');
228 function finalize () {
229 // Quit function when no pointer is set
230 if (is_resource($this->pointer)) {
231 // Add default depency
232 $this->storeExtensionVersion('cache');
235 $this->writeLine('?>');
237 // Close file add destroy handler
238 fclose($this->pointer);
240 // Reset readable status
241 $this->resetCacheReadStatus();
244 if ($this->isCacheReadable()) changeMode($this->fqfn, 0666);
246 // Remove pointer and status
247 unset($this->status[$this->name]);
248 $this->pointer = false;
249 //* DEBUG: */ debugOutput(__METHOD__ . '(<font color="#0000aa">' . __LINE__.'</font>): '.$this->name.' - FINALIZED!');
253 function getArrayFromCache () {
254 // Is the cache already loaded?
255 if (isset($this->data[$this->name])) {
256 // Return it's content!
257 return $this->data[$this->name];
260 // Is the cache file there?
261 if ($this->isCacheReadable()) {
263 include($this->fqfn);
265 // Is there an array?
266 if (isset($this->data[$this->name])) {
267 // Cache version found?
268 if (isset($this->version[$this->name])) {
269 // Check it here if cache matches ext-cache version
270 if (!$this->extensionVersionMatches('cache')) {
272 logDebugMessage(__METHOD__, __LINE__, 'Invalid cache data ' . $this->name . ' detected.');
273 $this->removeCacheFile();
277 // Return cache if detected
278 if (isset($this->data[$this->name])) {
279 return $this->data[$this->name];
282 logDebugMessage(__METHOD__, __LINE__, 'Possible damaged cache ' . $this->name . ' detected.');
283 $this->removeCacheFile();
287 // Cache file not found or not readable
288 debug_report_bug(__METHOD__, __LINE__, $this->name);
289 addFatalMessage(__METHOD__, __LINE__, '(<font color="#0000aa">' . __LINE__ . '</font>): ' . getMaskedMessage('CACHE_CANNOT_LOAD', $this->fqfn));
292 $this->removeCacheFile();
295 // Always return an empty array if we have trouble or no data
299 // Destroy an existing cache file
300 function removeCacheFile ($force = false) {
302 $this->resetCacheReadStatus();
305 //* DEBUG: */ logDebugMessage(__METHOD__, __LINE__, sprintf("%s should be removed.", $this->name));
307 // Is the cache file not yet rebuilt?
308 if ((!isset($this->rebuilt[$this->name])) && ($this->isCacheReadable())) {
309 // Only run in regular output mode
310 if ((!isHtmlOutputMode()) && ($force === false)) {
311 // Debug message if allowed
312 if (isDebugModeEnabled()) {
314 logDebugMessage(__METHOD__, __LINE__, 'Not removing cache ' . $this->name . ' in output_mode=' . getScriptOutputMode());
324 // Debug-mode enabled?
325 if (isDebugModeEnabled()) {
326 // Log removal of cache
327 logDebugMessage(__METHOD__, __LINE__, 'removing cache: ' . $this->name);
330 // Remove cache file from system
331 removeFile($this->fqfn);
334 $this->resetCacheReadStatus();
336 // Is the file there?
337 if (!$this->isCacheReadable()) {
338 // The cache does no longer exist so kill the content
339 unset($this->data[$this->name]);
340 unset($this->version[$this->name]);
341 $this->rebuilt[$this->name] = true;
344 addFatalMessage(__METHOD__, __LINE__, '(<font color="#0000aa">' . __LINE__ . '</font>): ' . getMaskedMessage('CACHE_CANNOT_UNLINK', $this->fqfn));
350 function removeEntry ($search, $data, $array) {
351 if ($this->status[$this->name] == 'done') {
352 // Load cache into dummy array
353 $dummy = $this->getArrayFromCache();
355 // Search for key in array
356 $key = array_search($data, $dummy[$search]);
358 // Key (hopefully) found?
359 foreach ($array as $a) {
360 // So we can remove all elements as requested
361 unset($dummy[$a][$key]);
364 // Flush array to cache file
368 $this->writeArray($dummy);
374 // Cannot write to cache!
375 addFatalMessage(__METHOD__, __LINE__, '(<font color="#0000aa">' . __LINE__ . '</font>): {--CACHE_PROBLEMS_DETECTED');
379 function writeArray ($array) {
380 if (is_resource($this->pointer)) {
381 foreach ($array as $k => $v) {
383 // Multi line(s) found
385 foreach($v as $k2 => $v2) {
386 // Put every array element in a row...
387 $LINE .= $this->rewriteEntry($k, $v2);
391 $LINE = $this->rewriteEntry($k, $v);
395 $this->writeLine($LINE);
398 // Cannot write array!
399 addFatalMessage(__METHOD__, __LINE__, '(<font color="#0000aa">' . __LINE__ . '</font>): {--CACHE_PROBLEMS_DETECTED');
404 function replaceEntry ($search, $replace, $search_key, $array) {
405 if ($this->status[$this->name] == 'done') {
406 // Load cache into dummy array
407 $dummy = $this->getArrayFromCache();
409 // Check if $dummy is valid (prevents some errors)
410 if ((is_array($dummy)) && (isset($dummy[$search])) && (is_array($dummy[$search]))) {
411 // Search for key in array
412 $key_found = array_key_exists($search_key, $dummy[$search]);
413 if ($key_found == true) {
415 // Key (hopefully) found?
416 foreach ($dummy as $a => $v) {
417 // So we can update all entries
420 $dummy[$a][$search_key] = $replace;
424 // Flush array to cache file
428 $this->writeArray($dummy);
435 // Cannot write to cache!
436 addFatalMessage(__METHOD__, __LINE__, '(<font color="#0000aa">' . __LINE__ . '</font>): {--CACHE_PROBLEMS_DETECTED');
440 // Writes the version of given extension to the cache file
441 function storeExtensionVersion ($ext_name) {
442 // Valid cache pointer?
443 if (is_resource($this->pointer)) {
444 // Write only if extension is installed
445 if (isExtensionInstalled($ext_name)) {
446 // Get extension version
447 $ext_ver = getExtensionVersion($ext_name);
449 // Add the extension version to object (DO NOT REMOVE IT! Endless loop...)
450 $this->version[$this->name][$ext_name] = $ext_ver;
452 // Write cache line to file
453 $this->writeLine($this->rewriteEntry($ext_name, $ext_ver, 'version', true));
455 //* DEBUG: */ debugOutput(__METHOD__ . '(<font color="#0000aa">' . __LINE__ . '</font>): '.$this->name.' - '.$ext_name.'='.$ext_ver);
457 // Cannot create file
458 addFatalMessage(__METHOD__, __LINE__, '(<font color="#0000aa">' . __LINE__ . '</font>): {--CACHE_PROBLEMS_DETECTED');
462 // Checks wether versions from cache and extension matches
463 function extensionVersionMatches ($ext_name) {
465 if (!isset($GLOBALS[__METHOD__][$ext_name])) {
466 // Does never match by default
467 $GLOBALS[__METHOD__][$ext_name] = false;
469 // Compare only if installed
470 if (isExtensionInstalled($ext_name)) {
471 // Get extension version
472 $ext_ver = getExtensionVersion($ext_name);
475 if (isset($this->version[$this->name][$ext_name])) {
477 $GLOBALS[__METHOD__][$ext_name] = ((isset($this->version[$this->name][$ext_name])) && ($this->version[$this->name][$ext_name] == $ext_ver));
478 } elseif ($this->isCacheReadable()) {
479 // No cache version found!
480 logDebugMessage(__METHOD__, __LINE__, 'Cache ' . $this->name . ' has missing version entry for extension ' . $ext_name . '! Purging cache...');
482 // Remove the cache file
483 $this->removeCacheFile(true);
486 // Not installed, does always match
487 $GLOBALS[__METHOD__][$ext_name] = true;
490 // Cache entry found, log debug message
491 //* DEBUG: */ logDebugMessage(__METHOD__, __LINE__, 'ext_name=' . $ext_name . ', matches=' . intval($GLOBALS[__METHOD__][$ext_name]));
495 return $GLOBALS[__METHOD__][$ext_name];
498 // Rewrit the entry so it can be stored in cache file
499 // @TODO Add support for more types which break in last else-block
500 function rewriteEntry ($key, $value, $prefix = 'data', $single = false) {
501 // Default is not single entry
504 // Add only for single array entry?
505 if ($single === true) {
512 // String or non-string? ;-)
513 if (is_string($value)) {
515 $line = '$this->' . $prefix . "['" . $this->name . "']['" . $key . "']" . $extender . " = '" . escapeQuotes($value) . "';";
516 } elseif (is_null($value)) {
518 $line = '$this->' . $prefix . "['" . $this->name . "']['" . $key . "']" . $extender . ' = null;';
519 } elseif (is_bool($value)) {
521 if ($value === true) {
523 $line = '$this->' . $prefix . "['" . $this->name . "']['" . $key . "']" . $extender . ' = true;';
526 $line = '$this->' . $prefix . "['" . $this->name . "']['" . $key . "']" . $extender . ' = false;';
528 } elseif (isset($value[0])) {
529 // These lines needs fixing
530 debug_report_bug(__METHOD__, __LINE__, 'Invalid entry with [0] found. key=' . $key);
533 $line = '$this->' . $prefix . "['" . $this->name . "']['" . $key . "']" . $extender . ' = ' . $value . ';';
540 // Getter for cache status code
541 function getStatusCode () {
542 return $this->statusCode;
545 // Setter for cache status code
546 function setStatusCode ($status) {
547 $this->statusCode = $status;
550 // Checks wether the current cache file is readable
551 function isCacheReadable () {
552 // Array entry found?
553 if (!isset($this->readable[$this->name])) {
554 // Not found, so create it
555 $this->readable[$this->name] = isFileReadable($this->fqfn);
559 return $this->readable[$this->name];
562 // Cloning not allowed
563 function __clone () {
564 // Please do not clone this class
565 debug_report_bug(__METHOD__, __LINE__, 'Cloning of this class is not allowed.');