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?: delete*, close
  42. 42:      * 2) deleting: open(r+b), delete*, close
  43. 43:      * 3) writing: open(r+b || wb), lock(EX), truncate*, write data, write meta, close
  44. 44:      *
  45. 45:      * delete* = lock(EX), try unlink, if fails (on NTFS) { truncate, close, unlink } else close (on ext3)
  46. 46:      */
  47. 47:  
  48. 48:     /**#@+ @ignore 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 bool */
  71. 71:     public static $useDirectories;
  72. 72:  
  73. 73:     /** @var string */
  74. 74:     private $dir;
  75. 75:  
  76. 76:     /** @var bool */
  77. 77:     private $useDirs;
  78. 78:  
  79. 79:  
  80. 80:  
  81. 81:     public function __construct($dir)
  82. 82:     {
  83. 83:         if (self::$useDirectories === NULL{
  84. 84:             self::$useDirectories !ini_get('safe_mode');
  85. 85:  
  86. 86:             // checks whether directory is writable
  87. 87:             $uniq uniqid();
  88. 88:             umask(0000);
  89. 89:             if (!@mkdir("$dir/$uniq"0777)) // intentionally @
  90. 90:                 throw new InvalidStateException("Unable to write to directory '$dir'. Make this directory writable.");
  91. 91:             }
  92. 92:  
  93. 93:             // tests subdirectory mode
  94. 94:             if (!self::$useDirectories && @file_put_contents("$dir/$uniq/_"''!== FALSE// intentionally @
  95. 95:                 self::$useDirectories TRUE;
  96. 96:                 unlink("$dir/$uniq/_");
  97. 97:             }
  98. 98:             rmdir("$dir/$uniq");
  99. 99:         }
  100. 100:  
  101. 101:         $this->dir $dir;
  102. 102:         $this->useDirs = (bool) self::$useDirectories;
  103. 103:  
  104. 104:         if (mt_rand(mt_getrandmax(self::$gcProbability{
  105. 105:             $this->clean(array());
  106. 106:         }
  107. 107:     }
  108. 108:  
  109. 109:  
  110. 110:  
  111. 111:     /**
  112. 112:      * Read from cache.
  113. 113:      * @param  string key
  114. 114:      * @return mixed|NULL
  115. 115:      */
  116. 116:     public function read($key)
  117. 117:     {
  118. 118:         $meta $this->readMeta($this->getCacheFile($key)LOCK_SH);
  119. 119:         if ($meta && $this->verify($meta)) {
  120. 120:             return $this->readData($meta)// calls fclose()
  121. 121:  
  122. 122:         else {
  123. 123:             return NULL;
  124. 124:         }
  125. 125:     }
  126. 126:  
  127. 127:  
  128. 128:  
  129. 129:     /**
  130. 130:      * Verifies dependencies.
  131. 131:      * @param  array 
  132. 132:      * @return bool 
  133. 133:      */
  134. 134:     private function verify($meta)
  135. 135:     {
  136. 136:         do {
  137. 137:             if (!empty($meta[self::META_DELTA])) {
  138. 138:                 // meta[file] was added by readMeta()
  139. 139:                 if (filemtime($meta[self::FILE]$meta[self::META_DELTAtime()) break;
  140. 140:                 touch($meta[self::FILE]);
  141. 141:  
  142. 142:             elseif (!empty($meta[self::META_EXPIRE]&& $meta[self::META_EXPIREtime()) {
  143. 143:                 break;
  144. 144:             }
  145. 145:  
  146. 146:             if (!empty($meta[self::META_CALLBACKS]&& !Cache::checkCallbacks($meta[self::META_CALLBACKS])) {
  147. 147:                 break;
  148. 148:             }
  149. 149:  
  150. 150:             if (!empty($meta[self::META_ITEMS])) {
  151. 151:                 foreach ($meta[self::META_ITEMSas $depFile => $time{
  152. 152:                     $m $this->readMeta($depFileLOCK_SH);
  153. 153:                     if ($m[self::META_TIME!== $timebreak 2;
  154. 154:                     if ($m && !$this->verify($m)) break 2;
  155. 155:                 }
  156. 156:             }
  157. 157:  
  158. 158:             return TRUE;
  159. 159:         while (FALSE);
  160. 160:  
  161. 161:         $this->delete($meta[self::HANDLE]$meta[self::FILE])// meta[handle] & meta[file] was added by readMeta()
  162. 162:         return FALSE;
  163. 163:     }
  164. 164:  
  165. 165:  
  166. 166:  
  167. 167:     /**
  168. 168:      * Writes item into the cache.
  169. 169:      * @param  string key
  170. 170:      * @param  mixed  data
  171. 171:      * @param  array  dependencies
  172. 172:      * @return bool  TRUE if no problem
  173. 173:      */
  174. 174:     public function write($key$dataarray $dp)
  175. 175:     {
  176. 176:         $meta array(
  177. 177:             self::META_TIME => microtime(),
  178. 178:         );
  179. 179:  
  180. 180:         if (!is_string($data)) {
  181. 181:             $data serialize($data);
  182. 182:             $meta[self::META_SERIALIZEDTRUE;
  183. 183:         }
  184. 184:  
  185. 185:         if (isset($dp[Cache::PRIORITY])) {
  186. 186:             $meta[self::META_PRIORITY= (int) $dp[Cache::PRIORITY];
  187. 187:         }
  188. 188:  
  189. 189:         if (!empty($dp[Cache::EXPIRE])) {
  190. 190:             if (empty($dp[Cache::SLIDING])) {
  191. 191:                 $meta[self::META_EXPIRE$dp[Cache::EXPIREtime()// absolute time
  192. 192:             else {
  193. 193:                 $meta[self::META_DELTA= (int) $dp[Cache::EXPIRE]// sliding time
  194. 194:             }
  195. 195:         }
  196. 196:  
  197. 197:         if (!empty($dp[Cache::TAGS])) {
  198. 198:             $meta[self::META_TAGSarray_flip(array_values((array) $dp[Cache::TAGS]));
  199. 199:         }
  200. 200:  
  201. 201:         if (!empty($dp[Cache::ITEMS])) {
  202. 202:             foreach ((array) $dp[Cache::ITEMSas $item{
  203. 203:                 $depFile $this->getCacheFile($item);
  204. 204:                 $m $this->readMeta($depFileLOCK_SH);
  205. 205:                 $meta[self::META_ITEMS][$depFile$m[self::META_TIME];
  206. 206:                 unset($m);
  207. 207:             }
  208. 208:         }
  209. 209:  
  210. 210:         if (!empty($dp[Cache::CALLBACKS])) {
  211. 211:             $meta[self::META_CALLBACKS$dp[Cache::CALLBACKS];
  212. 212:         }
  213. 213:  
  214. 214:         $cacheFile $this->getCacheFile($key);
  215. 215:         if ($this->useDirs && !is_dir($dir dirname($cacheFile))) {
  216. 216:             umask(0000);
  217. 217:             if (!mkdir($dir0777TRUE)) {
  218. 218:                 return FALSE;
  219. 219:             }
  220. 220:         }
  221. 221:         $handle @fopen($cacheFile'r+b')// intentionally @
  222. 222:         if (!$handle{
  223. 223:             $handle fopen($cacheFile'wb')// intentionally @
  224. 224:             if (!$handle{
  225. 225:                 return FALSE;
  226. 226:             }
  227. 227:         }
  228. 228:  
  229. 229:         flock($handleLOCK_EX);
  230. 230:         ftruncate($handle0);
  231. 231:  
  232. 232:         $head serialize($meta'?>';
  233. 233:         $head '<?php //netteCache[01]' str_pad((string) strlen($head)6'0'STR_PAD_LEFT$head;
  234. 234:         $headLen strlen($head);
  235. 235:         $dataLen strlen($data);
  236. 236:  
  237. 237:         if (fwrite($handlestr_repeat("\x00"$headLen)$headLen=== $headLen{
  238. 238:             if (fwrite($handle$data$dataLen=== $dataLen{
  239. 239:                 fseek($handle0);
  240. 240:                 if (fwrite($handle$head$headLen=== $headLen{
  241. 241:                     fclose($handle);
  242. 242:                     return TRUE;
  243. 243:                 }
  244. 244:             }
  245. 245:         }
  246. 246:  
  247. 247:         $this->delete($handle$cacheFile);
  248. 248:         return TRUE;
  249. 249:     }
  250. 250:  
  251. 251:  
  252. 252:  
  253. 253:     /**
  254. 254:      * Removes item from the cache.
  255. 255:      * @param  string key
  256. 256:      * @return bool  TRUE if no problem
  257. 257:      */
  258. 258:     public function remove($key)
  259. 259:     {
  260. 260:         $cacheFile $this->getCacheFile($key);
  261. 261:         $meta $this->readMeta($cacheFileLOCK_EX);
  262. 262:         if ($meta{
  263. 263:             $this->delete($meta[self::HANDLE]$cacheFile);
  264. 264:         }
  265. 265:         return TRUE;
  266. 266:     }
  267. 267:  
  268. 268:  
  269. 269:  
  270. 270:     /**
  271. 271:      * Removes items from the cache by conditions & garbage collector.
  272. 272:      * @param  array  conditions
  273. 273:      * @return bool  TRUE if no problem
  274. 274:      */
  275. 275:     public function clean(array $conds)
  276. 276:     {
  277. 277:         $tags isset($conds[Cache::TAGS]array_flip((array) $conds[Cache::TAGS]array();
  278. 278:  
  279. 279:         $priority isset($conds[Cache::PRIORITY]$conds[Cache::PRIORITY: -1;
  280. 280:  
  281. 281:         $all !empty($conds[Cache::ALL]);
  282. 282:  
  283. 283:         $now time();
  284. 284:  
  285. 285:         $base $this->dir . DIRECTORY_SEPARATOR 'c';
  286. 286:         $iterator new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->dir)RecursiveIteratorIterator::CHILD_FIRST);
  287. 287:         foreach ($iterator as $entry{
  288. 288:             if (strncmp($entry$basestrlen($base))) {
  289. 289:                 continue;
  290. 290:             }
  291. 291:             if ($entry->isDir()) {
  292. 292:                 @rmdir((string) $entry)// intentionally @
  293. 293:                 continue;
  294. 294:             }
  295. 295:             do {
  296. 296:                 $meta $this->readMeta((string) $entryLOCK_SH);
  297. 297:                 if (!$metacontinue 2;
  298. 298:  
  299. 299:                 if ($allbreak;
  300. 300:                 if (!empty($meta[self::META_EXPIRE]&& $meta[self::META_EXPIRE$now{
  301. 301:                     break;
  302. 302:                 }
  303. 303:  
  304. 304:                 if (!empty($meta[self::META_PRIORITY]&& $meta[self::META_PRIORITY<= $priority{
  305. 305:                     break;
  306. 306:                 }
  307. 307:  
  308. 308:                 if (!empty($meta[self::META_TAGS]&& array_intersect_key($tags$meta[self::META_TAGS])) {
  309. 309:                     break;
  310. 310:                 }
  311. 311:  
  312. 312:                 fclose($meta[self::HANDLE]);
  313. 313:                 continue 2;
  314. 314:             while (FALSE);
  315. 315:  
  316. 316:             $this->delete($meta[self::HANDLE](string) $entry);
  317. 317:         }
  318. 318:  
  319. 319:         return TRUE;
  320. 320:     }
  321. 321:  
  322. 322:  
  323. 323:  
  324. 324:     /**
  325. 325:      * Reads cache data from disk.
  326. 326:      * @param  string  file path
  327. 327:      * @param  int     lock mode
  328. 328:      * @return array|NULL
  329. 329:      */
  330. 330:     protected function readMeta($file$lock)
  331. 331:     {
  332. 332:         $handle @fopen($file'r+b')// intentionally @
  333. 333:         if (!$handlereturn NULL;
  334. 334:  
  335. 335:         flock($handle$lock);
  336. 336:  
  337. 337:         $head stream_get_contents($handleself::META_HEADER_LEN);
  338. 338:         if ($head && strlen($head=== self::META_HEADER_LEN{
  339. 339:             $size = (int) substr($head-6);
  340. 340:             $meta stream_get_contents($handle$sizeself::META_HEADER_LEN);
  341. 341:             $meta @unserialize($meta)// intentionally @
  342. 342:             if (is_array($meta)) {
  343. 343:                 fseek($handle$size self::META_HEADER_LEN)// needed by PHP < 5.2.6
  344. 344:                 $meta[self::FILE$file;
  345. 345:                 $meta[self::HANDLE$handle;
  346. 346:                 return $meta;
  347. 347:             }
  348. 348:         }
  349. 349:  
  350. 350:         fclose($handle);
  351. 351:         return NULL;
  352. 352:     }
  353. 353:  
  354. 354:  
  355. 355:  
  356. 356:     /**
  357. 357:      * Reads cache data from disk and closes cache file handle.
  358. 358:      * @param  array 
  359. 359:      * @return mixed 
  360. 360:      */
  361. 361:     protected function readData($meta)
  362. 362:     {
  363. 363:         $data stream_get_contents($meta[self::HANDLE]);
  364. 364:         fclose($meta[self::HANDLE]);
  365. 365:  
  366. 366:         if (empty($meta[self::META_SERIALIZED])) {
  367. 367:             return $data;
  368. 368:         else {
  369. 369:             return @unserialize($data)// intentionally @
  370. 370:         }
  371. 371:     }
  372. 372:  
  373. 373:  
  374. 374:  
  375. 375:     /**
  376. 376:      * Returns file name.
  377. 377:      * @param  string 
  378. 378:      * @return string 
  379. 379:      */
  380. 380:     protected function getCacheFile($key)
  381. 381:     {
  382. 382:         if ($this->useDirs{
  383. 383:             $key explode(Cache::NAMESPACE_SEPARATOR$key2);
  384. 384:             return $this->dir . '/c' (isset($key[1]'-' urlencode($key[0]'/_' urlencode($key[1]'_' urlencode($key[0]));
  385. 385:         else {
  386. 386:             return $this->dir . '/c_' urlencode($key);
  387. 387:         }
  388. 388:     }
  389. 389:  
  390. 390:  
  391. 391:  
  392. 392:     /**
  393. 393:      * Deletes and closes file.
  394. 394:      * @param  resource 
  395. 395:      * @param  string 
  396. 396:      * @return void 
  397. 397:      */
  398. 398:     private static function delete($handle$file)
  399. 399:     {
  400. 400:         if (@unlink($file)) // intentionally @
  401. 401:             fclose($handle);
  402. 402:         else {
  403. 403:             flock($handleLOCK_EX);
  404. 404:             ftruncate($handle0);
  405. 405:             fclose($handle);
  406. 406:             @unlink($file)// intentionally @; not atomic
  407. 407:         }
  408. 408:     }
  409. 409: