Namespaces

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

Classes

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

Interfaces

  • IJournal
  • Overview
  • Namespace
  • Class
  • Tree
  1: <?php
  2: 
  3: /**
  4:  * This file is part of the Nette Framework (http://nette.org)
  5:  *
  6:  * Copyright (c) 2004, 2011 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: 
 68: 
 69:     public function __construct($dir, IJournal $journal = NULL)
 70:     {
 71:         $this->dir = realpath($dir);
 72:         if ($this->dir === FALSE) {
 73:             throw new Nette\DirectoryNotFoundException("Directory '$dir' not found.");
 74:         }
 75: 
 76:         $this->useDirs = (bool) self::$useDirectories;
 77:         $this->journal = $journal;
 78: 
 79:         if (mt_rand() / mt_getrandmax() < self::$gcProbability) {
 80:             $this->clean(array());
 81:         }
 82:     }
 83: 
 84: 
 85: 
 86:     /**
 87:      * Read from cache.
 88:      * @param  string key
 89:      * @return mixed|NULL
 90:      */
 91:     public function read($key)
 92:     {
 93:         $meta = $this->readMetaAndLock($this->getCacheFile($key), LOCK_SH);
 94:         if ($meta && $this->verify($meta)) {
 95:             return $this->readData($meta); // calls fclose()
 96: 
 97:         } else {
 98:             return NULL;
 99:         }
100:     }
101: 
102: 
103: 
104:     /**
105:      * Verifies dependencies.
106:      * @param  array
107:      * @return bool
108:      */
109:     private function verify($meta)
110:     {
111:         do {
112:             if (!empty($meta[self::META_DELTA])) {
113:                 // meta[file] was added by readMetaAndLock()
114:                 if (filemtime($meta[self::FILE]) + $meta[self::META_DELTA] < time()) {
115:                     break;
116:                 }
117:                 touch($meta[self::FILE]);
118: 
119:             } elseif (!empty($meta[self::META_EXPIRE]) && $meta[self::META_EXPIRE] < time()) {
120:                 break;
121:             }
122: 
123:             if (!empty($meta[self::META_CALLBACKS]) && !Cache::checkCallbacks($meta[self::META_CALLBACKS])) {
124:                 break;
125:             }
126: 
127:             if (!empty($meta[self::META_ITEMS])) {
128:                 foreach ($meta[self::META_ITEMS] as $depFile => $time) {
129:                     $m = $this->readMetaAndLock($depFile, LOCK_SH);
130:                     if ($m[self::META_TIME] !== $time || ($m && !$this->verify($m))) {
131:                         break 2;
132:                     }
133:                 }
134:             }
135: 
136:             return TRUE;
137:         } while (FALSE);
138: 
139:         $this->delete($meta[self::FILE], $meta[self::HANDLE]); // meta[handle] & meta[file] was added by readMetaAndLock()
140:         return FALSE;
141:     }
142: 
143: 
144: 
145:     /**
146:      * Writes item into the cache.
147:      * @param  string key
148:      * @param  mixed  data
149:      * @param  array  dependencies
150:      * @return void
151:      */
152:     public function write($key, $data, array $dp)
153:     {
154:         $meta = array(
155:             self::META_TIME => microtime(),
156:         );
157: 
158:         if (isset($dp[Cache::EXPIRATION])) {
159:             if (empty($dp[Cache::SLIDING])) {
160:                 $meta[self::META_EXPIRE] = $dp[Cache::EXPIRATION] + time(); // absolute time
161:             } else {
162:                 $meta[self::META_DELTA] = (int) $dp[Cache::EXPIRATION]; // sliding time
163:             }
164:         }
165: 
166:         if (isset($dp[Cache::ITEMS])) {
167:             foreach ((array) $dp[Cache::ITEMS] as $item) {
168:                 $depFile = $this->getCacheFile($item);
169:                 $m = $this->readMetaAndLock($depFile, LOCK_SH);
170:                 $meta[self::META_ITEMS][$depFile] = $m[self::META_TIME]; // may be NULL
171:                 unset($m);
172:             }
173:         }
174: 
175:         if (isset($dp[Cache::CALLBACKS])) {
176:             $meta[self::META_CALLBACKS] = $dp[Cache::CALLBACKS];
177:         }
178: 
179:         $cacheFile = $this->getCacheFile($key);
180:         if ($this->useDirs && !is_dir($dir = dirname($cacheFile))) {
181:             umask(0000);
182:             if (!mkdir($dir, 0777)) {
183:                 return;
184:             }
185:         }
186:         $handle = @fopen($cacheFile, 'r+b'); // @ - file may not exist
187:         if (!$handle) {
188:             $handle = fopen($cacheFile, 'wb');
189:             if (!$handle) {
190:                 return;
191:             }
192:         }
193: 
194:         if (isset($dp[Cache::TAGS]) || isset($dp[Cache::PRIORITY])) {
195:             if (!$this->journal) {
196:                 throw new Nette\InvalidStateException('CacheJournal has not been provided.');
197:             }
198:             $this->journal->write($cacheFile, $dp);
199:         }
200: 
201:         flock($handle, LOCK_EX);
202:         ftruncate($handle, 0);
203: 
204:         if (!is_string($data)) {
205:             $data = serialize($data);
206:             $meta[self::META_SERIALIZED] = TRUE;
207:         }
208: 
209:         $head = serialize($meta) . '?>';
210:         $head = '<?php //netteCache[01]' . str_pad((string) strlen($head), 6, '0', STR_PAD_LEFT) . $head;
211:         $headLen = strlen($head);
212:         $dataLen = strlen($data);
213: 
214:         do {
215:             if (fwrite($handle, str_repeat("\x00", $headLen), $headLen) !== $headLen) {
216:                 break;
217:             }
218: 
219:             if (fwrite($handle, $data, $dataLen) !== $dataLen) {
220:                 break;
221:             }
222: 
223:             fseek($handle, 0);
224:             if (fwrite($handle, $head, $headLen) !== $headLen) {
225:                 break;
226:             }
227: 
228:             flock($handle, LOCK_UN);
229:             fclose($handle);
230:             return TRUE;
231:         } while (FALSE);
232: 
233:         $this->delete($cacheFile, $handle);
234:     }
235: 
236: 
237: 
238:     /**
239:      * Removes item from the cache.
240:      * @param  string key
241:      * @return void
242:      */
243:     public function remove($key)
244:     {
245:         $this->delete($this->getCacheFile($key));
246:     }
247: 
248: 
249: 
250:     /**
251:      * Removes items from the cache by conditions & garbage collector.
252:      * @param  array  conditions
253:      * @return void
254:      */
255:     public function clean(array $conds)
256:     {
257:         $all = !empty($conds[Cache::ALL]);
258:         $collector = empty($conds);
259: 
260:         // cleaning using file iterator
261:         if ($all || $collector) {
262:             $now = time();
263:             foreach (Nette\Utils\Finder::find('*')->from($this->dir)->childFirst() as $entry) {
264:                 $path = (string) $entry;
265:                 if ($entry->isDir()) { // collector: remove empty dirs
266:                     @rmdir($path); // @ - removing dirs is not necessary
267:                     continue;
268:                 }
269:                 if ($all) {
270:                     $this->delete($path);
271: 
272:                 } else { // collector
273:                     $meta = $this->readMetaAndLock($path, LOCK_SH);
274:                     if (!$meta) {
275:                         continue;
276:                     }
277: 
278:                     if ((!empty($meta[self::META_DELTA]) && filemtime($meta[self::FILE]) + $meta[self::META_DELTA] < $now)
279:                         || (!empty($meta[self::META_EXPIRE]) && $meta[self::META_EXPIRE] < $now)
280:                     ) {
281:                         $this->delete($path, $meta[self::HANDLE]);
282:                         continue;
283:                     }
284: 
285:                     flock($meta[self::HANDLE], LOCK_UN);
286:                     fclose($meta[self::HANDLE]);
287:                 }
288:             }
289: 
290:             if ($this->journal) {
291:                 $this->journal->clean($conds);
292:             }
293:             return;
294:         }
295: 
296:         // cleaning using journal
297:         if ($this->journal) {
298:             foreach ($this->journal->clean($conds) as $file) {
299:                 $this->delete($file);
300:             }
301:         }
302:     }
303: 
304: 
305: 
306:     /**
307:      * Reads cache data from disk.
308:      * @param  string  file path
309:      * @param  int     lock mode
310:      * @return array|NULL
311:      */
312:     protected function readMetaAndLock($file, $lock)
313:     {
314:         $handle = @fopen($file, 'r+b'); // @ - file may not exist
315:         if (!$handle) {
316:             return NULL;
317:         }
318: 
319:         flock($handle, $lock);
320: 
321:         $head = stream_get_contents($handle, self::META_HEADER_LEN);
322:         if ($head && strlen($head) === self::META_HEADER_LEN) {
323:             $size = (int) substr($head, -6);
324:             $meta = stream_get_contents($handle, $size, self::META_HEADER_LEN);
325:             $meta = @unserialize($meta); // intentionally @
326:             if (is_array($meta)) {
327:                 fseek($handle, $size + self::META_HEADER_LEN); // needed by PHP < 5.2.6
328:                 $meta[self::FILE] = $file;
329:                 $meta[self::HANDLE] = $handle;
330:                 return $meta;
331:             }
332:         }
333: 
334:         flock($handle, LOCK_UN);
335:         fclose($handle);
336:         return NULL;
337:     }
338: 
339: 
340: 
341:     /**
342:      * Reads cache data from disk and closes cache file handle.
343:      * @param  array
344:      * @return mixed
345:      */
346:     protected function readData($meta)
347:     {
348:         $data = stream_get_contents($meta[self::HANDLE]);
349:         flock($meta[self::HANDLE], LOCK_UN);
350:         fclose($meta[self::HANDLE]);
351: 
352:         if (empty($meta[self::META_SERIALIZED])) {
353:             return $data;
354:         } else {
355:             return @unserialize($data); // intentionally @
356:         }
357:     }
358: 
359: 
360: 
361:     /**
362:      * Returns file name.
363:      * @param  string
364:      * @return string
365:      */
366:     protected function getCacheFile($key)
367:     {
368:         $file = urlencode($key);
369:         if ($this->useDirs && $a = strrpos($file, '%00')) { // %00 = urlencode(Nette\Caching\Cache::NAMESPACE_SEPARATOR)
370:             $file = substr_replace($file, '/_', $a, 3);
371:         }
372:         return $this->dir . '/_' . $file;
373:     }
374: 
375: 
376: 
377:     /**
378:      * Deletes and closes file.
379:      * @param  string
380:      * @param  resource
381:      * @return void
382:      */
383:     private static function delete($file, $handle = NULL)
384:     {
385:         if (@unlink($file)) { // @ - file may not already exist
386:             if ($handle) {
387:                 flock($handle, LOCK_UN);
388:                 fclose($handle);
389:             }
390:             return;
391:         }
392: 
393:         if (!$handle) {
394:             $handle = @fopen($file, 'r+'); // @ - file may not exist
395:         }
396:         if ($handle) {
397:             flock($handle, LOCK_EX);
398:             ftruncate($handle, 0);
399:             flock($handle, LOCK_UN);
400:             fclose($handle);
401:             @unlink($file); // @ - file may not already exist
402:         }
403:     }
404: 
405: }
406: 
Nette Framework 2.0beta1 API API documentation generated by ApiGen 2.3.0