Source for file FileStorage.php

Documentation is available at FileStorage.php

  1. 1: <?php
  2. 2:  
  3. 3: /**
  4. 4:  * Nette Framework
  5. 5:  *
  6. 6:  * Copyright (c) 2004, 2009 David Grudl (http://davidgrudl.com)
  7. 7:  *
  8. 8:  * This source file is subject to the "Nette license" that is bundled
  9. 9:  * with this package in the file license.txt.
  10. 10:  *
  11. 11:  * For more information please see http://nettephp.com
  12. 12:  *
  13. 13:  * @copyright  Copyright (c) 2004, 2009 David Grudl
  14. 14:  * @license    http://nettephp.com/license  Nette license
  15. 15:  * @link       http://nettephp.com
  16. 16:  * @category   Nette
  17. 17:  * @package    Nette\Caching
  18. 18:  */
  19. 19:  
  20. 20:  
  21. 21:  
  22. 22: require_once dirname(__FILE__'/../Object.php';
  23. 23:  
  24. 24: require_once dirname(__FILE__'/../Caching/ICacheStorage.php';
  25. 25:  
  26. 26:  
  27. 27:  
  28. 28: /**
  29. 29:  * Cache file storage.
  30. 30:  *
  31. 31:  * @author     David Grudl
  32. 32:  * @copyright  Copyright (c) 2004, 2009 David Grudl
  33. 33:  * @package    Nette\Caching
  34. 34:  */
  35. 35: class FileStorage extends Object implements ICacheStorage
  36. 36: {
  37. 37:     /**
  38. 38:      * Atomic thread safe logic:
  39. 39:      *
  40. 40:      * 1) reading: open(r+b), lock(SH), read
  41. 41:      *     - delete?: lock(EX), truncate*, unlink*, close
  42. 42:      * 2) deleting: open(r+b), lock(EX), truncate*, unlink*, close
  43. 43:      * 3) writing: open(r+b || wb), lock(EX), truncate*, write data, write meta, close
  44. 44:      *
  45. 45:      * *unlink fails in windows
  46. 46:      */
  47. 47:  
  48. 48:     /**#@+ internal cache file structure */
  49. 49:     const META_HEADER_LEN = 28// 22b signature + 6b meta-struct size + serialized meta-struct + data
  50. 50:     // meta structure: array of
  51. 51:     const META_TIME = 'time'// timestamp
  52. 52:     const META_SERIALIZED = 'serialized'// is content serialized?
  53. 53:     const META_PRIORITY = 'priority'// priority
  54. 54:     const META_EXPIRE = 'expire'// expiration timestamp
  55. 55:     const META_DELTA = 'delta'// relative (sliding) expiration
  56. 56:     const META_ITEMS = 'di'// array of dependent items (file => timestamp)
  57. 57:     const META_TAGS = 'tags'// array of tags (tag => [foo])
  58. 58:     const META_CALLBACKS = 'callbacks'// array of callbacks (function, args)
  59. 59:     /**#@-*/
  60. 60:  
  61. 61:     /**#@+ additional cache structure */
  62. 62:     const FILE = 'file';
  63. 63:     const HANDLE = 'handle';
  64. 64:     /**#@-*/
  65. 65:  
  66. 66:  
  67. 67:     /** @var float  probability that the clean() routine is started */
  68. 68:     public static $gcProbability 0.001;
  69. 69:  
  70. 70:     /** @var string */
  71. 71:     private $dir;
  72. 72:  
  73. 73:     /** @var bool */
  74. 74:     private $useSubdir;
  75. 75:  
  76. 76:  
  77. 77:  
  78. 78:     public function __construct($dir)
  79. 79:     {
  80. 80:         $this->useSubdir !ini_get('safe_mode');
  81. 81:         $this->dir $dir;
  82. 82:         if (!$this->useSubdir && (!is_dir($dir|| !is_writable($dir))) {
  83. 83:             throw new InvalidStateException("Temporary directory '$dir' is not writable.");
  84. 84:         }
  85. 85:  
  86. 86:         if (mt_rand(mt_getrandmax(self::$gcProbability{
  87. 87:             $this->clean(array());
  88. 88:         }
  89. 89:     }
  90. 90:  
  91. 91:  
  92. 92:  
  93. 93:     /**
  94. 94:      * Read from cache.
  95. 95:      * @param  string key
  96. 96:      * @return mixed|NULL
  97. 97:      */
  98. 98:     public function read($key)
  99. 99:     {
  100. 100:         $meta $this->readMeta($this->getCacheFile($key)LOCK_SH);
  101. 101:         if ($meta && $this->verify($meta)) {
  102. 102:             return $this->readData($meta)// calls fclose()
  103. 103:  
  104. 104:         else {
  105. 105:             return NULL;
  106. 106:         }
  107. 107:     }
  108. 108:  
  109. 109:  
  110. 110:  
  111. 111:     /**
  112. 112:      * Verifies dependencies.
  113. 113:      * @param  array 
  114. 114:      * @return bool 
  115. 115:      */
  116. 116:     private function verify($meta)
  117. 117:     {
  118. 118:         do {
  119. 119:             if (!empty($meta[self::META_DELTA])) {
  120. 120:                 // meta[file] was added by readMeta()
  121. 121:                 if (filemtime($meta[self::FILE]$meta[self::META_DELTAtime()) break;
  122. 122:                 touch($meta[self::FILE]);
  123. 123:  
  124. 124:             elseif (!empty($meta[self::META_EXPIRE]&& $meta[self::META_EXPIREtime()) {
  125. 125:                 break;
  126. 126:             }
  127. 127:  
  128. 128:             if (!empty($meta[self::META_CALLBACKS]&& !Cache::checkCallbacks($meta[self::META_CALLBACKS])) {
  129. 129:                 break;
  130. 130:             }
  131. 131:  
  132. 132:             if (!empty($meta[self::META_ITEMS])) {
  133. 133:                 foreach ($meta[self::META_ITEMSas $depFile => $time{
  134. 134:                     $m $this->readMeta($depFileLOCK_SH);
  135. 135:                     if ($m[self::META_TIME!== $timebreak 2;
  136. 136:                     if ($m && !$this->verify($m)) break 2;
  137. 137:                 }
  138. 138:             }
  139. 139:  
  140. 140:             return TRUE;
  141. 141:         while (FALSE);
  142. 142:  
  143. 143:         // meta[handle] was added by readMeta()
  144. 144:         flock($meta[self::HANDLE]LOCK_EX);
  145. 145:         ftruncate($meta[self::HANDLE]0);
  146. 146:         @unlink($meta[self::FILE])// intentionally @; meta[file] was added by readMeta()
  147. 147:         fclose($meta[self::HANDLE]);
  148. 148:         return FALSE;
  149. 149:     }
  150. 150:  
  151. 151:  
  152. 152:  
  153. 153:     /**
  154. 154:      * Writes item into the cache.
  155. 155:      * @param  string key
  156. 156:      * @param  mixed  data
  157. 157:      * @param  array  dependencies
  158. 158:      * @return bool  TRUE if no problem
  159. 159:      */
  160. 160:     public function write($key$dataarray $dp)
  161. 161:     {
  162. 162:         $meta array(
  163. 163:             self::META_TIME => microtime(),
  164. 164:         );
  165. 165:  
  166. 166:         if (!is_string($data)) {
  167. 167:             $data serialize($data);
  168. 168:             $meta[self::META_SERIALIZEDTRUE;
  169. 169:         }
  170. 170:  
  171. 171:         if (isset($dp[Cache::PRIORITY])) {
  172. 172:             $meta[self::META_PRIORITY= (int) $dp[Cache::PRIORITY];
  173. 173:         }
  174. 174:  
  175. 175:         if (!empty($dp[Cache::EXPIRE])) {
  176. 176:             if (empty($dp[Cache::SLIDING])) {
  177. 177:                 $meta[self::META_EXPIRE$dp[Cache::EXPIREtime()// absolute time
  178. 178:             else {
  179. 179:                 $meta[self::META_DELTA= (int) $dp[Cache::EXPIRE]// sliding time
  180. 180:             }
  181. 181:         }
  182. 182:  
  183. 183:         if (!empty($dp[Cache::TAGS])) {
  184. 184:             $meta[self::META_TAGSarray_flip(array_values((array) $dp[Cache::TAGS]));
  185. 185:         }
  186. 186:  
  187. 187:         if (!empty($dp[Cache::ITEMS])) {
  188. 188:             foreach ((array) $dp[Cache::ITEMSas $item{
  189. 189:                 $depFile $this->getCacheFile($item);
  190. 190:                 $m $this->readMeta($depFileLOCK_SH);
  191. 191:                 $meta[self::META_ITEMS][$depFile$m[self::META_TIME];
  192. 192:                 unset($m);
  193. 193:             }
  194. 194:         }
  195. 195:  
  196. 196:         if (!empty($dp[Cache::CALLBACKS])) {
  197. 197:             $meta[self::META_CALLBACKS$dp[Cache::CALLBACKS];
  198. 198:         }
  199. 199:  
  200. 200:         $cacheFile $this->getCacheFile($key);
  201. 201:         $dir dirname($cacheFile);
  202. 202:         if ($this->useSubdir && !is_dir($dir)) {
  203. 203:             umask(0000);
  204. 204:             if (!@mkdir($dir0777TRUE)) {
  205. 205:                 throw new InvalidStateException("Unable to create directory '$dir'.");
  206. 206:             }
  207. 207:         }
  208. 208:         $handle @fopen($cacheFile'r+b')// intentionally @
  209. 209:         if (!$handle{
  210. 210:             $handle @fopen($cacheFile'wb')// intentionally @
  211. 211:  
  212. 212:             if (!$handle{
  213. 213:                 return FALSE;
  214. 214:             }
  215. 215:         }
  216. 216:  
  217. 217:         flock($handleLOCK_EX);
  218. 218:         ftruncate($handle0);
  219. 219:  
  220. 220:         $head serialize($meta'?>';
  221. 221:         $head '<?php //netteCache[01]' str_pad((string) strlen($head)6'0'STR_PAD_LEFT$head;
  222. 222:         $headLen strlen($head);
  223. 223:         $dataLen strlen($data);
  224. 224:  
  225. 225:         if (fwrite($handlestr_repeat("\x00"$headLen)$headLen=== $headLen{
  226. 226:             if (fwrite($handle$data$dataLen=== $dataLen{
  227. 227:                 fseek($handle0);
  228. 228:                 if (fwrite($handle$head$headLen=== $headLen{
  229. 229:                     fclose($handle);
  230. 230:                     return TRUE;
  231. 231:                 }
  232. 232:             }
  233. 233:         }
  234. 234:  
  235. 235:         ftruncate($handle0);
  236. 236:         @unlink($cacheFile)// intentionally @
  237. 237:         fclose($handle);
  238. 238:         return TRUE;
  239. 239:     }
  240. 240:  
  241. 241:  
  242. 242:  
  243. 243:     /**
  244. 244:      * Removes item from the cache.
  245. 245:      * @param  string key
  246. 246:      * @return bool  TRUE if no problem
  247. 247:      */
  248. 248:     public function remove($key)
  249. 249:     {
  250. 250:         $cacheFile $this->getCacheFile($key);
  251. 251:         $meta $this->readMeta($cacheFileLOCK_EX);
  252. 252:         if (!$metareturn TRUE;
  253. 253:  
  254. 254:         ftruncate($meta[self::HANDLE]0);
  255. 255:         @unlink($cacheFile)// intentionally @
  256. 256:         fclose($meta[self::HANDLE]);
  257. 257:         return TRUE;
  258. 258:     }
  259. 259:  
  260. 260:  
  261. 261:  
  262. 262:     /**
  263. 263:      * Removes items from the cache by conditions & garbage collector.
  264. 264:      * @param  array  conditions
  265. 265:      * @return bool  TRUE if no problem
  266. 266:      */
  267. 267:     public function clean(array $conds)
  268. 268:     {
  269. 269:         $tags isset($conds[Cache::TAGS]array_flip((array) $conds[Cache::TAGS]array();
  270. 270:  
  271. 271:         $priority isset($conds[Cache::PRIORITY]$conds[Cache::PRIORITY: -1;
  272. 272:  
  273. 273:         $all !empty($conds[Cache::ALL]);
  274. 274:  
  275. 275:         $now time();
  276. 276:  
  277. 277:         $base $this->dir . DIRECTORY_SEPARATOR 'c';
  278. 278:         $iterator new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->dir)RecursiveIteratorIterator::CHILD_FIRST);
  279. 279:         foreach ($iterator as $entry{
  280. 280:             if (strncmp($entry$basestrlen($base))) {
  281. 281:                 continue;
  282. 282:             }
  283. 283:             if ($entry->isDir()) {
  284. 284:                 @rmdir((string) $entry)// intentionally @
  285. 285:                 continue;
  286. 286:             }
  287. 287:             do {
  288. 288:                 $meta $this->readMeta((string) $entryLOCK_SH);
  289. 289:                 if (!$meta || $allcontinue 2;
  290. 290:  
  291. 291:                 if (!empty($meta[self::META_EXPIRE]&& $meta[self::META_EXPIRE$now{
  292. 292:                     break;
  293. 293:                 }
  294. 294:  
  295. 295:                 if (!empty($meta[self::META_PRIORITY]&& $meta[self::META_PRIORITY<= $priority{
  296. 296:                     break;
  297. 297:                 }
  298. 298:  
  299. 299:                 if (!empty($meta[self::META_TAGS]&& array_intersect_key($tags$meta[self::META_TAGS])) {
  300. 300:                     break;
  301. 301:                 }
  302. 302:  
  303. 303:                 fclose($meta[self::HANDLE]);
  304. 304:                 continue 2;
  305. 305:             while (FALSE);
  306. 306:  
  307. 307:             flock($meta[self::HANDLE]LOCK_EX);
  308. 308:             ftruncate($meta[self::HANDLE]0);
  309. 309:             @unlink((string) $entry)// intentionally @
  310. 310:             fclose($meta[self::HANDLE]);
  311. 311:         }
  312. 312:  
  313. 313:         return TRUE;
  314. 314:     }
  315. 315:  
  316. 316:  
  317. 317:  
  318. 318:     /**
  319. 319:      * Reads cache data from disk.
  320. 320:      * @param  string  file path
  321. 321:      * @param  int     lock mode
  322. 322:      * @return array|NULL
  323. 323:      */
  324. 324:     protected function readMeta($file$lock)
  325. 325:     {
  326. 326:         $handle @fopen($file'r+b')// intentionally @
  327. 327:         if (!$handlereturn NULL;
  328. 328:  
  329. 329:         flock($handle$lock);
  330. 330:  
  331. 331:         $head stream_get_contents($handleself::META_HEADER_LEN);
  332. 332:         if ($head && strlen($head=== self::META_HEADER_LEN{
  333. 333:             $size = (int) substr($head-6);
  334. 334:             $meta stream_get_contents($handle$sizeself::META_HEADER_LEN);
  335. 335:             $meta @unserialize($meta)// intentionally @
  336. 336:             if (is_array($meta)) {
  337. 337:                 fseek($handle$size self::META_HEADER_LEN)// needed by PHP < 5.2.6
  338. 338:                 $meta[self::FILE$file;
  339. 339:                 $meta[self::HANDLE$handle;
  340. 340:                 return $meta;
  341. 341:             }
  342. 342:         }
  343. 343:  
  344. 344:         fclose($handle);
  345. 345:         return NULL;
  346. 346:     }
  347. 347:  
  348. 348:  
  349. 349:  
  350. 350:     /**
  351. 351:      * Reads cache data from disk and closes cache file handle.
  352. 352:      * @param  array 
  353. 353:      * @return mixed 
  354. 354:      */
  355. 355:     protected function readData($meta)
  356. 356:     {
  357. 357:         $data stream_get_contents($meta[self::HANDLE]);
  358. 358:         fclose($meta[self::HANDLE]);
  359. 359:  
  360. 360:         if (empty($meta[self::META_SERIALIZED])) {
  361. 361:             return $data;
  362. 362:         else {
  363. 363:             return @unserialize($data)// intentionally @
  364. 364:         }
  365. 365:     }
  366. 366:  
  367. 367:  
  368. 368:  
  369. 369:     /**
  370. 370:      * Returns file name.
  371. 371:      * @param  string 
  372. 372:      * @return string 
  373. 373:      */
  374. 374:     protected function getCacheFile($key)
  375. 375:     {
  376. 376:         if ($this->useSubdir{
  377. 377:             $key explode(Cache::NAMESPACE_SEPARATOR$key2);
  378. 378:             return $this->dir . '/c' (isset($key[1]'-' urlencode($key[0]'/_' urlencode($key[1]'_' urlencode($key[0]));
  379. 379:         else {
  380. 380:             return $this->dir . '/c_' urlencode($key);
  381. 381:         }
  382. 382:     }
  383. 383: