Просмотр файла mc-2.7.0/libraries/file_cache.php

Размер файла: 2.55Kb
  1. <?php
  2.  
  3. /**
  4. * MobileCMS
  5. *
  6. * Open source content management system for mobile sites
  7. *
  8. * @author MobileCMS Team <support@mobilecms.pro>
  9. * @copyright Copyright (c) 2011-2019, MobileCMS Team
  10. * @link https://mobilecms.pro Official site
  11. * @license MIT license
  12. */
  13.  
  14. /**
  15. * Кэширование
  16. */
  17. class File_Cache {
  18.  
  19. /**
  20. * Constructor
  21. * @param string $dir
  22. */
  23. public function __construct($dir) {
  24. $this->dir = $dir;
  25.  
  26. if (!is_dir($this->dir) OR ! is_writable($this->dir)) {
  27. exit('Директория для кэша не найдена, либо нет прав на запись');
  28. }
  29. }
  30.  
  31. /**
  32. * Получение данных
  33. */
  34. public function get($key, $expiration = 3600) {
  35. $cache_path = $this->_name($key);
  36. if (!@file_exists($cache_path)) {
  37. return FALSE;
  38. }
  39. if (filemtime($cache_path) < (time() - $expiration)) {
  40. $this->clear($key);
  41. return FALSE;
  42. }
  43. if (!$fp = @fopen($cache_path, 'rb')) {
  44. return FALSE;
  45. }
  46. flock($fp, LOCK_SH);
  47. $cache = '';
  48. if (filesize($cache_path) > 0) {
  49. $cache = unserialize(fread($fp, filesize($cache_path)));
  50. } else {
  51. $cache = NULL;
  52. }
  53. flock($fp, LOCK_UN);
  54. fclose($fp);
  55. return $cache;
  56. }
  57.  
  58. /**
  59. * Запись данных
  60. */
  61. public function set($key, $data) {
  62. $cache_path = $this->_name($key, true);
  63. if (!$fp = fopen($cache_path, 'wb')) {
  64. return FALSE;
  65. }
  66. if (flock($fp, LOCK_EX)) {
  67. fwrite($fp, serialize($data));
  68. flock($fp, LOCK_UN);
  69. } else {
  70. return FALSE;
  71. }
  72. fclose($fp);
  73. @chmod($cache_path, 0777);
  74. return true;
  75. }
  76.  
  77. /**
  78. * Очистка кэша по ключу
  79. */
  80. public function clear($key) {
  81. $cache_path = $this->_name($key);
  82.  
  83. if (file_exists($cache_path)) {
  84. unlink($cache_path);
  85. return true;
  86. }
  87.  
  88. return false;
  89. }
  90.  
  91. /**
  92. * Генерация имени файла
  93. */
  94. private function _name($key, $is_set = false) {
  95. $key_name = md5($key);
  96. $subdir = substr($key_name, 0, 1);
  97. if ($is_set) {
  98. if (!file_exists($this->dir . '/' . $subdir)) {
  99. mkdir($this->dir . '/' . $subdir);
  100. chmod($this->dir . '/' . $subdir, 0777);
  101. }
  102. }
  103. return sprintf("%s/%s/%s", $this->dir, $subdir, $key_name);
  104. }
  105.  
  106. }