PageRenderTime 42ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/modules/cacher/filecacher.php

http://github.com/vito/chyrp
PHP | 82 lines | 44 code | 15 blank | 23 comment | 8 complexity | 7d773ab6c324250baa27fd3b6f781a24 MD5 | raw file
  1. <?php
  2. class FileCacher{
  3. public function __construct($url, $config) {
  4. $this->user = (logged_in()) ? Visitor::current()->login : "guest" ;
  5. $this->path = INCLUDES_DIR."/caches/".sanitize($this->user);
  6. $this->caches = INCLUDES_DIR."/caches";
  7. $this->url = $url;
  8. $this->file = $this->path."/".md5($this->url).".html";
  9. # If the cache directory is not writable, disable this module and cancel execution.
  10. if (!is_writable($this->caches))
  11. cancel_module("cacher");
  12. # Remove all expired files.
  13. $this->remove_expired();
  14. }
  15. public function url_available(){
  16. return file_exists($this->file);
  17. }
  18. public function get(){
  19. if (DEBUG)
  20. error_log("SERVING cache file for ".$this->url."...");
  21. $cache = array('contents' => file_get_contents($this->file), 'headers' => array());
  22. if (substr_count($cache['contents'], "<feed"))
  23. $cache["headers"][] = "Content-Type: application/atom+xml; charset=UTF-8";
  24. return $cache;
  25. }
  26. public function set($value){
  27. if (DEBUG)
  28. error_log("GENERATING cache file for ".$this->url."...");
  29. # Generate the user's directory.
  30. if (!file_exists($this->path))
  31. mkdir($this->path);
  32. file_put_contents($this->file, $value);
  33. }
  34. public function remove_expired(){
  35. foreach ((array) glob($this->caches."/*/*.html") as $file) {
  36. if (time() - filemtime($file) > Config::current()->cache_expire)
  37. @unlink($file);
  38. $dir = dirname($file);
  39. if (!count((array) glob($dir."/*")))
  40. @rmdir($dir);
  41. }
  42. }
  43. public function regenerate() {
  44. if (DEBUG)
  45. error_log("REGENERATING");
  46. foreach ((array) glob($this->caches."/*/*.html") as $file)
  47. @unlink($file);
  48. }
  49. public function regenerate_local($user = null) {
  50. if (DEBUG)
  51. error_log("REGENERATING local user ".$this->user."...");
  52. $directory = (isset($user)) ? $this->caches."/".$user : $this->path ;
  53. foreach ((array) glob($directory."/*.html") as $file)
  54. @unlink($file);
  55. }
  56. public function remove_caches_for($url) {
  57. if (DEBUG)
  58. error_log("REMOVING caches for ".$url."...");
  59. foreach ((array) glob($this->caches."/*/".md5($url).".html") as $file)
  60. @unlink($file);
  61. }
  62. }