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 addFatalMessage(__METHOD__, __LINE__, '(<font color="#0000aa">' . __LINE__ . '</font>): {--CACHE_PROBLEMS_DETECTED');
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 == 'refdepths') {
190 $GLOBALS['cache_array']['refdepths'][$k][$data['id']] = $v;
191 } elseif ($this->name == 'refsystem') {
193 $GLOBALS['cache_array']['refsystem'][$k][$data['id']] = $v;
194 } elseif ($this->name == 'revision') {
196 $GLOBALS['cache_array']['revision'][$k][0] = $v;
197 } elseif ($this->name == 'themes') {
199 if ($k == 'theme_path') {
200 $GLOBALS['cache_array']['themes'][$k][$data['id']] = $v;
202 $GLOBALS['cache_array']['themes'][$k][$data['theme_path']] = $v;
204 } elseif ($this->name == 'imprint') {
206 $GLOBALS['cache_array']['imprint'][$k][$data['imprint_id']] = $v;
207 } elseif (is_array($v)) {
208 // Serialize and BASE64-encode the array
209 $v = base64_encode(serialize($v));
211 // Finialize the cache and close it
215 $this->removeCacheFile(true);
217 // Unsupported/unhandled cache detected
218 debug_report_bug(__METHOD__, __LINE__, 'Unsupported cache ' . $this->name . ' detected.');
221 // Write cache line to file
222 $this->writeLine($this->rewriteEntry($k, $v));
225 // Cannot create file
226 addFatalMessage(__METHOD__, __LINE__, '(<font color="#0000aa">' . __LINE__ . '</font>): {--CACHE_PROBLEMS_DETECTED');
230 function finalize () {
231 // Quit function when no pointer is set
232 if (is_resource($this->pointer)) {
233 // Add default depency
234 $this->storeExtensionVersion('cache');
237 $this->writeLine('?>');
239 // Close file add destroy handler
240 fclose($this->pointer);
242 // Reset readable status
243 $this->resetCacheReadStatus();
246 if ($this->isCacheReadable()) changeMode($this->fqfn, 0666);
248 // Remove pointer and status
249 unset($this->status[$this->name]);
250 $this->pointer = false;
251 //* DEBUG: */ debugOutput(__METHOD__ . '(<font color="#0000aa">' . __LINE__.'</font>): '.$this->name.' - FINALIZED!');
255 function getArrayFromCache () {
256 // Is the cache already loaded?
257 if (isset($this->data[$this->name])) {
258 // Return it's content!
259 return $this->data[$this->name];
262 // Is the cache file there?
263 if ($this->isCacheReadable()) {
265 include($this->fqfn);
267 // Is there an array?
268 if (isset($this->data[$this->name])) {
269 // Cache version found?
270 if (isset($this->version[$this->name])) {
271 // Check it here if cache matches ext-cache version
272 if (!$this->extensionVersionMatches('cache')) {
274 logDebugMessage(__METHOD__, __LINE__, 'Invalid cache data ' . $this->name . ' detected.');
275 $this->removeCacheFile();
279 // Return cache if detected
280 if (isset($this->data[$this->name])) {
281 return $this->data[$this->name];
284 logDebugMessage(__METHOD__, __LINE__, 'Possible damaged cache ' . $this->name . ' detected.');
285 $this->removeCacheFile();
289 // Cache file not found or not readable
290 debug_report_bug(__METHOD__, __LINE__, $this->name);
291 addFatalMessage(__METHOD__, __LINE__, '(<font color="#0000aa">' . __LINE__ . '</font>): ' . getMaskedMessage('CACHE_CANNOT_LOAD', $this->fqfn));
294 $this->removeCacheFile();
297 // Always return an empty array if we have trouble or no data
301 // Destroy an existing cache file
302 function removeCacheFile ($force = false) {
304 $this->resetCacheReadStatus();
307 //* DEBUG: */ logDebugMessage(__METHOD__, __LINE__, sprintf("%s should be removed.", $this->name));
309 // Is the cache file not yet rebuilt?
310 if ((!isset($this->rebuilt[$this->name])) && ($this->isCacheReadable())) {
311 // Only run in regular output mode
312 if ((!isHtmlOutputMode()) && ($force === false)) {
313 // Debug message if allowed
314 if (isDebugModeEnabled()) {
316 logDebugMessage(__METHOD__, __LINE__, 'Not removing cache ' . $this->name . ' in output_mode=' . getScriptOutputMode());
326 // Debug-mode enabled?
327 if (isDebugModeEnabled()) {
328 // Log removal of cache
329 logDebugMessage(__METHOD__, __LINE__, 'removing cache: ' . $this->name);
332 // Remove cache file from system
333 removeFile($this->fqfn);
336 $this->resetCacheReadStatus();
338 // Is the file there?
339 if (!$this->isCacheReadable()) {
340 // The cache does no longer exist so kill the content
341 unset($this->data[$this->name]);
342 unset($this->version[$this->name]);
343 $this->rebuilt[$this->name] = true;
346 addFatalMessage(__METHOD__, __LINE__, '(<font color="#0000aa">' . __LINE__ . '</font>): ' . getMaskedMessage('CACHE_CANNOT_UNLINK', $this->fqfn));
352 function removeEntry ($search, $data, $array) {
353 if ($this->status[$this->name] == 'done') {
354 // Load cache into dummy array
355 $dummy = $this->getArrayFromCache();
357 // Search for key in array
358 $key = array_search($data, $dummy[$search]);
360 // Key (hopefully) found?
361 foreach ($array as $a) {
362 // So we can remove all elements as requested
363 unset($dummy[$a][$key]);
366 // Flush array to cache file
370 $this->writeArray($dummy);
376 // Cannot write to cache!
377 addFatalMessage(__METHOD__, __LINE__, '(<font color="#0000aa">' . __LINE__ . '</font>): {--CACHE_PROBLEMS_DETECTED');
381 function writeArray ($array) {
382 if (is_resource($this->pointer)) {
383 foreach ($array as $k => $v) {
385 // Multi line(s) found
387 foreach ($v as $k2 => $v2) {
388 // Put every array element in a row...
389 $LINE .= $this->rewriteEntry($k, $v2);
393 $LINE = $this->rewriteEntry($k, $v);
397 $this->writeLine($LINE);
400 // Cannot write array!
401 addFatalMessage(__METHOD__, __LINE__, '(<font color="#0000aa">' . __LINE__ . '</font>): {--CACHE_PROBLEMS_DETECTED');
406 function replaceEntry ($search, $replace, $search_key, $array) {
407 if ($this->status[$this->name] == 'done') {
408 // Load cache into dummy array
409 $dummy = $this->getArrayFromCache();
411 // Check if $dummy is valid (prevents some errors)
412 if ((is_array($dummy)) && (isset($dummy[$search])) && (is_array($dummy[$search]))) {
413 // Search for key in array
414 $key_found = array_key_exists($search_key, $dummy[$search]);
415 if ($key_found == true) {
417 // Key (hopefully) found?
418 foreach ($dummy as $a => $v) {
419 // So we can update all entries
422 $dummy[$a][$search_key] = $replace;
426 // Flush array to cache file
430 $this->writeArray($dummy);
437 // Cannot write to cache!
438 addFatalMessage(__METHOD__, __LINE__, '(<font color="#0000aa">' . __LINE__ . '</font>): {--CACHE_PROBLEMS_DETECTED');
442 // Writes the version of given extension to the cache file
443 function storeExtensionVersion ($ext_name) {
444 // Valid cache pointer?
445 if (is_resource($this->pointer)) {
446 // Write only if extension is installed
447 if (isExtensionInstalled($ext_name)) {
448 // Get extension version
449 $ext_ver = getExtensionVersion($ext_name);
451 // Add the extension version to object (DO NOT REMOVE IT! Endless loop...)
452 $this->version[$this->name][$ext_name] = $ext_ver;
454 // Write cache line to file
455 $this->writeLine($this->rewriteEntry($ext_name, $ext_ver, 'version', true));
457 //* DEBUG: */ debugOutput(__METHOD__ . '(<font color="#0000aa">' . __LINE__ . '</font>): '.$this->name.' - '.$ext_name.'='.$ext_ver);
459 // Cannot create file
460 addFatalMessage(__METHOD__, __LINE__, '(<font color="#0000aa">' . __LINE__ . '</font>): {--CACHE_PROBLEMS_DETECTED');
464 // Checks wether versions from cache and extension matches
465 function extensionVersionMatches ($ext_name) {
467 if (!isset($GLOBALS[__METHOD__][$ext_name])) {
468 // Does never match by default
469 $GLOBALS[__METHOD__][$ext_name] = false;
471 // Compare only if installed
472 if (isExtensionInstalled($ext_name)) {
473 // Get extension version
474 $ext_ver = getExtensionVersion($ext_name);
477 if (isset($this->version[$this->name][$ext_name])) {
479 $GLOBALS[__METHOD__][$ext_name] = ((isset($this->version[$this->name][$ext_name])) && ($this->version[$this->name][$ext_name] == $ext_ver));
480 } elseif ($this->isCacheReadable()) {
481 // No cache version found
482 logDebugMessage(__METHOD__, __LINE__, 'Cache ' . $this->name . ' has missing version entry for extension ' . $ext_name . '! Purging cache...');
484 // Remove the cache file
485 $this->removeCacheFile(true);
488 // Not installed, does always match
489 $GLOBALS[__METHOD__][$ext_name] = true;
492 // Cache entry found, log debug message
493 //* DEBUG: */ logDebugMessage(__METHOD__, __LINE__, 'ext_name=' . $ext_name . ', matches=' . intval($GLOBALS[__METHOD__][$ext_name]));
497 return $GLOBALS[__METHOD__][$ext_name];
500 // Rewrit the entry so it can be stored in cache file
501 // @TODO Add support for more types which break in last else-block
502 function rewriteEntry ($key, $value, $prefix = 'data', $single = false) {
503 // Default is not single entry
506 // Add only for single array entry?
507 if ($single === true) {
514 // String or non-string? ;-)
515 if (is_string($value)) {
517 $line = '$this->' . $prefix . "['" . $this->name . "']['" . $key . "']" . $extender . " = '" . escapeQuotes($value) . "';";
518 } elseif (is_null($value)) {
520 $line = '$this->' . $prefix . "['" . $this->name . "']['" . $key . "']" . $extender . ' = null;';
521 } elseif (is_bool($value)) {
523 if ($value === true) {
525 $line = '$this->' . $prefix . "['" . $this->name . "']['" . $key . "']" . $extender . ' = true;';
528 $line = '$this->' . $prefix . "['" . $this->name . "']['" . $key . "']" . $extender . ' = false;';
530 } elseif (isset($value[0])) {
531 // These lines needs fixing
532 debug_report_bug(__METHOD__, __LINE__, 'Invalid entry with [0] found. key=' . $key);
535 $line = '$this->' . $prefix . "['" . $this->name . "']['" . $key . "']" . $extender . ' = ' . $value . ';';
542 // Getter for cache status code
543 function getStatusCode () {
544 return $this->statusCode;
547 // Setter for cache status code
548 function setStatusCode ($status) {
549 $this->statusCode = $status;
552 // Checks wether the current cache file is readable
553 function isCacheReadable () {
554 // Array entry found?
555 if (!isset($this->readable[$this->name])) {
556 // Not found, so create it
557 $this->readable[$this->name] = isFileReadable($this->fqfn);
561 return $this->readable[$this->name];
564 // Cloning not allowed
565 function __clone () {
566 // Please do not clone this class
567 debug_report_bug(__METHOD__, __LINE__, 'Cloning of this class is not allowed.');