file.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. <?php
  2. /**
  3. * Copyright (c) 2012 Bart Visscher <bartv@thisnet.nl>
  4. * This file is licensed under the Affero General Public License version 3 or
  5. * later.
  6. * See the COPYING-README file.
  7. */
  8. class OC_Cache_File{
  9. protected $storage;
  10. protected function getStorage() {
  11. if (isset($this->storage)) {
  12. return $this->storage;
  13. }
  14. if(OC_User::isLoggedIn()) {
  15. $subdir = 'cache';
  16. $view = new OC_FilesystemView('/'.OC_User::getUser());
  17. if(!$view->file_exists($subdir)) {
  18. $view->mkdir($subdir);
  19. }
  20. $this->storage = new OC_FilesystemView('/'.OC_User::getUser().'/'.$subdir);
  21. return $this->storage;
  22. }else{
  23. OC_Log::write('core', 'Can\'t get cache storage, user not logged in', OC_Log::ERROR);
  24. return false;
  25. }
  26. }
  27. public function get($key) {
  28. if ($this->hasKey($key)) {
  29. $storage = $this->getStorage();
  30. return $storage->file_get_contents($key);
  31. }
  32. return null;
  33. }
  34. public function set($key, $value, $ttl=0) {
  35. $storage = $this->getStorage();
  36. if ($storage and $storage->file_put_contents($key, $value)) {
  37. if ($ttl === 0) {
  38. $ttl = 86400; // 60*60*24
  39. }
  40. return $storage->touch($key, time() + $ttl);
  41. }
  42. return false;
  43. }
  44. public function hasKey($key) {
  45. $storage = $this->getStorage();
  46. if ($storage && $storage->is_file($key)) {
  47. $mtime = $storage->filemtime($key);
  48. if ($mtime < time()) {
  49. $storage->unlink($key);
  50. return false;
  51. }
  52. return true;
  53. }
  54. return false;
  55. }
  56. public function remove($key) {
  57. $storage = $this->getStorage();
  58. if(!$storage) {
  59. return false;
  60. }
  61. return $storage->unlink($key);
  62. }
  63. public function clear($prefix='') {
  64. $storage = $this->getStorage();
  65. if($storage and $storage->is_dir('/')) {
  66. $dh=$storage->opendir('/');
  67. while($file=readdir($dh)) {
  68. if($file!='.' and $file!='..' and ($prefix==='' || strpos($file, $prefix) === 0)) {
  69. $storage->unlink('/'.$file);
  70. }
  71. }
  72. }
  73. return true;
  74. }
  75. public function gc() {
  76. $storage = $this->getStorage();
  77. if($storage and $storage->is_dir('/')) {
  78. $now = time();
  79. $dh=$storage->opendir('/');
  80. while($file=readdir($dh)) {
  81. if($file!='.' and $file!='..') {
  82. $mtime = $storage->filemtime('/'.$file);
  83. if ($mtime < $now) {
  84. $storage->unlink('/'.$file);
  85. }
  86. }
  87. }
  88. }
  89. }
  90. public static function loginListener() {
  91. $c = new self();
  92. $c->gc();
  93. }
  94. }