2 /************************************************************************
3 * MXChange v0.2.1 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 * Needs to be in all Files and every File needs "svn propset *
18 * svn:keywords Date Revision" (autoprobset!) at least!!!!!! *
19 * -------------------------------------------------------------------- *
20 * Copyright (c) 2003 - 2009 by Roland Haeder *
21 * For more information visit: http://www.mxchange.org *
23 * This program is free software; you can redistribute it and/or modify *
24 * it under the terms of the GNU General Public License as published by *
25 * the Free Software Foundation; either version 2 of the License, or *
26 * (at your option) any later version. *
28 * This program is distributed in the hope that it will be useful, *
29 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
30 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
31 * GNU General Public License for more details. *
33 * You should have received a copy of the GNU General Public License *
34 * along with this program; if not, write to the Free Software *
35 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
37 ************************************************************************/
39 // Some security stuff...
40 if (!defined('__SECURITY')) {
51 var $version = array();
53 var $rebuilt = array();
54 var $extension = '.cache';
55 var $statusDone = 'done';
56 var $status = array();
57 var $readable = array();
60 function CacheSystem () {
61 // Failed is the default
62 $this->ret = 'failed';
66 // Check if path exists
67 if (isDirectory(getConfig('CACHE_PATH'))) {
68 // Make FQFN for dummy file
69 $FQFN = getConfig('CACHE_PATH') . 'dummy.tmp';
71 // Check if we can create a file inside the path
75 if (isFileReadable($FQFN)) {
76 // Yes, we can do. So let's remove it
79 // Is there a .htaccess file?
80 if (isFileReadable(getConfig('CACHE_PATH') . '.htaccess')) {
82 $this->ret = $this->statusDone;
84 // Stop! Set a .htaccess file first
85 $this->ret = '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 = getConfig('CACHE_PATH') . $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: */ print($cacheName.'='.intval($this->isCacheReadable()).'/'.intval(is_writeable($this->fqfn)).'/'.intval($this->extensionVersionMatches('cache')).'<br />');
105 $this->status[$cacheName] = ($this->isCacheReadable() && (is_writeable($this->fqfn)) && ($this->extensionVersionMatches('cache')));
107 //* DEBUG: */ print($cacheName.'='.intval($this->status[$cacheName]).'<br />');
110 return $this->status[$cacheName];
113 // Initializes the cache file
115 // This will destory an existing cache file!
116 if ($this->ret == $this->statusDone) {
118 $this->resetCacheReadStatus();
121 if ($this->isCacheReadable()) changeMode($this->fqfn, 0666);
122 $this->pointer = fopen($this->fqfn, 'w') or app_die(__METHOD__, __LINE__, "Cannot write to cache ".$this->fqfn." !");
125 fwrite($this->pointer, "<?php\n");
127 // Cannot create file
128 addFatalMessage(__METHOD__, __LINE__, "(<font color=\"#0000aa\">".__LINE__."</font>): ".getMessage('CACHE_PROBLEMS_DETECTED'));
132 // Reset the read status
133 function resetCacheReadStatus () {
134 unset($this->readable[$this->name]);
135 unset($GLOBALS['file_readable'][$this->fqfn]);
136 unset($this->status[$this->name]);
139 function addRow ($data) {
140 // Is the pointe rvalid?
141 if (is_resource($this->pointer)) {
142 // Write every array element to cache file
143 foreach ($data as $k => $v) {
144 // Write global cache array for immediate access
145 if ((substr($k, 0, 4) == 'ext_') && (isset($data['ext_name'])) && (isset($data['ext_id']))) {
146 if ($k == 'ext_name') {
147 $GLOBALS['cache_array']['extension'][$k][$data['ext_id']] = $v;
149 $GLOBALS['cache_array']['extension'][$k][$data['ext_name']] = $v;
151 if (($k == 'ext_keep') && ($v == 'Y')) {
152 $GLOBALS['cache_array']['active_extensions'][$data['ext_name']] = $v;
154 } elseif (is_array($v)) {
155 // Serialize and BASE64-encode the array
156 $v = base64_encode(serialize($v));
157 } elseif ($this->name == 'config') {
159 $GLOBALS['cache_array']['config'][$data['config']][$k] = $v;
160 } elseif ($this->name == 'filter') {
162 $GLOBALS['cache_array']['filter']['chains'][$data['filter_name']][$data['filter_function']] = $data['filter_active'];
163 $GLOBALS['cache_array']['filter']['counter'][$data['filter_name']][$data['filter_function']] = $data['filter_counter'];
164 $GLOBALS['cache_array']['filter']['loaded'][$data['filter_name']][$data['filter_function']] = true;
165 } elseif ($this->name == 'modules') {
167 $GLOBALS['cache_array']['modules'][$k][$data['module']] = $v;
168 } elseif ($this->name == 'admin') {
171 $GLOBALS['cache_array']['admin'][$k][$data['admin_id']] = $v;
173 $GLOBALS['cache_array']['admin'][$k][$data['login']] = $v;
175 } elseif ($this->name == 'refdepths') {
177 $GLOBALS['cache_array']['refdepths'][$k][$data['id']] = $v;
178 } elseif ($this->name == 'revision') {
180 $GLOBALS['cache_array']['revision'][$k] = $v;
181 } elseif ($this->name == 'themes') {
183 if ($k == 'theme_path') {
184 $GLOBALS['cache_array']['themes'][$k][$data['id']] = $v;
186 $GLOBALS['cache_array']['themes'][$k][$data['theme_path']] = $v;
189 // Finialize the cache and close it
193 $this->removeCacheFile(true);
195 // Unsupported cache found!
196 debug_report_bug('Unsupported cache ' . $this->name . ' detected.');
199 // Write cache line to file
200 fwrite($this->pointer, $this->rewriteEntry($k, $v));
203 // Cannot create file
204 addFatalMessage(__METHOD__, __LINE__, "(<font color=\"#0000aa\">".__LINE__."</font>): ".getMessage('CACHE_PROBLEMS_DETECTED'));
208 function finalize () {
209 // Quit function when no pointer is set
210 if (is_resource($this->pointer)) {
211 // Add default depency
212 $this->storeExtensionVersion('cache');
215 fwrite($this->pointer, "?>\n");
217 // Close file add destroy handler
218 fclose($this->pointer);
220 // Reset readable status
221 $this->resetCacheReadStatus();
224 if ($this->isCacheReadable()) changeMode($this->fqfn, 0666);
226 // Remove pointer and status
227 unset($this->status[$this->name]);
228 $this->pointer = false;
229 //* DEBUG: */ outputHtml(__METHOD__."(<font color=\"#0000aa\">".__LINE__."</font>): {$this->name} - FINALIZED!<br />");
233 function getArrayFromCache () {
234 // Is the cache already loaded?
235 if (isset($this->data[$this->name])) {
236 // Return it's content!
237 return $this->data[$this->name];
240 // Is the cache file there?
241 if ($this->isCacheReadable()) {
243 require($this->fqfn);
245 // Is there an array?
246 if (isset($this->data[$this->name])) {
247 // Cache version found?
248 if (isset($this->version[$this->name])) {
249 // Check it here if cache matches ext-cache version
250 if (!$this->extensionVersionMatches('cache')) {
252 logDebugMessage(__METHOD__, __LINE__, 'Invalid cache data ' . $this->name . ' detected.');
253 $this->removeCacheFile();
257 // Return cache if detected
258 if (isset($this->data[$this->name])) {
259 return $this->data[$this->name];
262 logDebugMessage(__METHOD__, __LINE__, 'Possible damaged cache ' . $this->name . ' detected.');
263 $this->removeCacheFile();
267 // Cache file not found or not readable
268 debug_report_bug($this->name);
269 addFatalMessage(__METHOD__, __LINE__, "(<font color=\"#0000aa\">".__LINE__."</font>): ".sprintf(getMessage('CACHE_CANNOT_LOAD'), $this->fqfn));
272 $this->removeCacheFile();
275 // Always return an empty array if we have trouble or no data
279 // Destroy an existing cache file
280 function removeCacheFile ($force = false) {
282 $this->resetCacheReadStatus();
285 /* DEBUG: */ logDebugMessage(__METHOD__, __LINE__, sprintf("%s should be removed.", $this->name));
287 // Is the cache file not yet rebuilt?
288 if ((!isset($this->rebuilt[$this->name])) && ($this->isCacheReadable())) {
289 // Only run in regular output mode
290 if ((getOutputMode() != 0) && ($force === false)) {
291 // Debug message if allowed
292 if (isDebugModeEnabled()) {
294 debug_report_bug('Not removing cache ' . $this->name . ' in output_mode=' . getOutputMode());
304 // Debug-mode enabled?
305 if (isDebugModeEnabled()) {
306 // Log removal of cache
307 logDebugMessage(__METHOD__, __LINE__, 'removing cache: ' . $this->name);
310 // Remove cache file from system
311 removeFile($this->fqfn);
314 $this->resetCacheReadStatus();
316 // Is the file there?
317 if (!$this->isCacheReadable()) {
318 // The cache does no longer exist so kill the content
319 unset($this->data[$this->name]);
320 unset($this->version[$this->name]);
321 $this->rebuilt[$this->name] = true;
324 addFatalMessage(__METHOD__, __LINE__, "(<font color=\"#0000aa\">".__LINE__."</font>): ".sprintf(getMessage('CACHE_CANNOT_UNLINK'), $this->fqfn));
330 function removeEntry ($search, $data, $array) {
331 if ($this->status[$this->name] == $this->statusDone) {
332 // Load cache into dummy array
333 $dummy = $this->getArrayFromCache();
335 // Search for key in array
336 $key = array_search($data, $dummy[$search]);
338 // Key (hopefully) found?
339 foreach ($array as $a) {
340 // So we can remove all elements as requested
341 unset($dummy[$a][$key]);
344 // Flush array to cache file
348 $this->writeArray($dummy);
354 // Cannot write to cache!
355 addFatalMessage(__METHOD__, __LINE__, "(<font color=\"#0000aa\">".__LINE__."</font>): ".getMessage('CACHE_PROBLEMS_DETECTED'));
359 function writeArray ($array) {
360 if (is_resource($this->pointer)) {
361 foreach ($array as $k => $v) {
363 // Multi line(s) found
365 foreach($v as $k2 => $v2) {
366 // Put every array element in a row...
367 $LINE .= $this->rewriteEntry($k, $v2);
371 $LINE = $this->rewriteEntry($k, $v);
375 fwrite($this->pointer, $LINE);
378 // Cannot write array!
379 addFatalMessage(__METHOD__, __LINE__, "(<font color=\"#0000aa\">".__LINE__."</font>): ".getMessage('CACHE_PROBLEMS_DETECTED'));
384 function replaceEntry ($search, $replace, $search_key, $array) {
385 if ($this->status[$this->name] == $this->statusDone) {
386 // Load cache into dummy array
387 $dummy = $this->getArrayFromCache();
389 // Check if $dummy is valid (prevents some errors)
390 if ((is_array($dummy)) && (isset($dummy[$search])) && (is_array($dummy[$search]))) {
391 // Search for key in array
392 $key_found = array_key_exists($search_key, $dummy[$search]);
393 if ($key_found == true) {
395 // Key (hopefully) found?
396 foreach ($dummy as $a => $v) {
397 // So we can update all entries
400 $dummy[$a][$search_key] = $replace;
404 // Flush array to cache file
408 $this->writeArray($dummy);
415 // Cannot write to cache!
416 addFatalMessage(__METHOD__, __LINE__, "(<font color=\"#0000aa\">".__LINE__."</font>): ".getMessage('CACHE_PROBLEMS_DETECTED'));
420 // Writes the version of given extension to the cache file
421 function storeExtensionVersion ($ext_name) {
422 // Valid cache pointer?
423 if (is_resource($this->pointer)) {
424 // Write only if extension is installed
425 if (isExtensionInstalled($ext_name)) {
426 // Get extension version
427 $ext_ver = getExtensionVersion($ext_name);
429 // Write cache line to file
430 fwrite($this->pointer, $this->rewriteEntry($ext_name, $ext_ver, 'version', true));
432 // Add the extension version to object (DO NOT REMOVE IT! Endless loop...)
433 $this->version[$this->name][$ext_name] = $ext_ver;
435 //* DEBUG: */ outputHtml(__METHOD__."(<font color=\"#0000aa\">".__LINE__."</font>): {$this->name} - {$ext_name}={$ext_ver}<br />");
437 // Cannot create file
438 addFatalMessage(__METHOD__, __LINE__, "(<font color=\"#0000aa\">".__LINE__."</font>): ".getMessage('CACHE_PROBLEMS_DETECTED'));
442 // Checks wether versions from cache and extension matches
443 function extensionVersionMatches ($ext_name) {
444 // Default is not matching
447 // Compare only if installed
448 if (isExtensionInstalled($ext_name)) {
449 // Get extension version
450 $ext_ver = getExtensionVersion($ext_name);
453 if (isset($this->version[$this->name][$ext_name])) {
455 $matches = ((isset($this->version[$this->name][$ext_name])) && ($this->version[$this->name][$ext_name] == $ext_ver));
456 } elseif ($this->isCacheReadable()) {
457 // No cache version found!
458 logDebugMessage(__METHOD__, __LINE__, "Cache {$this->name} has missing version entry for extension {$ext_name}! Purging cache...");
460 // Remove the cache file
461 $this->removeCacheFile(true);
464 // Not installed, does always match
472 // Rewrit the entry so it can be stored in cache file
473 // @TODO Add support for more types which break in last else-block
474 function rewriteEntry ($key, $value, $prefix = 'data', $single = false) {
475 // Default is not single entry
478 // Add only for single array entry?
479 if ($single === true) $extender = '';
484 // String or non-string? ;-)
485 if (is_string($value)) {
487 $line = '$this->' . $prefix . "['".$this->name."']['" . $key . "']" . $extender . " = '" . smartAddSlashes($value) . "';\n";
488 } elseif (is_null($value)) {
490 $line = '$this->' . $prefix . "['".$this->name."']['" . $key . "']" . $extender . " = null;\n";
491 } elseif (is_bool($value)) {
493 if ($value === true) {
495 $line = '$this->' . $prefix . "['".$this->name."']['" . $key . "']" . $extender . " = true;\n";
498 $line = '$this->' . $prefix . "['".$this->name."']['" . $key . "']" . $extender . " = false;\n";
502 $line = '$this->' . $prefix . "['".$this->name."']['" . $key . "']" . $extender . " = " . $value . ";\n";
509 // Getter for cache status
510 function getStatus () {
514 // Checks wether the current cache file is readable
515 function isCacheReadable () {
516 // Array entry found?
517 if (!isset($this->readable[$this->name])) {
518 // Not found, so create it
519 $this->readable[$this->name] = isFileReadable($this->fqfn);
523 return $this->readable[$this->name];