-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStaticPages.module
More file actions
256 lines (182 loc) · 6.86 KB
/
Copy pathStaticPages.module
File metadata and controls
256 lines (182 loc) · 6.86 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
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
<?php
/*
Static pages module
https://github.com/ryancramerdesign/Helloworld
AT
28.07.26
*/
namespace ProcessWire;
class StaticPages extends WireData implements Module, ConfigurableModule {
public function init() {
$this->addHookAfter('Modules::saveConfig', $this, 'hookAfterSaveConfig');
if( !$this->isEnabled || $this->isEnabled == '' ) return;
$this->addHookAfter('Page::render', $this, 'hookCache', ['priority' => (int) $this->priority]);
$this->pages->addHookAfter('save', $this, 'hookWipe');
$this->pages->addHookAfter('delete', $this, 'hookWipe');
}
public function hookCache($event) {
return $this->cachePage($event);
}
public function hookWipe($event) {
//skipping wipe is page is a repeater item
if ( $event->arguments[0] instanceof RepeaterPage ) return;
/*
ob_start();
echo 'page: ', var_dump( $event->arguments[0] );
$buffer = ob_get_clean();
$this->message($buffer);
*/
return $this->wipeCaches();
}
public function hookAfterSaveConfig($event) {
//should run in backend only!
//Only continue if settings of this module are being saved.
if( $event->arguments[0] !== $this->className ) return;
if( $_POST['forceWipeOnModuleSave'] != 1 ) return;
return $this->wipeCaches();
}
////
public function cachePage($event) {
//should run in frontend only!
$page = $event->object;
//skipping 404 page caching
if( $page->id == wire('config')->http404PageID ) return;
$html = $event->return;
// skip if template is deprecated
if( in_array($page->template->id, (array)$this->nonStaticTemplates) ) return;
//skip if get or post request
if( count(wire('input')->get) > 0 || count (wire('input')->post) > 0 ) return;
//caching url segments independently for non-404 pages
//if( $page->id != wire('config')->http404PageID )
$urlSegmentStr = wire('input')->urlSegmentStr;
$dir = "{$_SERVER['DOCUMENT_ROOT']}{$page->path}";
if( $urlSegmentStr !='' ) $dir.= "$urlSegmentStr/";
$path = $dir.$this->staticFile;
mkdir($dir, octdec($this->newDirPermissions), true);
file_put_contents($path,$html);
}
public function wipeCaches(){
//wipes every dir/index.html in non-deprecated dirs with no regard to template, page etc
//should run in backend
$start = microtime(true);
ob_start();
if( $this->useShell ){
switch(true){
case stristr( PHP_OS, 'win' ):
$this->wipeCachesWindows();
break;
case stristr( PHP_OS, 'linux' ):
case stristr( PHP_OS, 'unix' ):
case stristr( PHP_OS, 'darwin' ):
$this->wipeCachesLinux();
break;
default:
$this->wipeCachesPHP();
}
}
else
$this->wipeCachesPHP();
$duration = round( microtime(true)-$start, 2 );
echo "Static cache cleaned in $duration s.";
$buffer = ob_get_clean();
$this->message($buffer);
}
//privates
private function wipeCachesLinux(){
//echo 'wipeCachesLinux()';//
$shellCommand = "find {$_SERVER['DOCUMENT_ROOT']} ";
$pruneCommands = [];
$nonStaticDirs = explode( "\n", $this->nonStaticDirs );
foreach( $nonStaticDirs as $nonStaticDir)
$pruneCommands[] = "-type d -name '$nonStaticDir' -prune ";
$shellCommand .= implode(' -o ', $pruneCommands);
$shellCommand .= "-o -type f -name '{$this->staticFile}' -exec rm {} + ";
//echo '$shellCommand: ', var_dump($shellCommand);
`$shellCommand`;
//deleting empty dirs
for( $i=0; $i<$this->rmDirPasses; $i++ )
`find {$_SERVER['DOCUMENT_ROOT']} -type d -empty -exec rmdir {} +`;
}
private function wipeCachesWindows(){
//echo 'wipeCachesWindows()';//
$nonStaticDirs = explode( "\n", $this->nonStaticDirs );
$shellCommand = "Get-ChildItem -Path {$_SERVER['DOCUMENT_ROOT']} -Filter '{$this->staticFile}' -Recurse -File ";
$notLikeCommands = [];
foreach( $nonStaticDirs as $nonStaticDir)
$notLikeCommands[] = "\$_.DirectoryName -notlike '*\\" . $nonStaticDir . "*' ";
if( count($notLikeCommands) )
$shellCommand .= ' | Where-Object {' . implode(' -or ', $notLikeCommands) . '}';
$shellCommand .= " | Remove-Item -Force";
$shellCommand = "powershell \"$shellCommand\"";
//echo '$shellCommand: ', var_dump($shellCommand);
$result = `$shellCommand`;
//echo '$result: ', var_dump($result);
//deleting empty dirs
$shellCommand = "Get-ChildItem -Path {$_SERVER['DOCUMENT_ROOT']} -Recurse -Directory | Where-Object { \$_.GetFileSystemInfos().Count -eq 0 } | Remove-Item -Force -Verbose";
$shellCommand = "powershell \"$shellCommand\"";
//echo '$shellCommand: ', var_dump($shellCommand);
for( $i=0; $i<$this->rmDirPasses; $i++ )
`$shellCommand`;
}
public function wipeCachesPHP(){
//wipes every dir/index.html in non-deprecated dirs with no regard to template, page etc
//should run in backend
$deletedFiles = 0;
$deletedDirs = 0;
$deletedBytes = 0;
$nonStaticDirs = explode( "\n", $this->nonStaticDirs );
//echo '$nonStaticDirs: ', var_dump($nonStaticDirs);//
//echo '$_SERVER[DOCUMENT_ROOT]: ', var_dump($_SERVER['DOCUMENT_ROOT']);//
$rii = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator($_SERVER['DOCUMENT_ROOT']) );
foreach ($rii as $entry) {
//skipping dirs
if ( $entry == $_SERVER['DOCUMENT_ROOT'].'/..' ) continue;
if ( $entry->isDir() ) continue;
$path = $entry->getPathname();
$pathInfo = pathinfo($path);
$dirPath = $pathInfo['dirname'];
//skipping files which should not be deleted
if( $pathInfo['basename'] != $this->staticFile ) continue;
//skipping $nonStaticDirs
$continueFlag = false;
foreach( $nonStaticDirs as $nonStaticDir ){
$sample = $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . $nonStaticDir;
if( strpos($dirPath, $sample) === false ) continue;
$continueFlag = true;
break;
}
if( $continueFlag ) continue;
//echo "deleting file $path...\n";//
$fileSize = filesize($path);
unlink($path);
$deletedFiles++;
$deletedBytes += $fileSize;
//trying to delete the dir if empty
$dirIsEmpty = !(new \FilesystemIterator($dirPath))->valid();
if( !$dirIsEmpty ) continue;
//echo "deleting dir $dirPath...\n";//
rmdir($dirPath);//
$deletedDirs++;
//trying to delete empty dirs up to the DOCUMENT_ROOT level
$parts = explode( DIRECTORY_SEPARATOR, $dirPath );
foreach( $parts as $part ){
array_pop($parts);
$parentDirPath = implode( DIRECTORY_SEPARATOR, $parts );
if( strlen($parentDirPath) <= strlen($_SERVER['DOCUMENT_ROOT']) ) continue;
if( in_array( $parentDirPath, ['', '.', '..'] ) ) continue;
$dirIsEmpty = !(new \FilesystemIterator($parentDirPath))->valid();
if( !$dirIsEmpty ) continue;
//echo "deleting dir $parentDirPath...\n";
rmdir($parentDirPath);//
$deletedDirs++;
}
}
$deletedBytes = $this->readableFilesize($deletedBytes);
echo "$deletedFiles static file(s) ($deletedBytes) and $deletedDirs dir(s) deleted. ";
}
private function readableFilesize($bytes, $decimals = 2) {
$sz = 'BKMGTP';
$factor = floor((strlen($bytes) - 1) / 3);
return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$sz[$factor];
}
}