Namespaces

  • Nette
    • Application
      • Diagnostics
      • Responses
      • Routers
      • UI
    • Caching
      • Storages
    • ComponentModel
    • Config
      • Adapters
      • Extensions
    • Database
      • Diagnostics
      • Drivers
      • Reflection
      • Table
    • DI
      • Diagnostics
    • Diagnostics
    • Forms
      • Controls
      • Rendering
    • Http
    • Iterators
    • Latte
      • Macros
    • Loaders
    • Localization
    • Mail
    • Reflection
    • Security
      • Diagnostics
    • Templating
    • Utils
      • PhpGenerator
  • NetteModule
  • None
  • PHP

Classes

  • DevNullStorage
  • FileJournal
  • FileStorage
  • MemcachedStorage
  • MemoryStorage
  • PhpFileStorage

Interfaces

  • IJournal
  • Overview
  • Namespace
  • Class
  • Tree
  • Deprecated
  1: <?php
  2: 
  3: /**
  4:  * This file is part of the Nette Framework (http://nette.org)
  5:  *
  6:  * Copyright (c) 2004 David Grudl (http://davidgrudl.com)
  7:  *
  8:  * For the full copyright and license information, please view
  9:  * the file license.txt that was distributed with this source code.
 10:  */
 11: 
 12: namespace Nette\Caching\Storages;
 13: 
 14: use Nette,
 15:     Nette\Caching\Cache;
 16: 
 17: 
 18: 
 19: /**
 20:  * Cache file storage.
 21:  *
 22:  * @author     David Grudl
 23:  */
 24: class FileStorage extends Nette\Object implements Nette\Caching\IStorage
 25: {
 26:     /**
 27:      * Atomic thread safe logic:
 28:      *
 29:      * 1) reading: open(r+b), lock(SH), read
 30:      *     - delete?: delete*, close
 31:      * 2) deleting: delete*
 32:      * 3) writing: open(r+b || wb), lock(EX), truncate*, write data, write meta, close
 33:      *
 34:      * delete* = try unlink, if fails (on NTFS) { lock(EX), truncate, close, unlink } else close (on ext3)
 35:      */
 36: 
 37:     /** @internal cache file structure */
 38:     const META_HEADER_LEN = 28, // 22b signature + 6b meta-struct size + serialized meta-struct + data
 39:     // meta structure: array of
 40:         META_TIME = 'time', // timestamp
 41:         META_SERIALIZED = 'serialized', // is content serialized?
 42:         META_EXPIRE = 'expire', // expiration timestamp
 43:         META_DELTA = 'delta', // relative (sliding) expiration
 44:         META_ITEMS = 'di', // array of dependent items (file => timestamp)
 45:         META_CALLBACKS = 'callbacks'; // array of callbacks (function, args)
 46: 
 47:     /** additional cache structure */
 48:     const FILE = 'file',
 49:         HANDLE = 'handle';
 50: 
 51: 
 52:     /** @var float  probability that the clean() routine is started */
 53:     public static $gcProbability = 0.001;
 54: 
 55:     /** @var bool */
 56:     public static $useDirectories = TRUE;
 57: 
 58:     /** @var string */
 59:     private $dir;
 60: 
 61:     /** @var bool */
 62:     private $useDirs;
 63: 
 64:     /** @var IJournal */
 65:     private $journal;
 66: 
 67:     /** @var array */
 68:     private $locks;
 69: 
 70: 
 71: 
 72:     public function __construct($dir, IJournal $journal = NULL)
 73:     {
 74:         $this->dir = realpath($dir);
 75:         if ($this->dir === FALSE) {
 76:             throw new Nette\DirectoryNotFoundException("Directory '$dir' not found.");
 77:         }
 78: 
 79:         $this->useDirs = (bool) static::$useDirectories;
 80:         $this->journal = $journal;
 81: 
 82:         if (mt_rand() / mt_getrandmax() < static::$gcProbability) {
 83:             $this->clean(array());
 84:         }
 85:     }
 86: 
 87: 
 88: 
 89:     /**
 90:      * Read from cache.
 91:      * @param  string key
 92:      * @return mixed|NULL
 93:      */
 94:     public function read($key)
 95:     {
 96:         $meta = $this->readMetaAndLock($this->getCacheFile($key), LOCK_SH);
 97:         if ($meta && $this->verify($meta)) {
 98:             return $this->readData($meta); // calls fclose()
 99: 
100:         } else {
101:             return NULL;
102:         }
103:     }
104: 
105: 
106: 
107:     /**
108:      * Verifies dependencies.
109:      * @param  array
110:      * @return bool
111:      */
112:     private function verify($meta)
113:     {
114:         do {
115:             if (!empty($meta[self::META_DELTA])) {
116:                 // meta[file] was added by readMetaAndLock()
117:                 if (filemtime($meta[self::FILE]) + $meta[self::META_DELTA] < time()) {
118:                     break;
119:                 }
120:                 touch($meta[self::FILE]);
121: 
122:             } elseif (!empty($meta[self::META_EXPIRE]) && $meta[self::META_EXPIRE] < time()) {
123:                 break;
124:             }
125: 
126:             if (!empty($meta[self::META_CALLBACKS]) && !Cache::checkCallbacks($meta[self::META_CALLBACKS])) {
127:                 break;
128:             }
129: 
130:             if (!empty($meta[self::META_ITEMS])) {
131:                 foreach ($meta[self::META_ITEMS] as $depFile => $time) {
132:                     $m = $this->readMetaAndLock($depFile, LOCK_SH);
133:                     if ($m[self::META_TIME] !== $time || ($m && !$this->verify($m))) {
134:                         break 2;
135:                     }
136:                 }
137:             }
138: 
139:             return TRUE;
140:         } while (FALSE);
141: 
142:         $this->delete($meta[self::FILE], $meta[self::HANDLE]); // meta[handle] & meta[file] was added by readMetaAndLock()
143:         return FALSE;
144:     }
145: 
146: 
147: 
148:     /**
149:      * Prevents item reading and writing. Lock is released by write() or remove().
150:      * @param  string key
151:      * @return void
152:      */
153:     public function lock($key)
154:     {
155:         $cacheFile = $this->getCacheFile($key);
156:         if ($this->useDirs && !is_dir($dir = dirname($cacheFile))) {
157:             @mkdir($dir, 0777); // @ - directory may already exist
158:         }
159:         $handle = @fopen($cacheFile, 'r+b'); // @ - file may not exist
160:         if (!$handle) {
161:             $handle = fopen($cacheFile, 'wb');
162:             if (!$handle) {
163:                 return;
164:             }
165:         }
166: 
167:         $this->locks[$key] = $handle;
168:         flock($handle, LOCK_EX);
169:     }
170: 
171: 
172: 
173:     /**
174:      * Writes item into the cache.
175:      * @param  string key
176:      * @param  mixed  data
177:      * @param  array  dependencies
178:      * @return void
179:      */
180:     public function write($key, $data, array $dp)
181:     {
182:         $meta = array(
183:             self::META_TIME => microtime(),
184:         );
185: 
186:         if (isset($dp[Cache::EXPIRATION])) {
187:             if (empty($dp[Cache::SLIDING])) {
188:                 $meta[self::META_EXPIRE] = $dp[Cache::EXPIRATION] + time(); // absolute time
189:             } else {
190:                 $meta[self::META_DELTA] = (int) $dp[Cache::EXPIRATION]; // sliding time
191:             }
192:         }
193: 
194:         if (isset($dp[Cache::ITEMS])) {
195:             foreach ((array) $dp[Cache::ITEMS] as $item) {
196:                 $depFile = $this->getCacheFile($item);
197:                 $m = $this->readMetaAndLock($depFile, LOCK_SH);
198:                 $meta[self::META_ITEMS][$depFile] = $m[self::META_TIME]; // may be NULL
199:                 unset($m);
200:             }
201:         }
202: 
203:         if (isset($dp[Cache::CALLBACKS])) {
204:             $meta[self::META_CALLBACKS] = $dp[Cache::CALLBACKS];
205:         }
206: 
207:         if (!isset($this->locks[$key])) {
208:             $this->lock($key);
209:             if (!isset($this->locks[$key])) {
210:                 return;
211:             }
212:         }
213:         $handle = $this->locks[$key];
214:         unset($this->locks[$key]);
215: 
216:         $cacheFile = $this->getCacheFile($key);
217: 
218:         if (isset($dp[Cache::TAGS]) || isset($dp[Cache::PRIORITY])) {
219:             if (!$this->journal) {
220:                 throw new Nette\InvalidStateException('CacheJournal has not been provided.');
221:             }
222:             $this->journal->write($cacheFile, $dp);
223:         }
224: 
225:         ftruncate($handle, 0);
226: 
227:         if (!is_string($data)) {
228:             $data = serialize($data);
229:             $meta[self::META_SERIALIZED] = TRUE;
230:         }
231: 
232:         $head = serialize($meta) . '?>';
233:         $head = '<?php //netteCache[01]' . str_pad((string) strlen($head), 6, '0', STR_PAD_LEFT) . $head;
234:         $headLen = strlen($head);
235:         $dataLen = strlen($data);
236: 
237:         do {
238:             if (fwrite($handle, str_repeat("\x00", $headLen), $headLen) !== $headLen) {
239:                 break;
240:             }
241: 
242:             if (fwrite($handle, $data, $dataLen) !== $dataLen) {
243:                 break;
244:             }
245: 
246:             fseek($handle, 0);
247:             if (fwrite($handle, $head, $headLen) !== $headLen) {
248:                 break;
249:             }
250: 
251:             flock($handle, LOCK_UN);
252:             fclose($handle);
253:             return;
254:         } while (FALSE);
255: 
256:         $this->delete($cacheFile, $handle);
257:     }
258: 
259: 
260: 
261:     /**
262:      * Removes item from the cache.
263:      * @param  string key
264:      * @return void
265:      */
266:     public function remove($key)
267:     {
268:         unset($this->locks[$key]);
269:         $this->delete($this->getCacheFile($key));
270:     }
271: 
272: 
273: 
274:     /**
275:      * Removes items from the cache by conditions & garbage collector.
276:      * @param  array  conditions
277:      * @return void
278:      */
279:     public function clean(array $conds)
280:     {
281:         $all = !empty($conds[Cache::ALL]);
282:         $collector = empty($conds);
283: 
284:         // cleaning using file iterator
285:         if ($all || $collector) {
286:             $now = time();
287:             foreach (Nette\Utils\Finder::find('_*')->from($this->dir)->childFirst() as $entry) {
288:                 $path = (string) $entry;
289:                 if ($entry->isDir()) { // collector: remove empty dirs
290:                     @rmdir($path); // @ - removing dirs is not necessary
291:                     continue;
292:                 }
293:                 if ($all) {
294:                     $this->delete($path);
295: 
296:                 } else { // collector
297:                     $meta = $this->readMetaAndLock($path, LOCK_SH);
298:                     if (!$meta) {
299:                         continue;
300:                     }
301: 
302:                     if ((!empty($meta[self::META_DELTA]) && filemtime($meta[self::FILE]) + $meta[self::META_DELTA] < $now)
303:                         || (!empty($meta[self::META_EXPIRE]) && $meta[self::META_EXPIRE] < $now)
304:                     ) {
305:                         $this->delete($path, $meta[self::HANDLE]);
306:                         continue;
307:                     }
308: 
309:                     flock($meta[self::HANDLE], LOCK_UN);
310:                     fclose($meta[self::HANDLE]);
311:                 }
312:             }
313: 
314:             if ($this->journal) {
315:                 $this->journal->clean($conds);
316:             }
317:             return;
318:         }
319: 
320:         // cleaning using journal
321:         if ($this->journal) {
322:             foreach ($this->journal->clean($conds) as $file) {
323:                 $this->delete($file);
324:             }
325:         }
326:     }
327: 
328: 
329: 
330:     /**
331:      * Reads cache data from disk.
332:      * @param  string  file path
333:      * @param  int     lock mode
334:      * @return array|NULL
335:      */
336:     protected function readMetaAndLock($file, $lock)
337:     {
338:         $handle = @fopen($file, 'r+b'); // @ - file may not exist
339:         if (!$handle) {
340:             return NULL;
341:         }
342: 
343:         flock($handle, $lock);
344: 
345:         $head = stream_get_contents($handle, self::META_HEADER_LEN);
346:         if ($head && strlen($head) === self::META_HEADER_LEN) {
347:             $size = (int) substr($head, -6);
348:             $meta = stream_get_contents($handle, $size, self::META_HEADER_LEN);
349:             $meta = @unserialize($meta); // intentionally @
350:             if (is_array($meta)) {
351:                 fseek($handle, $size + self::META_HEADER_LEN); // needed by PHP < 5.2.6
352:                 $meta[self::FILE] = $file;
353:                 $meta[self::HANDLE] = $handle;
354:                 return $meta;
355:             }
356:         }
357: 
358:         flock($handle, LOCK_UN);
359:         fclose($handle);
360:         return NULL;
361:     }
362: 
363: 
364: 
365:     /**
366:      * Reads cache data from disk and closes cache file handle.
367:      * @param  array
368:      * @return mixed
369:      */
370:     protected function readData($meta)
371:     {
372:         $data = stream_get_contents($meta[self::HANDLE]);
373:         flock($meta[self::HANDLE], LOCK_UN);
374:         fclose($meta[self::HANDLE]);
375: 
376:         if (empty($meta[self::META_SERIALIZED])) {
377:             return $data;
378:         } else {
379:             return @unserialize($data); // intentionally @
380:         }
381:     }
382: 
383: 
384: 
385:     /**
386:      * Returns file name.
387:      * @param  string
388:      * @return string
389:      */
390:     protected function getCacheFile($key)
391:     {
392:         $file = urlencode($key);
393:         if ($this->useDirs && $a = strrpos($file, '%00')) { // %00 = urlencode(Nette\Caching\Cache::NAMESPACE_SEPARATOR)
394:             $file = substr_replace($file, '/_', $a, 3);
395:         }
396:         return $this->dir . '/_' . $file;
397:     }
398: 
399: 
400: 
401:     /**
402:      * Deletes and closes file.
403:      * @param  string
404:      * @param  resource
405:      * @return void
406:      */
407:     private static function delete($file, $handle = NULL)
408:     {
409:         if (@unlink($file)) { // @ - file may not already exist
410:             if ($handle) {
411:                 flock($handle, LOCK_UN);
412:                 fclose($handle);
413:             }
414:             return;
415:         }
416: 
417:         if (!$handle) {
418:             $handle = @fopen($file, 'r+'); // @ - file may not exist
419:         }
420:         if ($handle) {
421:             flock($handle, LOCK_EX);
422:             ftruncate($handle, 0);
423:             flock($handle, LOCK_UN);
424:             fclose($handle);
425:             @unlink($file); // @ - file may not already exist
426:         }
427:     }
428: 
429: }
430: 
Nette Framework 2.0.8 API API documentation generated by ApiGen 2.8.0