-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFrontendAutoReload.module.php
executable file
·263 lines (222 loc) · 7.77 KB
/
FrontendAutoReload.module.php
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
<?php namespace ProcessWire;
/**
* Visionen & Kreationen – FrontendAutoReload
* https://github.com/digitalbricks/FrontendAutoReload
*
* This module is a simple helper for automatically reloading the browser window when a file in the
* /site/templates/ directory is changed. This is useful for development purposes.
*/
class FrontendAutoReload extends WireData implements Module {
/**
* getModuleInfo is a module required by all modules to tell ProcessWire about them
*
* @return array
*
*/
public static function getModuleInfo() {
return array(
'title' => 'FrontendAutoReload',
'version' => 005,
'summary' => 'A module for automatically reloading the browser window when a file in the /site/templates/ directory is changed.',
'author' => 'André Herdling – Visionen & Kreationen',
'icon' => 'refresh',
'autoload' => 'template!=admin', // load only in the frontend (https://processwire.com/talk/topic/3768-processwire-dev-branch/)
'singular' => true,
'requires' => 'ProcessWire>=3.0.173, PHP>=8.2.0'
);
}
private string $endpoint = '/frontendautoreload/latest';
private array $excludedDirectories = ['/images'];
private array $excludedExtensions = ['jpeg', 'jpg', 'png', 'svg', 'gif'];
private int $interval = 5;
private string $watchedDir = '';
public function __construct()
{
parent::__construct();
require_once(__DIR__ . '/ExcludeFilter.php');
$this->watchedDir = $this->wire('config')->paths->templates;
}
public function init() {
// get config from POST
$this->getConfigFromPost();
if(!$this->isAllowed()) return ''; // Only add the hook if the user is allowed
// add URL endpoint for JS polling
// URL hooks where introduced in ProcessWire 3.0.173
// @source: https://processwire.com/blog/posts/pw-3.0.173/
$this->wire->addHook($this->endpoint, function($event) {
header('Content-Type: application/json; charset=utf-8');
$timestamp = $this->getLatestModificationTime();
return json_encode($timestamp);
});
}
/**
* Returns the desired polling interval in seconds
*
* @return int
*/
public function getInterval(): int
{
return $this->interval;
}
/**
* @return array|string[]
*/
public function getExcludedDirectories(): array
{
return $this->excludedDirectories;
}
/**
* @return array|string[]
*/
public function getExcludedExtensions(): array
{
return $this->excludedExtensions;
}
/**
* @param array $excludedDirectories
* @return void
*/
public function setExcludedDirectories(array $excludedDirectories): void
{
$this->excludedDirectories = $excludedDirectories;
}
/**
* @param array $excludedExtensions
* @return void
*/
public function setExcludedExtensions(array $excludedExtensions): void
{
$this->excludedExtensions = $excludedExtensions;
}
/**
* @param int $interval
* @return void
*/
public function setInterval(int $interval): void
{
$this->interval = $interval;
}
/**
* Returns true if these conditions are met:
* - Debug mode is enabled
* - User is logged in
* - User is superuser
*
* @return bool
* @throws WireException
*/
private function isAllowed(){
if ($this->wire('config')->debug === false) return false;
if ($this->wire('user')->isLoggedin() === false) return false;
if ($this->wire('user')->isSuperuser() === false) return false;
return true;
}
/**
* Iterates over watched directory and subdirectories to find the latest modification time
*
* @return int timestamp of the latest modification in the watched directory
*/
private function getLatestModificationTime() {
$latestTime = 0;
$directory = $this->watchedDir;
// Define the image extensions to exclude
$excludedExtensions = ['jpeg', 'jpg', 'png', 'svg', 'gif'];
// Create a new FilesystemIterator
// @source: https://www.php.net/manual/en/class.recursivedirectoryiterator.php#85805
$iterator = new \RecursiveIteratorIterator(
new ExcludeFilter(new \RecursiveDirectoryIterator($directory), $this->watchedDir, $this->excludedDirectories),
\RecursiveIteratorIterator::SELF_FIRST
);
// Iterate through each file in the directory and subdirectories
foreach ($iterator as $file) {
if ($file->isDir()) {
// Check if the directory is in the excluded list
$folderRelativePath = $this->getStrippedPath($file->getPath());
if(in_array($folderRelativePath, $this->excludedDirectories)) {
continue;
}
}
// Check if it's a file (not a directory)
if ($file->isFile()) {
// Get the file extension
$fileExtension = strtolower(pathinfo($file->getFilename(), PATHINFO_EXTENSION));
// Check if the file extension is in the excluded list
if(in_array($fileExtension, $this->excludedExtensions)) {
continue;
}
// Get the modification time of the file
$fileTime = $file->getMTime();
// Update the latest modification time if this file is newer
if ($fileTime > $latestTime) {
$latestTime = $fileTime;
}
}
}
return $latestTime;
}
/**
* Strips the watched directory from the path
* e.g. /var/www/html/site/templates/images/icons -> /images/icons
*
* @param string $path
* @return string
*/
private function getStrippedPath(string $path):string {
$search = rtrim($this->watchedDir,"/");
return str_replace($search, '', $path);
}
/**
* Renders the frontend script element
*
* @return string
* @throws WireException
*/
public function renderScript() {
if(!$this->isAllowed()) return ''; // Only render the script if the user is allowed
return "\n\n".$this->wire('files')->render(__DIR__ . '/components/frontend-js.php', ['far' => $this]);
}
/**
* Returns the (relative) URL of the endpoint
*
* @return string
*/
public function getEndpointUrl(): string
{
$endpoint = ltrim($this->endpoint,"/");
return $this->wire('config')->urls->root . $endpoint;
}
/**
* Returns the configuration as an array
*
* @return array
*/
public function getConfig():array
{
return [
'excludedDirectories' => $this->excludedDirectories,
'excludedExtensions' => $this->excludedExtensions,
'interval' => $this->interval
];
}
/**
* Sets the configuration from the POST request
* (JSON encoded)
*
* @return void
* @throws WireException
*/
private function getConfigFromPost() {
$post = file_get_contents('php://input');
if(!$post) return;
$data = json_decode($post, true);
if(is_array($data) && array_key_exists('excludedDirectories', $data)) {
$this->setExcludedDirectories($data['excludedDirectories']);
}
if(is_array($data) && array_key_exists('excludedExtensions', $data)) {
$this->setExcludedExtensions($data['excludedExtensions']);
}
if(is_array($data) && array_key_exists('interval', $data)) {
$this->setInterval($data['interval']);
}
}
}