-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathCacheDirUtils.php
651 lines (555 loc) · 32.1 KB
/
CacheDirUtils.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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
<?php
namespace WebSharks\CometCache\Pro\Traits\Shared;
use WebSharks\CometCache\Pro\Classes;
trait CacheDirUtils
{
/**
* Cache directory path.
*
* @since 150422 Rewrite.
*
* @param string $rel_path Relative path inside cache directory.
*
* @throws \Exception If unable to get cache directory.
*
* @return string Absolute path to cache directory.
*/
public function cacheDir($rel_path = '')
{
$rel_path = (string) $rel_path;
if ($this->isAdvancedCache()) {
$cache_dir = defined('COMET_CACHE_DIR') ? COMET_CACHE_DIR : '';
} elseif (!empty($this->cache_sub_dir)) {
$cache_dir = $this->wpContentBaseDirTo($this->cache_sub_dir);
}
if (empty($cache_dir)) {
throw new \Exception(__('Unable to determine cache directory location.', SLUG_TD));
}
return rtrim($cache_dir, '/').($rel_path ? '/'.ltrim($rel_path) : '');
}
/**
* Wipe files from the cache directory (for all hosts/blogs);
* i.e., those that match a specific regex pattern.
*
* @since 151002 While working on directory stats.
*
* @param string $regex A regex pattern; see {@link deleteFilesFromCacheDir()}.
*
* @return int Total files wiped by this routine.
*/
public function wipeFilesFromCacheDir($regex)
{
return $this->deleteFilesFromCacheDir($regex);
}
/**
* Clear files from the cache directory (for the current host);
* i.e., those that match a specific regex pattern.
*
* @since 150422 Rewrite. Updated 151002 w/ multisite compat. improvements.
*
* @param string $regex A regex pattern; see {@link deleteFilesFromHostCacheDir()}.
*
* @return int Total files cleared by this routine (if any).
*/
public function clearFilesFromHostCacheDir($regex)
{
return $this->deleteFilesFromHostCacheDir($regex);
}
/**
* Wurge (purge) files from the cache directory (for all hosts/blogs);
* i.e., those that match a specific regex pattern.
*
* @since 151002 While working on directory stats.
*
* @param string $regex A regex pattern; see {@link deleteFilesFromCacheDir()}.
*
* @return int Total files wurged by this routine.
*/
public function wurgeFilesFromCacheDir($regex)
{
return $this->deleteFilesFromCacheDir($regex, true);
}
/**
* Purge files from the cache directory (for the current host);
* i.e., those that match a specific regex pattern.
*
* @since 150422 Rewrite. Updated 151002 w/ multisite compat. improvements.
*
* @param string $regex A regex pattern; see {@link deleteFilesFromHostCacheDir()}.
*
* @return int Total files purged by this routine (if any).
*/
public function purgeFilesFromHostCacheDir($regex)
{
return $this->deleteFilesFromHostCacheDir($regex, true);
}
/**
* Delete files from the cache directory (for all hosts/blogs);
* i.e., those that match a specific regex pattern.
*
* @since 150422 Rewrite. Updated 151002 w/ multisite compat. improvements.
*
* @param string $regex A `/[regex pattern]/`; relative to the cache directory.
* e.g. `/^http\/example\.com\/my\-slug(?:\/index)?(?:\.|\/(?:page\/[0-9]+|comment\-page\-[0-9]+)[.\/])/`
*
* Or, this can also be a full/absolute regex pattern against an absolute path;
* provided that it always starts with `/^`; including the full absolute cache/host directory path.
* e.g. `/^\/cache\/dir\/http\/example\.com\/my\-slug(?:\/index)?(?:\.|\/(?:page\/[0-9]+|comment\-page\-[0-9]+)[.\/])/`
* @param bool $check_max_age Check max age? i.e., use purge behavior?
*
* @throws \Exception If unable to delete a file for any reason.
* @return int Total files deleted by this routine (if any).
*
*
* @TODO Optimize this for multisite networks w/ a LOT of child blogs.
* @TODO Optimize this for extremely large sites. A LOT of files here could slow things down.
* This class member is currently used in wiping and purging for a network. So there is the potential for a LOT of files in a single scan.
* See also: <https://codex.wordpress.org/Function_Reference/wp_is_large_network>
*/
public function deleteFilesFromCacheDir($regex, $check_max_age = false)
{
$counter = 0; // Initialize.
if (!($regex = (string) $regex)) {
return $counter; // Nothing to do.
}
if (!is_dir($cache_dir = $this->cacheDir())) {
return $counter; // Nothing to do.
}
$cache_dir = $this->nDirSeps($cache_dir);
if ($check_max_age && $this->isAdvancedCache()) {
throw new \Exception(__('Invalid argument; isAdvancedCache!', SLUG_TD));
}
if ($check_max_age && !($max_age = strtotime('-'.$this->options['cache_max_age']))) {
return $counter; // Invalid cache expiration time.
}
/* ------- Begin lock state... ----------- */
$cache_lock = $this->cacheLock(); // Lock cache writes.
clearstatcache(); // Clear stat cache to be sure we have a fresh start below.
$cache_dir_tmp = $this->addTmpSuffix($cache_dir); // Temporary directory.
$cache_dir_tmp_regex = $regex; // Initialize host-specific regex pattern for the tmp directory.
$cache_dir_tmp_regex = '\\/'.ltrim($cache_dir_tmp_regex, '^\\/'); // Make sure it begins with an escaped `/`.
$cache_dir_tmp_regex = $this->strIreplaceOnce(preg_quote($cache_dir.'/', '/'), '', $cache_dir_tmp_regex);
$cache_dir_tmp_regex = ltrim($cache_dir_tmp_regex, '^\\/');
if (strpos($cache_dir_tmp_regex, '(?:\/') === 0 || strpos($cache_dir_tmp_regex, '(\/') === 0) {
$cache_dir_tmp_regex = '/^'.preg_quote($cache_dir_tmp, '/').$cache_dir_tmp_regex;
} else {
$cache_dir_tmp_regex = '/^'.preg_quote($cache_dir_tmp.'/', '/').$cache_dir_tmp_regex;
}
# if(WP_DEBUG) file_put_contents(WP_CONTENT_DIR.'/'.strtolower(SHORT_NAME).'-debug.log', print_r($regex, TRUE)."\n".print_r($cache_dir_tmp_regex, TRUE)."\n\n", FILE_APPEND);
// Uncomment the above line to debug regex pattern matching used by this routine; and others that call upon it.
if (!rename($cache_dir, $cache_dir_tmp)) {
throw new \Exception(sprintf(__('Unable to delete files. Rename failure on directory: `%1$s`.', SLUG_TD), $cache_dir));
}
foreach (($_dir_regex_iteration = $this->dirRegexIteration($cache_dir_tmp, $cache_dir_tmp_regex)) as $_resource) {
$_resource_type = $_resource->getType();
$_sub_path_name = $_resource->getSubpathname();
$_path_name = $_resource->getPathname();
if ($_resource_type !== 'dir' && strpos($_sub_path_name, '/') === false) {
continue; // Don't delete links/files in the immediate directory; e.g. `[SHORT_NAME]-advanced-cache` or `.htaccess`, etc.
// Actual `http|https/...` cache links/files are nested. Links/files in the immediate directory are for other purposes.
}
switch ($_resource_type) {// Based on type; i.e., `link`, `file`, `dir`.
case 'link': // Symbolic links; i.e., 404 errors.
if ($check_max_age && !empty($max_age) && is_file($_resource->getLinkTarget())) {
if (($_lstat = lstat($_path_name)) && !empty($_lstat['mtime'])) {
if ($_lstat['mtime'] >= $max_age) {
break; // Break switch.
}
}
}
if (!unlink($_path_name)) {
$this->tryErasingAllFilesDirsIn($cache_dir_tmp, true); // Cleanup if possible.
throw new \Exception(sprintf(__('Unable to delete symlink: `%1$s`.', SLUG_TD), $_path_name));
}
++$counter; // Increment counter for each link we delete.
break; // Break switch handler.
case 'file': // Regular files; i.e., not symlinks.
if ($check_max_age && !empty($max_age)) {
if ($_resource->getMTime() >= $max_age) {
break; // Break switch.
}
}
if (!unlink($_path_name)) {
$this->tryErasingAllFilesDirsIn($cache_dir_tmp, true); // Cleanup if possible.
throw new \Exception(sprintf(__('Unable to delete file: `%1$s`.', SLUG_TD), $_path_name));
}
++$counter; // Increment counter for each file we delete.
break; // Break switch handler.
case 'dir': // A regular directory; i.e., not a symlink.
if ($regex !== '/^.+/i') {
break; // Not deleting everything.
}
if ($check_max_age && !empty($max_age)) {
break; // Not deleting everything.
}
if (!rmdir($_path_name)) {
$this->tryErasingAllFilesDirsIn($cache_dir_tmp, true); // Cleanup if possible.
throw new \Exception(sprintf(__('Unable to delete dir: `%1$s`.', SLUG_TD), $_path_name));
}
# $counter++; // Increment counter for each directory we delete. ~ NO don't do that here.
break; // Break switch handler.
default: // Something else that is totally unexpected here.
$this->tryErasingAllFilesDirsIn($cache_dir_tmp, true); // Cleanup if possible.
throw new \Exception(sprintf(__('Unexpected resource type: `%1$s`.', SLUG_TD), $_resource_type));
}
}
unset($_dir_regex_iteration, $_resource, $_resource_type, $_sub_path_name, $_path_name, $_lstat); // Housekeeping.
if (!rename($cache_dir_tmp, $cache_dir)) {
$this->tryErasingAllFilesDirsIn($cache_dir_tmp, true); // Cleanup if possible.
throw new \Exception(sprintf(__('Unable to delete files. Rename failure on tmp directory: `%1$s`.', SLUG_TD), $cache_dir_tmp));
}
/* ------- End lock state... ------------- */
$this->cacheUnlock($cache_lock); // Release.
return $counter;
}
/**
* Delete files from the cache directory (for the current host);
* i.e., those that match a specific regex pattern.
*
* @since 150422 Rewrite. Updated 151002 w/ multisite compat. improvements.
*
* @param string $regex A `/[regex pattern]/`; relative to the host cache directory.
* e.g. `/^my\-slug(?:\/index)?(?:\.|\/(?:page\/[0-9]+|comment\-page\-[0-9]+)[.\/])/`
*
* Or, this can also be a full/absolute regex pattern against an absolute path;
* provided that it always starts with `/^`; including the full absolute cache/host directory path.
* e.g. `/^\/cache\/dir\/http\/example\.com\/my\-slug(?:\/index)?(?:\.|\/(?:page\/[0-9]+|comment\-page\-[0-9]+)[.\/])/`
* @param bool $check_max_age Check max age? i.e., use purge behavior?
* @param bool $___considering_domain_mapping For internal use only.
* @param bool $___consider_domain_mapping_host_token For internal use only.
* @param bool $___consider_domain_mapping_host_base_dir_tokens For internal use only.
*
* @throws \Exception If unable to delete a file for any reason.
* @return int Total files deleted by this routine (if any).
*
*/
public function deleteFilesFromHostCacheDir(
$regex,
$check_max_age = false,
$___considering_domain_mapping = false,
$___consider_domain_mapping_host_token = null,
$___consider_domain_mapping_host_base_dir_tokens = null
) {
$counter = 0; // Initialize.
if (!($regex = (string) $regex)) {
return $counter; // Nothing to do.
}
if (!is_dir($cache_dir = $this->cacheDir())) {
return $counter; // Nothing to do.
}
$cache_dir = $this->nDirSeps($cache_dir); // Normalize.
$host_token = $current_host_token = $this->hostToken();
$host_base_dir_tokens = $current_host_base_dir_tokens = $this->hostBaseDirTokens();
if ($___considering_domain_mapping && isset($___consider_domain_mapping_host_token, $___consider_domain_mapping_host_base_dir_tokens)) {
$host_token = (string) $___consider_domain_mapping_host_token;
$host_base_dir_tokens = (string) $___consider_domain_mapping_host_base_dir_tokens;
}
if (!$host_token) { // Must have a host in the sub-routine below.
throw new \Exception(__('Invalid argument; host token empty!', SLUG_TD));
}
if ($check_max_age && $this->isAdvancedCache()) {
throw new \Exception(__('Invalid argument; isAdvancedCache!', SLUG_TD));
}
if ($check_max_age && !($max_age = strtotime('-'.$this->options['cache_max_age']))) {
return $counter; // Invalid cache expiration time.
}
/* ------- Begin lock state... ----------- */
$cache_lock = $this->cacheLock(); // Lock cache writes.
clearstatcache(); // Clear stat cache to be sure we have a fresh start below.
foreach (['http', 'https'] as $_host_scheme) {
$_host_url = $_host_scheme.'://'.$host_token.$host_base_dir_tokens;
$_host_cache_path_flags = $this::CACHE_PATH_NO_PATH_INDEX | $this::CACHE_PATH_NO_QUV | $this::CACHE_PATH_NO_EXT;
$_host_cache_path = $this->buildCachePath($_host_url, '', '', $_host_cache_path_flags);
$_host_cache_dir = $this->nDirSeps($cache_dir.'/'.$_host_cache_path); // Normalize.
if (!$_host_cache_dir || !is_dir($_host_cache_dir)) {
// On a multisite install this may have a cache sub-directory.
// e.g., `http/example-com[[-base]-child1][[/base]/child1]` instead of `http/example-com`.
continue; // Nothing to do.
}
$_host_cache_dir_tmp = $this->addTmpSuffix($_host_cache_dir); // Temporary directory.
$_host_cache_dir_tmp_regex = $regex; // Initialize host-specific regex pattern for the tmp directory.
$_host_cache_dir_tmp_regex = '\\/'.ltrim($_host_cache_dir_tmp_regex, '^\\/'); // Make sure it begins with an escaped `/`.
$_host_cache_dir_tmp_regex = $this->strIreplaceOnce(preg_quote($_host_cache_path.'/', '/'), '', $_host_cache_dir_tmp_regex);
$_host_cache_dir_tmp_regex = $this->strIreplaceOnce(preg_quote($_host_cache_dir.'/', '/'), '', $_host_cache_dir_tmp_regex);
$_host_cache_dir_tmp_regex = ltrim($_host_cache_dir_tmp_regex, '^\\/');
if (strpos($_host_cache_dir_tmp_regex, '(?:\/') === 0 || strpos($_host_cache_dir_tmp_regex, '(\/') === 0) {
$_host_cache_dir_tmp_regex = '/^'.preg_quote($_host_cache_dir_tmp, '/').$_host_cache_dir_tmp_regex;
} else {
$_host_cache_dir_tmp_regex = '/^'.preg_quote($_host_cache_dir_tmp.'/', '/').$_host_cache_dir_tmp_regex;
}
#if(WP_DEBUG) file_put_contents(WP_CONTENT_DIR.'/'.strtolower(SHORT_NAME).'-debug.log', print_r($regex, TRUE)."\n".print_r($_host_cache_dir_tmp_regex, TRUE)."\n\n", FILE_APPEND);
// Uncomment the above line to debug regex pattern matching used by this routine; and others that call upon it.
if (!rename($_host_cache_dir, $_host_cache_dir_tmp)) {
throw new \Exception(sprintf(__('Unable to delete files. Rename failure on tmp directory: `%1$s`.', SLUG_TD), $_host_cache_dir));
}
foreach (($_dir_regex_iteration = $this->dirRegexIteration($_host_cache_dir_tmp, $_host_cache_dir_tmp_regex)) as $_resource) {
$_resource_type = $_resource->getType();
$_sub_path_name = $_resource->getSubpathname();
$_path_name = $_resource->getPathname();
if ($_host_cache_dir === $cache_dir && $_resource_type !== 'dir' && strpos($_sub_path_name, '/') === false) {
continue; // Don't delete links/files in the immediate directory; e.g. `[SHORT_NAME]-advanced-cache` or `.htaccess`, etc.
// Actual `http|https/...` cache links/files are nested. Links/files in the immediate directory are for other purposes.
}
switch ($_resource_type) {// Based on type; i.e., `link`, `file`, `dir`.
case 'link': // Symbolic links; i.e., 404 errors.
if ($check_max_age && !empty($max_age) && is_file($_resource->getLinkTarget())) {
if (($_lstat = lstat($_path_name)) && !empty($_lstat['mtime'])) {
if ($_lstat['mtime'] >= $max_age) {
break; // Break switch.
}
}
}
if (!unlink($_path_name)) {
$this->tryErasingAllFilesDirsIn($_host_cache_dir_tmp, true); // Cleanup if possible.
throw new \Exception(sprintf(__('Unable to delete symlink: `%1$s`.', SLUG_TD), $_path_name));
}
++$counter; // Increment counter for each link we delete.
break; // Break switch handler.
case 'file': // Regular files; i.e., not symlinks.
if ($check_max_age && !empty($max_age)) {
if ($_resource->getMTime() >= $max_age) {
break; // Break switch handler.
}
}
if (!unlink($_path_name)) {
$this->tryErasingAllFilesDirsIn($_host_cache_dir_tmp, true); // Cleanup if possible.
throw new \Exception(sprintf(__('Unable to delete file: `%1$s`.', SLUG_TD), $_path_name));
}
++$counter; // Increment counter for each file we delete.
break; // Break switch handler.
case 'dir': // A regular directory; i.e., not a symlink.
if ($regex !== '/^.+/i') {
break; // Not deleting everything.
}
if ($check_max_age && !empty($max_age)) {
break; // Not deleting everything.
}
if (!rmdir($_path_name)) {
$this->tryErasingAllFilesDirsIn($_host_cache_dir_tmp, true); // Cleanup if possible.
throw new \Exception(sprintf(__('Unable to delete dir: `%1$s`.', SLUG_TD), $_path_name));
}
# $counter++; // Increment counter for each directory we delete. ~ NO don't do that here.
break; // Break switch handler.
default: // Something else that is totally unexpected here.
$this->tryErasingAllFilesDirsIn($_host_cache_dir_tmp, true); // Cleanup if possible.
throw new \Exception(sprintf(__('Unexpected resource type: `%1$s`.', SLUG_TD), $_resource_type));
}
}
unset($_dir_regex_iteration, $_resource, $_resource_type, $_sub_path_name, $_path_name, $_lstat); // Housekeeping.
if (!rename($_host_cache_dir_tmp, $_host_cache_dir)) {
$this->tryErasingAllFilesDirsIn($_host_cache_dir_tmp, true); // Cleanup if possible.
throw new \Exception(sprintf(__('Unable to delete files. Rename failure on tmp directory: `%1$s`.', SLUG_TD), $_host_cache_dir_tmp));
}
}
unset($_host_scheme, $_host_url, $_host_cache_path_flags, $_host_cache_path, $_host_cache_dir, $_host_cache_dir_tmp, $_host_cache_dir_tmp_regex);
/* ------- End lock state... ------------- */
$this->cacheUnlock($cache_lock); // Release.
/* ------- Include domain mapping variations also. ------- */
if (!$___considering_domain_mapping && is_multisite() && $this->canConsiderDomainMapping()) {
$domain_mapping_variations = []; // Initialize array of domain variations.
if (($_host_token_for_blog = $this->hostTokenForBlog())) {
$_host_base_dir_tokens_for_blog = $this->hostBaseDirTokensForBlog();
$domain_mapping_variations[] = ['host_token' => $_host_token_for_blog, 'host_base_dir_tokens' => $_host_base_dir_tokens_for_blog];
} // The original blog host; i.e., without domain mapping.
unset($_host_token_for_blog, $_host_base_dir_tokens_for_blog); // Housekeeping.
foreach ($this->domainMappingBlogDomains() as $_domain_mapping_blog_domain) {
if (($_domain_host_token_for_blog = $this->hostTokenForBlog(false, true, $_domain_mapping_blog_domain))) {
$_domain_host_base_dir_tokens_for_blog = $this->hostBaseDirTokensForBlog(false, true); // This is only a formality.
$domain_mapping_variations[] = ['host_token' => $_domain_host_token_for_blog, 'host_base_dir_tokens' => $_domain_host_base_dir_tokens_for_blog];
}
} // This includes all of the domain mappings configured for the current blog ID.
unset($_domain_mapping_blog_domain, $_domain_host_token_for_blog, $_domain_host_base_dir_tokens_for_blog); // Housekeeping.
foreach ($domain_mapping_variations as $_domain_mapping_variation) {
if ($_domain_mapping_variation['host_token'] === $current_host_token && $_domain_mapping_variation['host_base_dir_tokens'] === $current_host_base_dir_tokens) {
continue; // Exclude current tokens. They were already iterated above.
}
$counter += $this->deleteFilesFromHostCacheDir($regex, $check_max_age, true, $_domain_mapping_variation['host_token'], $_domain_mapping_variation['host_base_dir_tokens']);
}
unset($_domain_mapping_variation); // Housekeeping.
}
return $counter;
}
/**
* Delete all files/dirs from a directory (for all schemes/hosts);
* including `[SHORT_NAME]-` prefixed files; or anything else for that matter.
*
* @since 150422 Rewrite. Updated 151002 w/ multisite compat. improvements.
*
* @param string $dir The directory from which to delete files/dirs.
*
* SECURITY: This directory MUST be located inside the `/wp-content/` directory.
* Also, it MUST be a sub-directory of `/wp-content/`, NOT the directory itself.
* Also, it cannot be: `mu-plugins`, `themes`, or `plugins`.
* @param bool $delete_dir_too Delete parent? i.e., delete the `$dir` itself also?
*
* @throws \Exception If unable to delete a file/directory for any reason.
* @return int Total files/directories deleted by this routine (if any).
*
*/
public function deleteAllFilesDirsIn($dir, $delete_dir_too = false)
{
$counter = 0; // Initialize.
if (!($dir = trim((string) $dir)) || !is_dir($dir)) {
return $counter; // Nothing to do.
}
$dir = $this->nDirSeps($dir);
$dir_temp = $this->addTmpSuffix($dir);
$wp_content_dir = $this->nDirSeps(WP_CONTENT_DIR);
$wp_content_dir_regex = preg_quote($wp_content_dir, '/');
if (!preg_match('/^'.$wp_content_dir_regex.'\/[^\/]+/i', $dir)) {
return $counter; // Security flag; do nothing in this case.
}
if (preg_match('/^'.$wp_content_dir_regex.'\/(?:mu\-plugins|themes|plugins)(?:\/|$)/i', $dir)) {
return $counter; // Security flag; do nothing in this case.
}
/* ------- Begin lock state... ----------- */
$cache_lock = $this->cacheLock(); // Lock cache writes.
clearstatcache(); // Clear stat cache to be sure we have a fresh start below.
if (!rename($dir, $dir_temp)) {
throw new \Exception(sprintf(__('Unable to delete all files/dirs. Rename failure on tmp directory: `%1$s`.', SLUG_TD), $dir));
}
foreach (($_dir_regex_iteration = $this->dirRegexIteration($dir_temp, '/.+/')) as $_resource) {
$_resource_type = $_resource->getType();
$_sub_path_name = $_resource->getSubpathname();
$_path_name = $_resource->getPathname();
switch ($_resource_type) {// Based on type; i.e., `link`, `file`, `dir`.
case 'link': // Symbolic links; i.e., 404 errors.
if (!unlink($_path_name)) {
$this->tryErasingAllFilesDirsIn($dir_temp, true); // Cleanup if possible.
throw new \Exception(sprintf(__('Unable to delete symlink: `%1$s`.', SLUG_TD), $_path_name));
}
++$counter; // Increment counter for each link we delete.
break; // Break switch handler.
case 'file': // Regular files; i.e., not symlinks.
if (!unlink($_path_name)) {
$this->tryErasingAllFilesDirsIn($dir_temp, true); // Cleanup if possible.
throw new \Exception(sprintf(__('Unable to delete file: `%1$s`.', SLUG_TD), $_path_name));
}
++$counter; // Increment counter for each file we delete.
break; // Break switch handler.
case 'dir': // A regular directory; i.e., not a symlink.
if (!rmdir($_path_name)) {
$this->tryErasingAllFilesDirsIn($dir_temp, true); // Cleanup if possible.
throw new \Exception(sprintf(__('Unable to delete dir: `%1$s`.', SLUG_TD), $_path_name));
}
# ++$counter; // Increment counter for each directory we delete. ~ NO don't do that here.
break; // Break switch handler.
default: // Something else that is totally unexpected here.
$this->tryErasingAllFilesDirsIn($dir_temp, true); // Cleanup if possible.
throw new \Exception(sprintf(__('Unexpected resource type: `%1$s`.', SLUG_TD), $_resource_type));
}
}
unset($_dir_regex_iteration, $_resource, $_resource_type, $_sub_path_name, $_path_name); // Housekeeping.
if (!rename($dir_temp, $dir)) {
$this->tryErasingAllFilesDirsIn($dir_temp, true); // Cleanup if possible.
throw new \Exception(sprintf(__('Unable to delete all files/dirs. Rename failure on tmp directory: `%1$s`.', SLUG_TD), $dir_temp));
}
if ($delete_dir_too) {
if (!rmdir($dir)) {
throw new \Exception(sprintf(__('Unable to delete directory: `%1$s`.', SLUG_TD), $dir));
}
++$counter; // Increment counter for each directory we delete.
}
/* ------- End lock state... ------------- */
$this->cacheUnlock($cache_lock); // Release.
return $counter;
}
/**
* Erase all files/dirs from a directory (for all schemes/hosts);
* including `[SHORT_NAME]-` prefixed files; or anything else for that matter.
*
* WARNING: This does NO LOCKING and NO ATOMIC deletions.
*
* @since 150821 Improving recovery under stress.
*
* @param string $dir The directory from which to erase files/dirs.
*
* SECURITY: This directory MUST be located inside the `/wp-content/` directory.
* Also, it MUST be a sub-directory of `/wp-content/`, NOT the directory itself.
* Also, it cannot be: `mu-plugins`, `themes`, or `plugins`.
* @param bool $erase_dir_too Erase parent? i.e., erase the `$dir` itself also?
*
* @throws \Exception If unable to erase a file/directory for any reason.
* @return int Total files/directories erased by this routine (if any).
*
*/
public function eraseAllFilesDirsIn($dir, $erase_dir_too = false)
{
$counter = 0; // Initialize.
if (!($dir = trim((string) $dir)) || !is_dir($dir)) {
return $counter; // Nothing to do.
}
$dir = $this->nDirSeps($dir);
$wp_content_dir = $this->nDirSeps(WP_CONTENT_DIR);
$wp_content_dir_regex = preg_quote($wp_content_dir, '/');
if (!preg_match('/^'.$wp_content_dir_regex.'\/[^\/]+/i', $dir)) {
return $counter; // Security flag; do nothing in this case.
}
if (preg_match('/^'.$wp_content_dir_regex.'\/(?:mu\-plugins|themes|plugins)(?:\/|$)/i', $dir)) {
return $counter; // Security flag; do nothing in this case.
}
clearstatcache(); // Clear stat cache to be sure we have a fresh start below.
foreach (($_dir_regex_iteration = $this->dirRegexIteration($dir, '/.+/')) as $_resource) {
$_resource_type = $_resource->getType();
$_sub_path_name = $_resource->getSubpathname();
$_path_name = $_resource->getPathname();
switch ($_resource_type) {// Based on type; i.e., `link`, `file`, `dir`.
case 'link': // Symbolic links; i.e., 404 errors.
if (!unlink($_path_name)) {
throw new \Exception(sprintf(__('Unable to erase symlink: `%1$s`.', SLUG_TD), $_path_name));
}
++$counter; // Increment counter for each link we erase.
break; // Break switch handler.
case 'file': // Regular files; i.e., not symlinks.
if (!unlink($_path_name)) {
throw new \Exception(sprintf(__('Unable to erase file: `%1$s`.', SLUG_TD), $_path_name));
}
++$counter; // Increment counter for each file we erase.
break; // Break switch handler.
case 'dir': // A regular directory; i.e., not a symlink.
if (!rmdir($_path_name)) {
throw new \Exception(sprintf(__('Unable to erase dir: `%1$s`.', SLUG_TD), $_path_name));
}
# ++$counter; // Increment counter for each directory we erase. ~ NO don't do that here.
break; // Break switch handler.
default: // Something else that is totally unexpected here.
throw new \Exception(sprintf(__('Unexpected resource type: `%1$s`.', SLUG_TD), $_resource_type));
}
}
unset($_dir_regex_iteration, $_resource, $_resource_type, $_sub_path_name, $_path_name); // Housekeeping.
if ($erase_dir_too) {
if (!rmdir($dir)) {
throw new \Exception(sprintf(__('Unable to erase directory: `%1$s`.', SLUG_TD), $dir));
}
++$counter; // Increment counter for each directory we erase.
}
return $counter;
}
/**
* Try to erase all files/dirs from a directory (for all schemes/hosts);
* including `[SHORT_NAME]-` prefixed files; or anything else for that matter.
*
* WARNING: This does NO LOCKING and NO ATOMIC deletions.
*
* @since 150821 Improving recovery under stress.
*
* @param string $dir The directory from which to erase files/dirs.
*
* SECURITY: This directory MUST be located inside the `/wp-content/` directory.
* Also, it MUST be a sub-directory of `/wp-content/`, NOT the directory itself.
* Also, it cannot be: `mu-plugins`, `themes`, or `plugins`.
* @param bool $erase_dir_too Erase parent? i.e., erase the `$dir` itself also?
*
* @return int Total files/directories erased by this routine (if any).
*/
public function tryErasingAllFilesDirsIn($dir, $erase_dir_too = false)
{
$counter = 0; // Initialize counter.
try {
$counter += $this->eraseAllFilesDirsIn($dir, $erase_dir_too);
} catch (\Exception $exception) {
// Fail softly.
}
return $counter;
}
}