fileglobal.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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_FileGlobal{
  9. static protected function getCacheDir() {
  10. $cache_dir = get_temp_dir().'/owncloud-'.OC_Util::getInstanceId().'/';
  11. if (!is_dir($cache_dir)) {
  12. mkdir($cache_dir);
  13. }
  14. return $cache_dir;
  15. }
  16. protected function fixKey($key) {
  17. return str_replace('/', '_', $key);
  18. }
  19. public function get($key) {
  20. $key = $this->fixKey($key);
  21. if ($this->hasKey($key)) {
  22. $cache_dir = self::getCacheDir();
  23. return file_get_contents($cache_dir.$key);
  24. }
  25. return null;
  26. }
  27. public function set($key, $value, $ttl=0) {
  28. $key = $this->fixKey($key);
  29. $cache_dir = self::getCacheDir();
  30. if ($cache_dir and file_put_contents($cache_dir.$key, $value)) {
  31. if ($ttl === 0) {
  32. $ttl = 86400; // 60*60*24
  33. }
  34. return touch($cache_dir.$key, time() + $ttl);
  35. }
  36. return false;
  37. }
  38. public function hasKey($key) {
  39. $key = $this->fixKey($key);
  40. $cache_dir = self::getCacheDir();
  41. if ($cache_dir && is_file($cache_dir.$key)) {
  42. $mtime = filemtime($cache_dir.$key);
  43. if ($mtime < time()) {
  44. unlink($cache_dir.$key);
  45. return false;
  46. }
  47. return true;
  48. }
  49. return false;
  50. }
  51. public function remove($key) {
  52. $cache_dir = self::getCacheDir();
  53. if(!$cache_dir) {
  54. return false;
  55. }
  56. $key = $this->fixKey($key);
  57. return unlink($cache_dir.$key);
  58. }
  59. public function clear($prefix='') {
  60. $cache_dir = self::getCacheDir();
  61. $prefix = $this->fixKey($prefix);
  62. if($cache_dir and is_dir($cache_dir)) {
  63. $dh=opendir($cache_dir);
  64. while($file=readdir($dh)) {
  65. if($file!='.' and $file!='..' and ($prefix==='' || strpos($file, $prefix) === 0)) {
  66. unlink($cache_dir.$file);
  67. }
  68. }
  69. }
  70. }
  71. static public function gc() {
  72. $last_run = OC_AppConfig::getValue('core', 'global_cache_gc_lastrun', 0);
  73. $now = time();
  74. if (($now - $last_run) < 300) {
  75. // only do cleanup every 5 minutes
  76. return;
  77. }
  78. OC_AppConfig::setValue('core', 'global_cache_gc_lastrun', $now);
  79. $cache_dir = self::getCacheDir();
  80. if($cache_dir and is_dir($cache_dir)) {
  81. $dh=opendir($cache_dir);
  82. while($file=readdir($dh)) {
  83. if($file!='.' and $file!='..') {
  84. $mtime = filemtime($cache_dir.$file);
  85. if ($mtime < $now) {
  86. unlink($cache_dir.$file);
  87. }
  88. }
  89. }
  90. }
  91. }
  92. }