forked from codeigniter4/CodeIgniter4
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFileHandler.php
More file actions
440 lines (363 loc) · 11.8 KB
/
FileHandler.php
File metadata and controls
440 lines (363 loc) · 11.8 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
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
<?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Cache\Handlers;
use CodeIgniter\Cache\Exceptions\CacheException;
use CodeIgniter\I18n\Time;
use Config\Cache;
use Throwable;
/**
* File system cache handler
*
* @see \CodeIgniter\Cache\Handlers\FileHandlerTest
*/
class FileHandler extends BaseHandler
{
/**
* Maximum key length.
*/
public const MAX_KEY_LENGTH = 255;
/**
* Where to store cached files on the disk.
*
* @var string
*/
protected $path;
/**
* Mode for the stored files.
* Must be chmod-safe (octal).
*
* @var int
*
* @see https://www.php.net/manual/en/function.chmod.php
*/
protected $mode;
/**
* Note: Use `CacheFactory::getHandler()` to instantiate.
*
* @throws CacheException
*/
public function __construct(Cache $config)
{
$this->path = ! empty($config->file['storePath']) ? $config->file['storePath'] : WRITEPATH . 'cache';
$this->path = rtrim($this->path, '/') . '/';
if (! is_really_writable($this->path)) {
throw CacheException::forUnableToWrite($this->path);
}
$this->mode = $config->file['mode'] ?? 0640;
$this->prefix = $config->prefix;
helper('filesystem');
}
/**
* {@inheritDoc}
*/
public function initialize()
{
}
/**
* {@inheritDoc}
*/
public function get(string $key)
{
$key = static::validateKey($key, $this->prefix);
$data = $this->getItem($key);
return is_array($data) ? $data['data'] : null;
}
/**
* {@inheritDoc}
*/
public function save(string $key, $value, int $ttl = 60)
{
$key = static::validateKey($key, $this->prefix);
$contents = [
'time' => Time::now()->getTimestamp(),
'ttl' => $ttl,
'data' => $value,
];
if (write_file($this->path . $key, serialize($contents))) {
try {
chmod($this->path . $key, $this->mode);
// @codeCoverageIgnoreStart
} catch (Throwable $e) {
log_message('debug', 'Failed to set mode on cache file: ' . $e);
// @codeCoverageIgnoreEnd
}
return true;
}
return false;
}
/**
* {@inheritDoc}
*/
public function delete(string $key)
{
$key = static::validateKey($key, $this->prefix);
return is_file($this->path . $key) && unlink($this->path . $key);
}
/**
* {@inheritDoc}
*
* @return int
*/
public function deleteMatching(string $pattern)
{
$deleted = 0;
foreach (glob($this->path . $pattern, GLOB_NOSORT) as $filename) {
if (is_file($filename) && @unlink($filename)) {
$deleted++;
}
}
return $deleted;
}
/**
* {@inheritDoc}
*/
public function increment(string $key, int $offset = 1)
{
$prefixedKey = static::validateKey($key, $this->prefix);
$tmp = $this->getItem($prefixedKey);
if ($tmp === false) {
$tmp = ['data' => 0, 'ttl' => 60];
}
['data' => $value, 'ttl' => $ttl] = $tmp;
if (! is_int($value)) {
return false;
}
$value += $offset;
return $this->save($key, $value, $ttl) ? $value : false;
}
/**
* {@inheritDoc}
*/
public function decrement(string $key, int $offset = 1)
{
return $this->increment($key, -$offset);
}
/**
* {@inheritDoc}
*/
public function clean()
{
return delete_files($this->path, false, true);
}
/**
* {@inheritDoc}
*/
public function getCacheInfo()
{
return get_dir_file_info($this->path);
}
/**
* {@inheritDoc}
*/
public function getMetaData(string $key)
{
$key = static::validateKey($key, $this->prefix);
if (false === $data = $this->getItem($key)) {
return false; // @TODO This will return null in a future release
}
return [
'expire' => $data['ttl'] > 0 ? $data['time'] + $data['ttl'] : null,
'mtime' => filemtime($this->path . $key),
'data' => $data['data'],
];
}
/**
* {@inheritDoc}
*/
public function isSupported(): bool
{
return is_writable($this->path);
}
/**
* Does the heavy lifting of actually retrieving the file and
* verifying its age.
*
* @return array{data: mixed, ttl: int, time: int}|false
*/
protected function getItem(string $filename)
{
if (! is_file($this->path . $filename)) {
return false;
}
$content = @file_get_contents($this->path . $filename);
if ($content === false) {
return false;
}
try {
$data = unserialize($content);
} catch (Throwable) {
return false;
}
if (! is_array($data)) {
return false;
}
if (! isset($data['ttl']) || ! is_int($data['ttl'])) {
return false;
}
if (! isset($data['time']) || ! is_int($data['time'])) {
return false;
}
if ($data['ttl'] > 0 && Time::now()->getTimestamp() > $data['time'] + $data['ttl']) {
@unlink($this->path . $filename);
return false;
}
return $data;
}
/**
* Writes a file to disk, or returns false if not successful.
*
* @deprecated 4.6.1 Use `write_file()` instead.
*
* @param string $path
* @param string $data
* @param string $mode
*
* @return bool
*/
protected function writeFile($path, $data, $mode = 'wb')
{
if (($fp = @fopen($path, $mode)) === false) {
return false;
}
flock($fp, LOCK_EX);
$result = 0;
for ($written = 0, $length = strlen($data); $written < $length; $written += $result) {
if (($result = fwrite($fp, substr($data, $written))) === false) {
break;
}
}
flock($fp, LOCK_UN);
fclose($fp);
return is_int($result);
}
/**
* Deletes all files contained in the supplied directory path.
* Files must be writable or owned by the system in order to be deleted.
* If the second parameter is set to TRUE, any directories contained
* within the supplied base directory will be nuked as well.
*
* @deprecated 4.6.1 Use `delete_files()` instead.
*
* @param string $path File path
* @param bool $delDir Whether to delete any directories found in the path
* @param bool $htdocs Whether to skip deleting .htaccess and index page files
* @param int $_level Current directory depth level (default: 0; internal use only)
*/
protected function deleteFiles(string $path, bool $delDir = false, bool $htdocs = false, int $_level = 0): bool
{
// Trim the trailing slash
$path = rtrim($path, '/\\');
if (! $currentDir = @opendir($path)) {
return false;
}
while (false !== ($filename = @readdir($currentDir))) {
if ($filename !== '.' && $filename !== '..') {
if (is_dir($path . DIRECTORY_SEPARATOR . $filename) && $filename[0] !== '.') {
$this->deleteFiles($path . DIRECTORY_SEPARATOR . $filename, $delDir, $htdocs, $_level + 1);
} elseif (! $htdocs || preg_match('/^(\.htaccess|index\.(html|htm|php)|web\.config)$/i', $filename) !== 1) {
@unlink($path . DIRECTORY_SEPARATOR . $filename);
}
}
}
closedir($currentDir);
return ($delDir && $_level > 0) ? @rmdir($path) : true;
}
/**
* Reads the specified directory and builds an array containing the filenames,
* filesize, dates, and permissions
*
* Any sub-folders contained within the specified path are read as well.
*
* @deprecated 4.6.1 Use `get_dir_file_info()` instead.
*
* @param string $sourceDir Path to source
* @param bool $topLevelOnly Look only at the top level directory specified?
* @param bool $_recursion Internal variable to determine recursion status - do not use in calls
*
* @return array|false
*/
protected function getDirFileInfo(string $sourceDir, bool $topLevelOnly = true, bool $_recursion = false)
{
static $_filedata = [];
$relativePath = $sourceDir;
if ($fp = @opendir($sourceDir)) {
// reset the array and make sure $sourceDir has a trailing slash on the initial call
if ($_recursion === false) {
$_filedata = [];
$sourceDir = rtrim(realpath($sourceDir) ?: $sourceDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
}
// Used to be foreach (scandir($sourceDir, 1) as $file), but scandir() is simply not as fast
while (false !== ($file = readdir($fp))) {
if (is_dir($sourceDir . $file) && $file[0] !== '.' && $topLevelOnly === false) {
$this->getDirFileInfo($sourceDir . $file . DIRECTORY_SEPARATOR, $topLevelOnly, true);
} elseif (! is_dir($sourceDir . $file) && $file[0] !== '.') {
$_filedata[$file] = $this->getFileInfo($sourceDir . $file);
$_filedata[$file]['relative_path'] = $relativePath;
}
}
closedir($fp);
return $_filedata;
}
return false;
}
/**
* Given a file and path, returns the name, path, size, date modified
* Second parameter allows you to explicitly declare what information you want returned
* Options are: name, server_path, size, date, readable, writable, executable, fileperms
* Returns FALSE if the file cannot be found.
*
* @deprecated 4.6.1 Use `get_file_info()` instead.
*
* @param string $file Path to file
* @param array|string $returnedValues Array or comma separated string of information returned
*
* @return array|false
*/
protected function getFileInfo(string $file, $returnedValues = ['name', 'server_path', 'size', 'date'])
{
if (! is_file($file)) {
return false;
}
if (is_string($returnedValues)) {
$returnedValues = explode(',', $returnedValues);
}
$fileInfo = [];
foreach ($returnedValues as $key) {
switch ($key) {
case 'name':
$fileInfo['name'] = basename($file);
break;
case 'server_path':
$fileInfo['server_path'] = $file;
break;
case 'size':
$fileInfo['size'] = filesize($file);
break;
case 'date':
$fileInfo['date'] = filemtime($file);
break;
case 'readable':
$fileInfo['readable'] = is_readable($file);
break;
case 'writable':
$fileInfo['writable'] = is_writable($file);
break;
case 'executable':
$fileInfo['executable'] = is_executable($file);
break;
case 'fileperms':
$fileInfo['fileperms'] = fileperms($file);
break;
}
}
return $fileInfo;
}
}