This repository was archived by the owner on Aug 30, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgriva-chache.php
More file actions
143 lines (128 loc) · 5.49 KB
/
griva-chache.php
File metadata and controls
143 lines (128 loc) · 5.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
<?php
/**
* Plugin Name: GRIVA WordPress Frontend Cache for guests
* Plugin URI: http://tech.griva.group/frontend-guests-cache
* Description: Плагин предназначен для простого кеширования страниц
* Author: Vasily Grigoriev
* Author URI: https://grigoriev.site/
* Network: true
* Version: 0.1.1
*/
class grivaFrontendCache
{
/**
* Относительный путь к папке хранения кэша (относительно корневого каталога сайта)
* !! В конце строки не должно быть символов разделителя директорий
* @var string
*/
private $cacheDir = "wp-content/cache";
/**
* Время хранения файла кэша в секундах
* @var int
*/
private $cacheTime = 3600;
public function __construct()
{
if (!$this->cahceEnabled()) return;
$currentUrl = $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
$hashUrl = md5($currentUrl);
$file = $this->getFilePath($hashUrl);
$isUser = $this->isLoggedInUser();
$renew = false;
// Проверяем - существует ли кэш-файл URL и не истек ли срок его дествия
if (!file_exists($file) || empty(file_get_contents($file))) $renew = true;
elseif (file_exists($file) && time() - filemtime($file) > $this->cacheTime) $renew = true;
if ($renew && !$isUser) {
ob_start(function ($buffer) use ($file) {
file_put_contents($file, $buffer);
return $buffer;
});
add_action('shutdown', function() {
if (!empty(ob_list_handlers())) {
ob_end_flush();
}
}, 100);
} elseif (!$renew && !$isUser) {
print file_get_contents($file); die;
} else {
if (file_exists($file)) unlink($file);
}
}
/**
* Функция возвращает путь к файлу кеша на основе его идентификатора.
* Если подпапок не создано, то они попутно создаются
* @param string $hashUrl Идентификатор файла с кэшем
* @return string
*/
private function getFilePath($hashUrl)
{
$cacheLayers = $this->getLayers($hashUrl);
$absoluteCacheDir = ABSPATH.$this->cacheDir;
// Создаем основную папку, если не создана
if (!is_dir($absoluteCacheDir)) mkdir($absoluteCacheDir);
foreach ($cacheLayers as $layer) {
$currentDir = $absoluteCacheDir.DIRECTORY_SEPARATOR.$layer;
if (is_writable($absoluteCacheDir) && !is_dir($currentDir)) mkdir($currentDir);
$absoluteCacheDir = $currentDir;
}
$cacheFile = $absoluteCacheDir.DIRECTORY_SEPARATOR.$hashUrl.".cache";
return $cacheFile;
}
/**
* Возращает массив названия подпапок, предназначеных для организации кэша,
* выведенного из идентификатора файла кэша
* @param string $hashUrl Идентификатор файла кэша
* @return array Массив с название подпапок
*/
private function getLayers($hashUrl)
{
$firstLayer = substr($hashUrl, 0, 2);
$secondLayer = substr($hashUrl, 2, 2);
return array($firstLayer, $secondLayer);
}
/**
* Метод проверяет все возможные случаи, когда жесткое кеширование страниц не целесообразно
* @return bool
*/
private function cahceEnabled()
{
$isAuth = $this->isAuthPages();
$isAdmin = is_admin();
$isAjax = defined('DOING_AJAX') && DOING_AJAX;
$isPost = !empty($_POST);
$isOffCache = $isAuth || $isAdmin || $isAjax || $isPost;
return !$isOffCache;
}
/**
* Небольшая функция, позволяющая опеределить, указывает ли текущий URL
* на страницу регистрации или страницу входа на сайт.
* @return bool
*/
private function isAuthPages()
{
$absPath = str_replace(['\\','/'], DIRECTORY_SEPARATOR, ABSPATH);
$isRegistrationPage = in_array($absPath.'wp-register.php', get_included_files());
$isLoginPageByFiles = in_array($absPath.'wp-login.php', get_included_files());
$isLoginPageByGlobals = isset($GLOBALS['pagenow']) && $GLOBALS['pagenow'] === 'wp-login.php';
$isLoginPageBySelf = $_SERVER['PHP_SELF']== '/wp-login.php';
$isLoginPage = $isLoginPageByFiles || $isLoginPageByGlobals || $isLoginPageBySelf;
return $isLoginPage || $isRegistrationPage;
}
/**
* Проверяет наличие cookie авторизованного пользователя, т.к. другого варианта
* на данной стадии инициализации WP просто нет
*
* @return bool
*/
private function isLoggedInUser()
{
$isLoggedIn = false;
foreach ($_COOKIE as $key => $value) {
if (preg_match("/^wordpress_logged_in_/i", $key)) {
$isLoggedIn = true;
}
}
return $isLoggedIn;
}
}
new grivaFrontendCache();