Skip to content

Commit 22afa4b

Browse files
committed
fix(Cache): delete hidden cache entries in the File handler
A cache key may begin with a period, so save() writes a hidden cache file. clean() called delete_files() without $hidden, getCacheInfo() used a helper that always skipped dot-leading names, and deleteMatching() used FNM_PERIOD. Such an entry was not listed by getCacheInfo() nor bulk-removed by clean() or deleteMatching(), so cache:clear left it in place permanently. - clean(): pass $hidden = true. .htaccess, index.* and web.config stay protected by $htdocs. - getCacheInfo(): add an optional $hidden parameter to get_dir_file_info(), keep its default behavior, and include hidden files. - deleteMatching(): drop FNM_PERIOD so wildcards match dot-leading entries, and skip the .htaccess protection file case-insensitively. The user guide and the 4.7.7 changelog describe the new behavior.
1 parent 53e4148 commit 22afa4b

8 files changed

Lines changed: 208 additions & 18 deletions

File tree

‎docs/changelogs/v4.7.7.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ Release Date: Unreleased
2222

2323
- **API:** Fixed HTTP 500 errors in `ResponseTrait::paginate()` when using a Query Builder with a very large page number or `$perPage = 0`.
2424
- **Cache:** Fixed a bug where `PredisHandler::increment()` and `PredisHandler::decrement()` updated the unused `'data'` hash field instead of `'__ci_value'`, causing `get()` to return stale values for existing counters.
25+
- **Cache:** Fixed a bug where the File handler skipped cache entries whose key begins with a period in `clean()`, `getCacheInfo()` and `deleteMatching()`. Such entries were not listed by `getCacheInfo()` and were not removed by `clean()` or `deleteMatching()`, so `cache:clear` left them in place. `deleteMatching()` wildcard patterns now also match these entries, while the `.htaccess` protection file is still skipped.
2526
- **CORS:** Fixed a bug where `Cors::hasResponseHeaders()` matched header substrings via `str_contains()`, causing false positives when existing exposed headers shared a prefix with configured exposed headers.
2627
- **Database:** Fixed a bug where `BaseConnection::prepare()` did not reset pretend mode when the closure threw an exception, leaving the connection in pretend mode so that subsequent queries on it were silently discarded.
2728
- **Database:** Fixed a bug where `Postgre`, `OCI8`, and `SQLSRV` `Forge::_dropKeyAsConstraint()` interpolated table, constraint, and schema names without escaping.

‎docs/helpers/filesystem_helper.md‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -216,11 +216,15 @@ Example:
216216
$controllers = get_filenames(APPPATH . 'Controllers/');
217217
```
218218

219-
#### get_dir_file_info($sourceDir[, $topLevelOnly = true])
219+
#### get_dir_file_info($sourceDir[, $topLevelOnly = true[, $recursion = false[, $hidden = false]]])
220220

221221
- **Parameters**
222222
- **$sourceDir** `string` Directory path
223223
- **$topLevelOnly** `bool` Whether to look only at the specified directory (excluding sub-directories)
224+
- **$recursion** `bool` Whether to recurse into sub-directories. For internal use; do not pass it from application code.
225+
- **$hidden** `bool` Whether to include hidden files (files beginning with a period)
226+
227+
> **Note:** `$recursion` is an internal parameter and should not be passed by callers. When you need hidden files, use the named argument, e.g. `get_dir_file_info($sourceDir, hidden: true)`.
224228
225229
- **Returns**: An array containing info on the supplied directory's contents
226230

‎docs/libraries/caching.md‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ $key = 'search_' . hash('sha256', $userInput);
7070

7171
This is an array of settings specific to the **File** handler to determine how it should save the cache files.
7272

73-
Cache files whose names start with a dot are not fully supported by the File handler: `getCacheInfo()` does not report them, `deleteMatching()` wildcard patterns do not match them, and `clean()` / `cache:clear` do not delete them. Avoid keys and prefixes that produce a leading dot.
73+
Dot-leading cache keys are supported by the File handler: they are reported by `getCacheInfo()`, matched by `deleteMatching()`, and removed by `clean()` / `cache:clear`. The `.htaccess` protection file is never deleted by `deleteMatching()`, and the protection files (`.htaccess`, `index.html`, `index.htm`, `index.php`, `web.config`) are kept by `clean()`; any other dot-leading file in the cache directory is affected. See the notes below `deleteMatching()`, `clean()` and `getCacheInfo()`.
7474

7575
### $memcached
7676

@@ -201,7 +201,7 @@ This method will delete multiple items from the cache store at once by matching
201201
This method is only implemented for the File, Redis and Predis handlers. Due to limitations, it couldn't be implemented for the Memcached and Wincache handlers.
202202

203203
!!! note "Note"
204-
With the File handler, the pattern is matched against cache file names only and cannot match files in subdirectories. A pattern containing a forward slash (`/`) therefore never matches.
204+
With the File handler, the pattern is matched against cache file names only and cannot match files in subdirectories. A pattern containing a forward slash (`/`) therefore never matches. A cache entry whose key begins with a period (a dot-leading file name) is matched by patterns like any other entry, but the `.htaccess` protection file is never deleted. Any other dot-leading file in the cache directory (for example `.gitignore` or `.env`) is matched as well.
205205

206206
Example:
207207

@@ -276,6 +276,9 @@ Example:
276276
$cache->clean();
277277
```
278278

279+
!!! note "Note"
280+
The File handler also deletes cache entries whose key begins with a period, while the `.htaccess`, `index.html`, `index.htm`, `index.php` and `web.config` files are kept. Any other dot-leading file in the cache directory or its subdirectories (for example `.gitignore`, `.env` or `.user.ini`) is deleted as well.
281+
279282
#### getCacheInfo()
280283

281284
- **Returns**: Information on the entire cache database
@@ -294,6 +297,9 @@ var_dump($cache->getCacheInfo());
294297
!!! note "Note"
295298
The information returned and the structure of the data are dependent on which adapter is being used.
296299

300+
!!! note "Note"
301+
The File handler also reports dot-leading files in the cache directory, including the `.htaccess` protection file.
302+
297303
#### getMetadata(string $key)
298304

299305
- **Parameters**

‎system/Cache/Handlers/FileHandler.php‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -162,8 +162,12 @@ public function deleteMatching(string $pattern): int
162162
$deleted = 0;
163163

164164
foreach ($iterator as $file) {
165-
// FNM_PERIOD keeps glob() semantics: wildcards don't match a leading dot.
166-
if (! fnmatch($pattern, $file->getFilename(), FNM_PERIOD)) {
165+
$filename = $file->getFilename();
166+
167+
// A dot-leading file name is a legal cache entry, so wildcards must
168+
// match it. `.htaccess` protects the cache directory and is never a
169+
// cache entry, so it must never be deleted.
170+
if (strcasecmp($filename, '.htaccess') === 0 || ! fnmatch($pattern, $filename)) {
167171
continue;
168172
}
169173

@@ -202,12 +206,12 @@ public function decrement(string $key, int $offset = 1): bool|int
202206

203207
public function clean(): bool
204208
{
205-
return delete_files($this->path, false, true);
209+
return delete_files($this->path, htdocs: true, hidden: true);
206210
}
207211

208212
public function getCacheInfo(): array
209213
{
210-
return get_dir_file_info($this->path);
214+
return get_dir_file_info($this->path, hidden: true);
211215
}
212216

213217
public function getMetaData(string $key): ?array

‎system/Helpers/filesystem_helper.php‎

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -258,6 +258,7 @@ function get_filenames(
258258
* @param string $sourceDir Path to source
259259
* @param bool $topLevelOnly Look only at the top level directory specified?
260260
* @param bool $recursion Internal variable to determine recursion status - do not use in calls
261+
* @param bool $hidden Whether to include hidden files (files beginning with a period)
261262
*
262263
* @return array<string, array{
263264
* name: string,
@@ -267,7 +268,7 @@ function get_filenames(
267268
* relative_path: string,
268269
* }>
269270
*/
270-
function get_dir_file_info(string $sourceDir, bool $topLevelOnly = true, bool $recursion = false): array
271+
function get_dir_file_info(string $sourceDir, bool $topLevelOnly = true, bool $recursion = false, bool $hidden = false): array
271272
{
272273
static $fileData = [];
273274
$relativePath = $sourceDir;
@@ -283,9 +284,17 @@ function get_dir_file_info(string $sourceDir, bool $topLevelOnly = true, bool $r
283284

284285
// Used to be foreach (scandir($sourceDir, 1) as $file), but scandir() is simply not as fast
285286
while (false !== ($file = readdir($fp))) {
286-
if (is_dir($sourceDir . $file) && $file[0] !== '.' && $topLevelOnly === false) {
287-
get_dir_file_info($sourceDir . $file . DIRECTORY_SEPARATOR, $topLevelOnly, true);
288-
} elseif ($file[0] !== '.') {
287+
if ($file === '.' || $file === '..') {
288+
continue;
289+
}
290+
291+
if (! $hidden && $file[0] === '.') {
292+
continue;
293+
}
294+
295+
if (is_dir($sourceDir . $file) && $topLevelOnly === false) {
296+
get_dir_file_info($sourceDir . $file . DIRECTORY_SEPARATOR, $topLevelOnly, true, $hidden);
297+
} else {
289298
$info = get_file_info($sourceDir . $file);
290299
if ($info !== null) {
291300
$fileData[$file] = $info;

‎tests/system/Cache/Handlers/FileHandlerTest.php‎

Lines changed: 100 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -327,24 +327,117 @@ public function testDeleteMatchingTreatsCachePathLiterally(): void
327327
}
328328
}
329329

330-
public function testDeleteMatchingWildcardDoesNotMatchHiddenFiles(): void
330+
public function testDeleteMatchingWildcardMatchesHiddenEntries(): void
331331
{
332-
$hidden = $this->config->file['storePath'] . '/.hidden';
332+
$this->assertTrue($this->handler->save('.hidden', 'value'));
333+
$this->assertTrue($this->handler->save(self::$key1, 'value'));
334+
335+
$this->assertSame(2, $this->handler->deleteMatching('*'));
336+
$this->assertNull($this->handler->get('.hidden'));
337+
$this->assertNull($this->handler->get(self::$key1));
338+
}
339+
340+
public function testDeleteMatchingMatchesExplicitDotPattern(): void
341+
{
342+
$this->assertTrue($this->handler->save('.hidden', 'value'));
343+
$this->assertTrue($this->handler->save(self::$key1, 'value'));
344+
345+
$this->assertSame(1, $this->handler->deleteMatching('.hid*'));
346+
$this->assertNull($this->handler->get('.hidden'));
347+
$this->assertSame('value', $this->handler->get(self::$key1));
348+
}
333349

334-
$this->assertNotFalse(file_put_contents($hidden, 'data'));
350+
#[DataProvider('provideDeleteMatchingDoesNotDeleteHtaccess')]
351+
public function testDeleteMatchingDoesNotDeleteHtaccess(string $protectionFile): void
352+
{
353+
$path = $this->config->file['storePath'] . DIRECTORY_SEPARATOR . $protectionFile;
335354

336355
try {
337-
$this->assertTrue($this->handler->save(self::$key1, 'value'));
356+
$this->assertNotFalse(file_put_contents($path, 'Deny from all'));
357+
$this->assertTrue($this->handler->save('.hidden', 'value'));
338358

339359
$this->assertSame(1, $this->handler->deleteMatching('*'));
340-
$this->assertFileExists($hidden);
360+
$this->assertFileExists($path);
361+
$this->assertNull($this->handler->get('.hidden'));
341362
} finally {
342-
if (is_file($hidden)) {
343-
unlink($hidden);
363+
if (is_file($path)) {
364+
unlink($path);
344365
}
345366
}
346367
}
347368

369+
/**
370+
* @return iterable<string, array{string}>
371+
*/
372+
public static function provideDeleteMatchingDoesNotDeleteHtaccess(): iterable
373+
{
374+
yield 'lowercase' => ['.htaccess'];
375+
376+
yield 'uppercase' => ['.HTACCESS'];
377+
378+
yield 'mixed case' => ['.HtAccess'];
379+
}
380+
381+
public function testCleanDeletesHiddenEntries(): void
382+
{
383+
$path = $this->config->file['storePath'] . DIRECTORY_SEPARATOR . '.hidden';
384+
385+
$this->assertTrue($this->handler->save('.hidden', 'value'));
386+
$this->assertFileExists($path);
387+
388+
$this->assertTrue($this->handler->clean());
389+
$this->assertFileDoesNotExist($path);
390+
$this->assertNull($this->handler->get('.hidden'));
391+
}
392+
393+
public function testCleanKeepsProtectionFiles(): void
394+
{
395+
$protectionFiles = ['.htaccess', 'index.html', 'index.htm', 'index.php', 'web.config'];
396+
397+
try {
398+
foreach ($protectionFiles as $protectionFile) {
399+
$this->assertNotFalse(
400+
file_put_contents(
401+
$this->config->file['storePath'] . DIRECTORY_SEPARATOR . $protectionFile,
402+
'',
403+
),
404+
);
405+
}
406+
407+
$this->assertTrue($this->handler->save(self::$key1, 'value'));
408+
$this->assertTrue($this->handler->save('.hidden', 'value'));
409+
410+
$this->assertTrue($this->handler->clean());
411+
$this->assertNull($this->handler->get(self::$key1));
412+
$this->assertNull($this->handler->get('.hidden'));
413+
414+
foreach ($protectionFiles as $protectionFile) {
415+
$this->assertFileExists($this->config->file['storePath'] . DIRECTORY_SEPARATOR . $protectionFile);
416+
}
417+
} finally {
418+
foreach ($protectionFiles as $protectionFile) {
419+
$path = $this->config->file['storePath'] . DIRECTORY_SEPARATOR . $protectionFile;
420+
421+
if (is_file($path)) {
422+
unlink($path);
423+
}
424+
}
425+
}
426+
}
427+
428+
public function testGetCacheInfoReportsHiddenEntries(): void
429+
{
430+
$this->assertTrue($this->handler->save('.hidden', 'value'));
431+
432+
$info = $this->handler->getCacheInfo();
433+
434+
$this->assertArrayHasKey('.hidden', $info);
435+
$this->assertSame('.hidden', $info['.hidden']['name']);
436+
$this->assertArrayHasKey('server_path', $info['.hidden']);
437+
$this->assertArrayNotHasKey('.', $info);
438+
$this->assertArrayNotHasKey('..', $info);
439+
}
440+
348441
public function testIncrement(): void
349442
{
350443
$this->handler->save(self::$key1, 1);

‎tests/system/Commands/Cache/ClearCacheTest.php‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,16 @@ public function testClearCacheWorks(): void
111111
$this->assertStringContainsString('Cache cleared.', $this->getStreamFilterBuffer());
112112
}
113113

114+
public function testClearCacheRemovesHiddenEntries(): void
115+
{
116+
cache()->save('.hidden', 'bar');
117+
$this->assertSame('bar', cache('.hidden'));
118+
119+
command('cache:clear');
120+
121+
$this->assertNull(cache('.hidden'));
122+
}
123+
114124
public function testClearCacheDiscardsSharedLocatorCache(): void
115125
{
116126
$handler = $this->getIsolatedCacheHandler();

‎tests/system/Helpers/FilesystemHelperTest.php‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -497,6 +497,69 @@ public function testGetDirFileInfoIgnoresDirectoriesWhenTopLevelOnlyIsTrue(): vo
497497
$this->assertArrayNotHasKey('subdir', $result);
498498
}
499499

500+
public function testGetDirFileInfoSkipsHiddenFilesByDefault(): void
501+
{
502+
$dir = WRITEPATH . 'test_get_dir_file_info_hidden_' . bin2hex(random_bytes(4));
503+
504+
$this->assertTrue(mkdir($dir, 0777, true));
505+
$this->assertNotFalse(file_put_contents($dir . '/file.txt', 'visible'));
506+
$this->assertNotFalse(file_put_contents($dir . '/.hidden', 'hidden'));
507+
508+
try {
509+
$result = get_dir_file_info($dir, true);
510+
511+
$this->assertArrayHasKey('file.txt', $result);
512+
$this->assertArrayNotHasKey('.hidden', $result);
513+
} finally {
514+
unlink($dir . '/file.txt');
515+
unlink($dir . '/.hidden');
516+
rmdir($dir);
517+
}
518+
}
519+
520+
public function testGetDirFileInfoIncludesHiddenFiles(): void
521+
{
522+
$dir = WRITEPATH . 'test_get_dir_file_info_hidden_' . bin2hex(random_bytes(4));
523+
524+
$this->assertTrue(mkdir($dir, 0777, true));
525+
$this->assertNotFalse(file_put_contents($dir . '/file.txt', 'visible'));
526+
$this->assertNotFalse(file_put_contents($dir . '/.hidden', 'hidden'));
527+
528+
try {
529+
$result = get_dir_file_info($dir, true, false, true);
530+
531+
$this->assertArrayHasKey('file.txt', $result);
532+
$this->assertArrayHasKey('.hidden', $result);
533+
$this->assertSame('.hidden', $result['.hidden']['name']);
534+
$this->assertArrayNotHasKey('.', $result);
535+
$this->assertArrayNotHasKey('..', $result);
536+
} finally {
537+
unlink($dir . '/file.txt');
538+
unlink($dir . '/.hidden');
539+
rmdir($dir);
540+
}
541+
}
542+
543+
public function testGetDirFileInfoIncludesHiddenDirectoryRecursively(): void
544+
{
545+
$dir = WRITEPATH . 'test_get_dir_file_info_hidden_' . bin2hex(random_bytes(4));
546+
547+
$this->assertTrue(mkdir($dir . '/.sub', 0777, true));
548+
$this->assertNotFalse(file_put_contents($dir . '/.sub/inner.txt', 'inner'));
549+
550+
try {
551+
$withHidden = get_dir_file_info($dir, false, false, true);
552+
$this->assertArrayHasKey('inner.txt', $withHidden);
553+
554+
$withoutHidden = get_dir_file_info($dir, false);
555+
$this->assertArrayNotHasKey('inner.txt', $withoutHidden);
556+
} finally {
557+
unlink($dir . '/.sub/inner.txt');
558+
rmdir($dir . '/.sub');
559+
rmdir($dir);
560+
}
561+
}
562+
500563
public function testGetFileInfo(): void
501564
{
502565
$file = SUPPORTPATH . 'Files/baker/banana.php';

0 commit comments

Comments
 (0)