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 - 2012 by Mailer Developer Team *
20 * For more information visit: http://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 reportBug(__METHOD__, __LINE__, 'Cannot write to cache ' . $this->fqfn . ' !');
125 $this->writeLine('<?php');
127 // Cannot create file
128 reportBug(__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 . PHP_EOL);
143 // Something bad happened
144 reportBug(__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 // 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;
166 $GLOBALS['cache_array']['extension'][$k][$data['ext_name']] = $v;
168 if (($k == 'ext_keep') && ($v == 'Y')) {
169 $GLOBALS['cache_array']['always_active'][$data['ext_name']] = $v;
171 } elseif ($this->name == 'config') {
173 $GLOBALS['cache_array']['config'][$data['config']][$k] = $v;
174 } elseif ($this->name == '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') {
181 $GLOBALS['cache_array']['modules'][$k][$data['module']] = $v;
182 } elseif ($this->name == 'admin') {
184 if ($k == 'admin_id') {
185 $GLOBALS['cache_array']['admin'][$k][$data['login']] = $v;
187 $GLOBALS['cache_array']['admin'][$k][$data['admin_id']] = $v;
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') {
194 $GLOBALS['cache_array']['refdepths'][$k][$data['id']] = $v;
195 } elseif ($this->name == 'refsystem') {
197 $GLOBALS['cache_array']['refsystem'][$k][$data['id']] = $v;
198 } elseif ($this->name == 'revision') {
200 $GLOBALS['cache_array']['revision'][$k][0] = $v;
201 } elseif ($this->name == 'themes') {
203 if ($k == 'theme_path') {
204 $GLOBALS['cache_array']['themes'][$k][$data['id']] = $v;
206 $GLOBALS['cache_array']['themes'][$k][$data['theme_path']] = $v;
208 } elseif ($this->name == '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') {
216 $GLOBALS['cache_array']['earning'][$k][$data['earning_id']] = $v;
217 } elseif ($this->name == '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));
224 // Finialize the cache and close it
228 $this->removeCacheFile(TRUE);
230 // Unsupported/unhandled cache detected
231 reportBug(__METHOD__, __LINE__, 'Unsupported cache ' . $this->name . ' detected, data=' . print_r($data, TRUE) . ',k=' . $k . ',v=' . $v);
234 // Write cache line to file
235 $this->writeLine($this->rewriteEntry($k, $v));
238 // Cannot create file
239 reportBug(__METHOD__, __LINE__, 'Problem with cache detected, no resource! pointer[]=' . gettype($this->pointer));
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');
251 $this->writeLine('?>');
253 // Close file add destroy handler
254 fclose($this->pointer);
256 // Reset readable status
257 $this->resetCacheReadStatus();
260 if ($this->isCacheReadable()) changeMode($this->fqfn, 0666);
262 // Remove pointer and status
263 unset($this->status[$this->name]);
264 $this->pointer = FALSE;
265 //* DEBUG: */ logDebugMessage(__METHOD__, __LINE__, 'name=' . $this->name . ' - FINALIZED!');
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];
277 // Is the cache file there?
278 if ($this->isCacheReadable()) {
280 include($this->fqfn);
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')) {
289 logDebugMessage(__METHOD__, __LINE__, 'Invalid cache data ' . $this->name . ' detected.');
290 $this->removeCacheFile();
294 // Return cache if detected
295 if (isset($this->data[$this->name])) {
296 return $this->data[$this->name];
299 logDebugMessage(__METHOD__, __LINE__, 'Possible damaged cache ' . $this->name . ' detected.');
300 $this->removeCacheFile();
304 // Cache file not found or not readable
305 reportBug(__METHOD__, __LINE__, '{%message,CACHE_CANNOT_LOAD=' . $this->name . '%}');
308 $this->removeCacheFile();
311 // Always return an empty array if we have trouble or no data
315 // Destroy an existing cache file
316 function removeCacheFile ($force = FALSE) {
318 $this->resetCacheReadStatus();
321 //* DEBUG: */ logDebugMessage(__METHOD__, __LINE__, sprintf("%s should be removed.", $this->name));
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()) {
330 logDebugMessage(__METHOD__, __LINE__, 'Not removing cache ' . $this->name . ' in output_mode=' . getScriptOutputMode());
340 // Debug-mode enabled?
341 if (isDebugModeEnabled()) {
342 // Log removal of cache
343 logDebugMessage(__METHOD__, __LINE__, 'removing cache: ' . $this->name);
346 // Remove cache file from system
347 //* DEBUG: */ reportBug(__METHOD__, __LINE__, 'About to remove ' . basename($this->fqfn) . '!');
348 removeFile($this->fqfn);
351 $this->resetCacheReadStatus();
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;
361 reportBug(__METHOD__, __LINE__, '{%message,CACHE_CANNOT_UNLINK=' . $this->name . '%}');
367 function removeEntry ($search, $data, $array) {
368 if ($this->status[$this->name] == 'done') {
369 // Load cache into dummy array
370 $dummy = $this->getArrayFromCache();
372 // Search for key in array
373 $key = array_search($data, $dummy[$search]);
375 // Key (hopefully) found?
376 foreach ($array as $a) {
377 // So we can remove all elements as requested
378 unset($dummy[$a][$key]);
381 // Flush array to cache file
385 $this->writeArray($dummy);
391 // Cannot write to cache!
392 reportBug(__METHOD__, __LINE__, 'Problem with cache detected: Unexpected status ' . $this->status[$this->name]);
396 function writeArray ($array) {
397 if (is_resource($this->pointer)) {
398 foreach ($array as $k => $v) {
400 // Multi line(s) found
402 foreach ($v as $k2 => $v2) {
403 // Put every array element in a row...
404 $LINE .= $this->rewriteEntry($k, $v2);
408 $LINE = $this->rewriteEntry($k, $v);
412 $this->writeLine($LINE);
415 // Cannot write array!
416 reportBug(__METHOD__, __LINE__, 'Problem with cache detected: pointer is not resource! pointer[]=' . gettype($this->pointer));
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();
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) {
432 // Key (hopefully) found?
433 foreach ($dummy as $a => $v) {
434 // So we can update all entries
437 $dummy[$a][$search_key] = $replace;
441 // Flush array to cache file
445 $this->writeArray($dummy);
452 // Cannot write to cache!
453 reportBug(__METHOD__, __LINE__, 'Problem with cache detected: Unexpected status ' . $this->status[$this->name]);
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);
466 // Add the extension version to object (DO NOT REMOVE IT! Endless loop...)
467 $this->version[$this->name][$ext_name] = $ext_ver;
469 // Write cache line to file
470 $this->writeLine($this->rewriteEntry($ext_name, $ext_ver, 'version', TRUE));
472 //* DEBUG: */ logDebugMessage(__METHOD__, __LINE__, 'name=' . $this->name . ',ext_name=' . $ext_name . ',ext_ver=' . $ext_ver);
474 // Cannot create file
475 reportBug(__METHOD__, __LINE__, 'Problem with cache detected: pointer is not resource! pointer[]=' . gettype($this->pointer));
479 // Checks whether versions from cache and extension matches
480 function extensionVersionMatches ($ext_name) {
482 if (!isset($GLOBALS[__METHOD__][$ext_name])) {
483 // Does never match by default
484 $GLOBALS[__METHOD__][$ext_name] = FALSE;
486 // Compare only if installed
487 if (isExtensionInstalled($ext_name)) {
488 // Get extension version
489 $ext_ver = getExtensionVersion($ext_name);
492 if (isset($this->version[$this->name][$ext_name])) {
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...');
499 // Remove the cache file
500 $this->removeCacheFile(TRUE);
503 // Not installed, does always match
504 $GLOBALS[__METHOD__][$ext_name] = TRUE;
507 // Cache entry found, log debug message
508 //* DEBUG: */ logDebugMessage(__METHOD__, __LINE__, 'ext_name=' . $ext_name . ', matches=' . intval($GLOBALS[__METHOD__][$ext_name]));
512 return $GLOBALS[__METHOD__][$ext_name];
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
521 // Add only for single array entry?
522 if ($single === TRUE) {
529 // String or non-string? ;-)
530 if (is_string($value)) {
532 $line = '$this->' . $prefix . "['" . $this->name . "']['" . $key . "']" . $extender . " = '" . escapeQuotes($value) . "';";
533 } elseif (is_null($value)) {
535 $line = '$this->' . $prefix . "['" . $this->name . "']['" . $key . "']" . $extender . ' = NULL;';
536 } elseif (is_bool($value)) {
538 if ($value === TRUE) {
540 $line = '$this->' . $prefix . "['" . $this->name . "']['" . $key . "']" . $extender . ' = TRUE;';
543 $line = '$this->' . $prefix . "['" . $this->name . "']['" . $key . "']" . $extender . ' = FALSE;';
545 } elseif (isset($value[0])) {
546 // These lines needs fixing
547 reportBug(__METHOD__, __LINE__, 'Invalid entry with [0] found. key=' . $key);
550 $line = '$this->' . $prefix . "['" . $this->name . "']['" . $key . "']" . $extender . ' = ' . $value . ';';
557 // Getter for cache status code
558 function getStatusCode () {
559 return $this->statusCode;
562 // Setter for cache status code
563 function setStatusCode ($status) {
564 $this->statusCode = $status;
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);
576 return $this->readable[$this->name];
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.');