]> git.mxchange.org Git - mailer.git/blob - inc/classes/cachesystem.class.php
SQL fixed (opps)
[mailer.git] / inc / classes / cachesystem.class.php
1 <?php
2 /************************************************************************
3  * Mailer v0.2.1-FINAL                                Start: 10/22/2009 *
4  * ===================                          Last change: 10/22/2009 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : cachesystem.class.php                            *
8  * -------------------------------------------------------------------- *
9  * Short description : CacheSystem class                                *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : CacheSystem-Klasse                               *
12  * -------------------------------------------------------------------- *
13  * $Revision::                                                        $ *
14  * $Date::                                                            $ *
15  * $Tag:: 0.2.1-FINAL                                                 $ *
16  * $Author::                                                          $ *
17  * -------------------------------------------------------------------- *
18  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
19  * Copyright (c) 2009 - 2011 by Mailer Developer Team                   *
20  * For more information visit: http://mxchange.org                      *
21  *                                                                      *
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.                                  *
26  *                                                                      *
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.                         *
31  *                                                                      *
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,               *
35  * MA  02110-1301  USA                                                  *
36  ************************************************************************/
37
38 // Some security stuff...
39 if (!defined('__SECURITY')) {
40         die();
41 } // END - if
42
43 // Caching class
44 class CacheSystem {
45         // Status code
46         var $statusCode = 'init';
47
48         // Full-qualified filename
49         var $fqfn = '';
50
51         // Resource to cache file
52         var $pointer = false;
53
54         // Data array from cache
55         var $data = array();
56
57         // Version data from cache
58         var $version = array();
59
60         // Cache name
61         var $name = '';
62         var $rebuilt = array();
63
64         // File extension
65         var $extension = '.cache';
66         var $status = array();
67         var $readable = array();
68         var $fullPath = '';
69
70         // Constructor
71         function CacheSystem () {
72                 // Construct full path
73                 $this->fullPath = getPath() . getCachePath();
74
75                 // Failed is the default
76                 $this->setStatusCode('failed');
77
78                 // Check if path exists
79                 if (isDirectory($this->fullPath)) {
80                         // Is there a .htaccess file?
81                         if (isFileReadable($this->fullPath . '.htaccess')) {
82                                 // All done!
83                                 $this->setStatusCode('done');
84                         } else {
85                                 // Stop! Set a .htaccess file first
86                                 $this->setStatusCode('htaccess');
87                         }
88                 } // END - if
89         }
90
91         // Checks validity of cache file and if content is given
92         function loadCacheFile ($cacheName) {
93                 // Remember cache file
94                 $this->name = $cacheName;
95
96                 // Construct FQFN (full qualified file name)
97                 $this->fqfn = $this->fullPath . $cacheName . $this->extension;
98
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();
103
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')));
106                 } // END - if
107                 //* DEBUG: */ debugOutput('cacheName='.$cacheName.',status='.intval($this->status[$cacheName]));
108
109                 // Return status
110                 return $this->status[$cacheName];
111         }
112
113         // Initializes the cache file
114         function init () {
115                 // This will destory an existing cache file!
116                 if ($this->getStatusCode() == 'done') {
117                         // Reset read status
118                         $this->resetCacheReadStatus();
119
120                         // Create file
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 . ' !');
123
124                         // Add open PHP tag
125                         $this->writeLine('<?php');
126                 } else {
127                         // Cannot create file
128                         debug_report_bug(__METHOD__, __LINE__, 'Problems with cache directory detected, getStatusCode()=' . $this->getStatusCode());
129                 }
130         }
131
132         /**
133          * Writes a line to the pointer and adds a \n (new-line) to the end
134          *
135          * @access private
136          */
137         function writeLine ($line) {
138                 // Is the pointer a valid resource?
139                 if (is_resource($this->pointer)) {
140                         // Write the line
141                         fwrite($this->pointer, $line . "\n");
142                 } else {
143                         // Something bad happened
144                         debug_report_bug(__METHOD__, __LINE__, 'Pointer type is ' . gettype($this->pointer) . ', expected is resource.');
145                 }
146         }
147
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]);
153         }
154
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;
164                                         } else {
165                                                 $GLOBALS['cache_array']['extension'][$k][$data['ext_name']] = $v;
166                                         }
167                                         if (($k == 'ext_keep') && ($v == 'Y')) {
168                                                 $GLOBALS['cache_array']['always_active'][$data['ext_name']] = $v;
169                                         } // END - if
170                                 } elseif ($this->name == 'config') {
171                                         // Configuration
172                                         $GLOBALS['cache_array']['config'][$data['config']][$k] = $v;
173                                 } elseif ($this->name == 'filter') {
174                                         // 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') {
179                                         // Modules
180                                         $GLOBALS['cache_array']['modules'][$k][$data['module']] = $v;
181                                 } elseif ($this->name == 'admin') {
182                                         // Admin logins
183                                         if ($k == 'admin_id') {
184                                                 $GLOBALS['cache_array']['admin'][$k][$data['login']] = $v;
185                                         } else {
186                                                 $GLOBALS['cache_array']['admin'][$k][$data['admin_id']] = $v;
187                                         }
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') {
192                                         // Referral levels
193                                         $GLOBALS['cache_array']['refdepths'][$k][$data['id']] = $v;
194                                 } elseif ($this->name == 'refsystem') {
195                                         // Referral system
196                                         $GLOBALS['cache_array']['refsystem'][$k][$data['id']] = $v;
197                                 } elseif ($this->name == 'revision') {
198                                         // Revision data
199                                         $GLOBALS['cache_array']['revision'][$k][0] = $v;
200                                 } elseif ($this->name == 'themes') {
201                                         // Themes
202                                         if ($k == 'theme_path') {
203                                                 $GLOBALS['cache_array']['themes'][$k][$data['id']] = $v;
204                                         } else {
205                                                 $GLOBALS['cache_array']['themes'][$k][$data['theme_path']] = $v;
206                                         }
207                                 } elseif ($this->name == 'imprint') {
208                                         // 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 ($this->name == 'earning') {
214                                         // Table 'earning'
215                                         $GLOBALS['cache_array']['earning'][$k][$data['earning_id']] = $v;
216                                 } elseif (is_array($v)) {
217                                         // Serialize and BASE64-encode the array
218                                         $v = base64_encode(serialize($v));
219                                 } else {
220                                         // Finialize the cache and close it
221                                         $this->finalize();
222
223                                         // Remove cache
224                                         $this->removeCacheFile(true);
225
226                                         // Unsupported/unhandled cache detected
227                                         debug_report_bug(__METHOD__, __LINE__, 'Unsupported cache ' . $this->name . ' detected.');
228                                 }
229
230                                 // Write cache line to file
231                                 $this->writeLine($this->rewriteEntry($k, $v));
232                         } // END - foreach
233                 } else {
234                         // Cannot create file
235                         debug_report_bug(__METHOD__, __LINE__, 'Problem with cache detected, no resource! pointer[]=' . gettype($this->pointer));
236                 }
237         }
238
239         function finalize () {
240                 // Quit function when no pointer is set
241                 if (is_resource($this->pointer)) {
242                         // Add default depency
243                         $this->storeExtensionVersion('cache');
244
245                         // Write footer
246                         $this->writeLine('?>');
247
248                         // Close file add destroy handler
249                         fclose($this->pointer);
250
251                         // Reset readable status
252                         $this->resetCacheReadStatus();
253
254                         // Set rights
255                         if ($this->isCacheReadable()) changeMode($this->fqfn, 0666);
256
257                         // Remove pointer and status
258                         unset($this->status[$this->name]);
259                         $this->pointer = false;
260                         //* DEBUG: */ logDebugMessage(__METHOD__, __LINE__, 'name=' . $this->name . ' - FINALIZED!');
261                 } // END - if
262         }
263
264         function getArrayFromCache () {
265                 // Is the cache already loaded?
266                 if (isset($this->data[$this->name])) {
267                         // Return it's content!
268                         return $this->data[$this->name];
269                 } // END - if
270
271                 // Is the cache file there?
272                 if ($this->isCacheReadable()) {
273                         // Load cache file
274                         include($this->fqfn);
275
276                         // Is there an array?
277                         if (isset($this->data[$this->name])) {
278                                 // Cache version found?
279                                 if (isset($this->version[$this->name])) {
280                                         // Check it here if cache matches ext-cache version
281                                         if (!$this->extensionVersionMatches('cache')) {
282                                                 // Invalid
283                                                 logDebugMessage(__METHOD__, __LINE__, 'Invalid cache data ' . $this->name . ' detected.');
284                                                 $this->removeCacheFile();
285                                         } // END - if
286                                 } // END - if
287
288                                 // Return cache if detected
289                                 if (isset($this->data[$this->name])) {
290                                         return $this->data[$this->name];
291                                 } else {
292                                         // Damaged!
293                                         logDebugMessage(__METHOD__, __LINE__, 'Possible damaged cache ' . $this->name . ' detected.');
294                                         $this->removeCacheFile();
295                                 }
296                         } // END - if
297                 } else {
298                         // Cache file not found or not readable
299                         debug_report_bug(__METHOD__, __LINE__, '{%message,CACHE_CANNOT_LOAD=' . $this->name . '%}');
300
301                         // Try to remove it
302                         $this->removeCacheFile();
303                 }
304
305                 // Always return an empty array if we have trouble or no data
306                 return array();
307         }
308
309         // Destroy an existing cache file
310         function removeCacheFile ($force = false) {
311                 // Reset read status
312                 $this->resetCacheReadStatus();
313
314                 // Debug message
315                 //* DEBUG: */ logDebugMessage(__METHOD__, __LINE__, sprintf("%s should be removed.", $this->name));
316
317                 // Is the cache file not yet rebuilt?
318                 if ((!isset($this->rebuilt[$this->name])) && ($this->isCacheReadable())) {
319                         // Only run in regular output mode
320                         if ((!isHtmlOutputMode()) && ($force === false)) {
321                                 // Debug message if allowed
322                                 if (isDebugModeEnabled()) {
323                                         // Debug message
324                                         logDebugMessage(__METHOD__, __LINE__, 'Not removing cache ' . $this->name . ' in output_mode=' . getScriptOutputMode());
325                                 } // END - if
326
327                                 // Abort here
328                                 return;
329                         } // END - if
330
331                         // Close cache
332                         $this->finalize();
333
334                         // Debug-mode enabled?
335                         if (isDebugModeEnabled()) {
336                                 // Log removal of cache
337                                 logDebugMessage(__METHOD__, __LINE__, 'removing cache: ' . $this->name);
338                         } // END - if
339
340                         // Remove cache file from system
341                         //* DEBUG: */ debug_report_bug(__METHOD__, __LINE__, 'About to remove ' . basename($this->fqfn) . '!');
342                         removeFile($this->fqfn);
343
344                         // Reset read status
345                         $this->resetCacheReadStatus();
346
347                         // Is the file there?
348                         if (!$this->isCacheReadable()) {
349                                 // The cache does no longer exist so kill the content
350                                 unset($this->data[$this->name]);
351                                 unset($this->version[$this->name]);
352                                 $this->rebuilt[$this->name] = true;
353                         } else {
354                                 // Not removed!
355                                 debug_report_bug(__METHOD__, __LINE__, '{%message,CACHE_CANNOT_UNLINK=' . $this->name . '%}');
356                         }
357                 } // END - if
358         }
359
360         // Unused method:
361         function removeEntry ($search, $data, $array) {
362                 if ($this->status[$this->name] == 'done') {
363                         // Load cache into dummy array
364                         $dummy = $this->getArrayFromCache();
365
366                         // Search for key in array
367                         $key = array_search($data, $dummy[$search]);
368                         if (!empty($key)) {
369                                 // Key (hopefully) found?
370                                 foreach ($array as $a) {
371                                         // So we can remove all elements as requested
372                                         unset($dummy[$a][$key]);
373                                 } // END - foreach
374
375                                 // Flush array to cache file
376                                 $this->init();
377
378                                 // Write array out
379                                 $this->writeArray($dummy);
380
381                                 // Close cache file
382                                 $this->finalize();
383                         } // END - if
384                 } else {
385                         // Cannot write to cache!
386                         debug_report_bug(__METHOD__, __LINE__, 'Problem with cache detected: Unexpected status ' . $this->status[$this->name]);
387                 }
388         }
389
390         function writeArray ($array) {
391                 if (is_resource($this->pointer)) {
392                         foreach ($array as $k => $v) {
393                                 if (is_array($v)) {
394                                         // Multi line(s) found
395                                         $LINE = '';
396                                         foreach ($v as $k2 => $v2) {
397                                                 // Put every array element in a row...
398                                                 $LINE .= $this->rewriteEntry($k, $v2);
399                                         } // END - foreach
400                                 } else {
401                                         // Single line found
402                                         $LINE = $this->rewriteEntry($k, $v);
403                                 }
404
405                                 // Write line(s)
406                                 $this->writeLine($LINE);
407                         } // END - foreach
408                 } else {
409                         // Cannot write array!
410                         debug_report_bug(__METHOD__, __LINE__, 'Problem with cache detected: pointer is not resource! pointer[]=' . gettype($this->pointer));
411                 }
412         }
413
414         // Unused method
415         function replaceEntry ($search, $replace, $search_key, $array) {
416                 if ($this->status[$this->name] == 'done') {
417                         // Load cache into dummy array
418                         $dummy = $this->getArrayFromCache();
419
420                         // Check if $dummy is valid (prevents some errors)
421                         if ((is_array($dummy)) && (isset($dummy[$search])) && (is_array($dummy[$search]))) {
422                                 // Search for key in array
423                                 $key_found = array_key_exists($search_key, $dummy[$search]);
424                                 if ($key_found == true) {
425                                         $key = $search_key;
426                                         // Key (hopefully) found?
427                                         foreach ($dummy as $a => $v) {
428                                                 // So we can update all entries
429                                                 if ($a == $search) {
430                                                         // Update now...
431                                                         $dummy[$a][$search_key] = $replace;
432                                                 } // END - if
433                                         } // END - foreach
434
435                                         // Flush array to cache file
436                                         $this->init();
437
438                                         // Write array out
439                                         $this->writeArray($dummy);
440
441                                         // Close cache file
442                                         $this->finalize();
443                                 } // END - if
444                         } // END - if
445                 } else {
446                         // Cannot write to cache!
447                         debug_report_bug(__METHOD__, __LINE__, 'Problem with cache detected: Unexpected status ' . $this->status[$this->name]);
448                 }
449         }
450
451         // Writes the version of given extension to the cache file
452         function storeExtensionVersion ($ext_name) {
453                 // Valid cache pointer?
454                 if (is_resource($this->pointer)) {
455                         // Write only if extension is installed
456                         if (isExtensionInstalled($ext_name)) {
457                                 // Get extension version
458                                 $ext_ver = getExtensionVersion($ext_name);
459
460                                 // Add the extension version to object (DO NOT REMOVE IT! Endless loop...)
461                                 $this->version[$this->name][$ext_name] = $ext_ver;
462
463                                 // Write cache line to file
464                                 $this->writeLine($this->rewriteEntry($ext_name, $ext_ver, 'version', true));
465                         } // END - if
466                         //* DEBUG: */ logDebugMessage(__METHOD__, __LINE__, 'name=' . $this->name . ',ext_name=' . $ext_name . ',ext_ver=' . $ext_ver);
467                 } else {
468                         // Cannot create file
469                         debug_report_bug(__METHOD__, __LINE__, 'Problem with cache detected: pointer is not resource! pointer[]=' . gettype($this->pointer));
470                 }
471         }
472
473         // Checks wether versions from cache and extension matches
474         function extensionVersionMatches ($ext_name) {
475                 // Check cache
476                 if (!isset($GLOBALS[__METHOD__][$ext_name])) {
477                         // Does never match by default
478                         $GLOBALS[__METHOD__][$ext_name] = false;
479
480                         // Compare only if installed
481                         if (isExtensionInstalled($ext_name)) {
482                                 // Get extension version
483                                 $ext_ver = getExtensionVersion($ext_name);
484
485                                 // Debug messages
486                                 if (isset($this->version[$this->name][$ext_name])) {
487                                         // Does it match?
488                                         $GLOBALS[__METHOD__][$ext_name] = ((isset($this->version[$this->name][$ext_name])) && ($this->version[$this->name][$ext_name] == $ext_ver));
489                                 } elseif ($this->isCacheReadable()) {
490                                         // No cache version found
491                                         logDebugMessage(__METHOD__, __LINE__, 'Cache ' . $this->name . ' has missing version entry for extension ' . $ext_name . '! Purging cache...');
492         
493                                         // Remove the cache file
494                                         $this->removeCacheFile(true);
495                                 }
496                         } else {
497                                 // Not installed, does always match
498                                 $GLOBALS[__METHOD__][$ext_name] = true;
499                         }
500                 } else {
501                         // Cache entry found, log debug message
502                         //* DEBUG: */ logDebugMessage(__METHOD__, __LINE__, 'ext_name=' . $ext_name . ', matches=' . intval($GLOBALS[__METHOD__][$ext_name]));
503                 }
504
505                 // Compare both
506                 return $GLOBALS[__METHOD__][$ext_name];
507         }
508
509         // Rewrit the entry so it can be stored in cache file
510         // @TODO Add support for more types which break in last else-block
511         function rewriteEntry ($key, $value, $prefix = 'data', $single = false) {
512                 // Default is not single entry
513                 $extender = '[]';
514
515                 // Add only for single array entry?
516                 if ($single === true) {
517                         $extender = '';
518                 } // END - if
519
520                 // Init line
521                 $line = '';
522
523                 // String or non-string? ;-)
524                 if (is_string($value)) {
525                         // String...
526                         $line = '$this->' . $prefix . "['" . $this->name . "']['" . $key . "']" . $extender . " = '" . escapeQuotes($value) . "';";
527                 } elseif (is_null($value)) {
528                         // Null
529                         $line = '$this->' . $prefix . "['" . $this->name . "']['" . $key . "']" . $extender . ' = NULL;';
530                 } elseif (is_bool($value)) {
531                         // Boolean value
532                         if ($value === true) {
533                                 // True
534                                 $line = '$this->' . $prefix . "['" . $this->name . "']['" . $key . "']" . $extender . ' = true;';
535                         } else {
536                                 // False
537                                 $line = '$this->' . $prefix . "['" . $this->name . "']['" . $key . "']" . $extender . ' = false;';
538                         }
539                 } elseif (isset($value[0])) {
540                         // These lines needs fixing
541                         debug_report_bug(__METHOD__, __LINE__, 'Invalid entry with [0] found. key=' . $key);
542                 } else {
543                         // Non-string
544                         $line = '$this->' . $prefix . "['" . $this->name . "']['" . $key . "']" . $extender . ' = ' . $value . ';';
545                 }
546
547                 // Return line
548                 return $line;
549         }
550
551         // Getter for cache status code
552         function getStatusCode () {
553                 return $this->statusCode;
554         }
555
556         // Setter for cache status code
557         function setStatusCode ($status) {
558                 $this->statusCode = $status;
559         }
560
561         // Checks wether the current cache file is readable
562         function isCacheReadable () {
563                 // Array entry found?
564                 if (!isset($this->readable[$this->name])) {
565                         // Not found, so create it
566                         $this->readable[$this->name] = isFileReadable($this->fqfn);
567                 } // END - if
568
569                 // Return result
570                 return $this->readable[$this->name];
571         }
572
573         // Cloning not allowed
574         function __clone () {
575                 // Please do not clone this class
576                 debug_report_bug(__METHOD__, __LINE__, 'Cloning of this class is not allowed.');
577         }
578 } // END - class
579
580 // [EOF]
581 ?>