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