Completed
Push — V6 ( 0a67f6...23eee8 )
by Georges
02:41
created

Driver::driverClear()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 4
rs 10
1
<?php
2
/**
3
 *
4
 * This file is part of phpFastCache.
5
 *
6
 * @license MIT License (MIT)
7
 *
8
 * For full copyright and license information, please see the docs/CREDITS.txt file.
9
 *
10
 * @author Khoa Bui (khoaofgod)  <[email protected]> http://www.phpfastcache.com
11
 * @author Georges.L (Geolim4)  <[email protected]>
12
 *
13
 */
14
15
namespace phpFastCache\Drivers\Files;
16
17
use phpFastCache\Core\Pool\DriverBaseTrait;
18
use phpFastCache\Core\Pool\ExtendedCacheItemPoolInterface;
19
use phpFastCache\Core\Pool\IO\PathSeekerTrait;
20
use phpFastCache\Entities\driverStatistic;
21
use phpFastCache\Exceptions\phpFastCacheDriverCheckException;
22
use phpFastCache\Exceptions\phpFastCacheDriverException;
23
use phpFastCache\Util\Directory;
24
use Psr\Cache\CacheItemInterface;
25
26
/**
27
 * Class Driver
28
 * @package phpFastCache\Drivers
29
 */
30
class Driver implements ExtendedCacheItemPoolInterface
31
{
32
    use DriverBaseTrait, PathSeekerTrait;
33
34
    /**
35
     *
36
     */
37
    const FILE_DIR = 'files';
38
39
    /**
40
     * Driver constructor.
41
     * @param array $config
42
     * @throws phpFastCacheDriverException
43
     */
44
    public function __construct(array $config = [])
45
    {
46
        $this->setup($config);
47
48
        if (!$this->driverCheck()) {
49
            throw new phpFastCacheDriverCheckException(sprintf(self::DRIVER_CHECK_FAILURE, $this->getDriverName()));
50
        }
51
    }
52
53
    /**
54
     * @return bool
55
     */
56
    public function driverCheck()
57
    {
58
        return is_writable($this->getFileDir()) || @mkdir($this->getFileDir(), $this->setChmodAuto(), true);
0 ignored issues
show
Security File Manipulation introduced by
$this->getFileDir() can contain request data and is used in file manipulation context(s) leading to a potential security vulnerability.

1 path for user data to reach this point

  1. Fetching key HTTP_HOST from $_SERVER, and $_SERVER['HTTP_HOST'] is passed through str_replace(), and str_replace(':', '_', $_SERVER['HTTP_HOST']) is passed through strtolower(), and strtolower(str_replace(':', '_', $_SERVER['HTTP_HOST'])) is passed through preg_replace(), and $securityKey is assigned
    in src/phpFastCache/Core/Pool/IO/PathSeekerTrait.php on line 60
  2. Data is passed through trim(), and Data is passed through preg_replace()
    in vendor/src/phpFastCache/Core/Pool/IO/PathSeekerTrait.php on line 194
  3. $securityKey is assigned
    in src/phpFastCache/Core/Pool/IO/PathSeekerTrait.php on line 70
  4. $full_path is assigned
    in src/phpFastCache/Core/Pool/IO/PathSeekerTrait.php on line 87
  5. $full_path is passed through realpath()
    in src/phpFastCache/Core/Pool/IO/PathSeekerTrait.php on line 104
  6. PathSeekerTrait::getPath() returns tainted data
    in src/phpFastCache/Core/Pool/IO/PathSeekerTrait.php on line 133
  7. PathSeekerTrait::getFileDir() returns tainted data
    in src/phpFastCache/Drivers/Files/Driver.php on line 58

General Strategies to prevent injection

In general, it is advisable to prevent any user-data to reach this point. This can be done by white-listing certain values:

if ( ! in_array($value, array('this-is-allowed', 'and-this-too'), true)) {
    throw new \InvalidArgumentException('This input is not allowed.');
}

For numeric data, we recommend to explicitly cast the data:

$sanitized = (integer) $tainted;
Loading history...
59
    }
60
61
    /**
62
     * @param \Psr\Cache\CacheItemInterface $item
63
     * @return mixed
64
     * @throws \InvalidArgumentException
65
     */
66
    protected function driverWrite(CacheItemInterface $item)
67
    {
68
        /**
69
         * Check for Cross-Driver type confusion
70
         */
71
        if ($item instanceof Item) {
72
            $file_path = $this->getFilePath($item->getKey());
73
            $data = $this->encode($this->driverPreWrap($item));
74
75
            /**
76
             * Force write
77
             */
78
            try {
79
                return $this->writefile($file_path, $data, $this->config['secureFileManipulation']);
80
            } catch (\Exception $e) {
81
                return false;
82
            }
83
        } else {
84
            throw new \InvalidArgumentException('Cross-Driver type confusion detected');
85
        }
86
    }
87
88
    /**
89
     * @param \Psr\Cache\CacheItemInterface $item
90
     * @return mixed
91
     */
92
    protected function driverRead(CacheItemInterface $item)
93
    {
94
        /**
95
         * Check for Cross-Driver type confusion
96
         */
97
        $file_path = $this->getFilePath($item->getKey());
98
        if (!file_exists($file_path)) {
99
            return null;
100
        }
101
102
        $content = $this->readfile($file_path);
103
104
        return $this->decode($content);
105
106
    }
107
108
    /**
109
     * @param \Psr\Cache\CacheItemInterface $item
110
     * @return bool
111
     * @throws \InvalidArgumentException
112
     */
113
    protected function driverDelete(CacheItemInterface $item)
114
    {
115
        /**
116
         * Check for Cross-Driver type confusion
117
         */
118
        if ($item instanceof Item) {
119
            $file_path = $this->getFilePath($item->getKey(), true);
120
            if (file_exists($file_path) && @unlink($file_path)) {
0 ignored issues
show
Security File Manipulation introduced by
$file_path can contain request data and is used in file manipulation context(s) leading to a potential security vulnerability.

1 path for user data to reach this point

  1. Fetching key HTTP_HOST from $_SERVER, and $_SERVER['HTTP_HOST'] is passed through str_replace(), and str_replace(':', '_', $_SERVER['HTTP_HOST']) is passed through strtolower(), and strtolower(str_replace(':', '_', $_SERVER['HTTP_HOST'])) is passed through preg_replace(), and $securityKey is assigned
    in src/phpFastCache/Core/Pool/IO/PathSeekerTrait.php on line 60
  2. Data is passed through trim(), and Data is passed through preg_replace()
    in vendor/src/phpFastCache/Core/Pool/IO/PathSeekerTrait.php on line 194
  3. $securityKey is assigned
    in src/phpFastCache/Core/Pool/IO/PathSeekerTrait.php on line 70
  4. $full_path is assigned
    in src/phpFastCache/Core/Pool/IO/PathSeekerTrait.php on line 87
  5. $full_path is passed through realpath()
    in src/phpFastCache/Core/Pool/IO/PathSeekerTrait.php on line 104
  6. PathSeekerTrait::getPath() returns tainted data
    in src/phpFastCache/Core/Pool/IO/PathSeekerTrait.php on line 133
  7. PathSeekerTrait::getFileDir() returns tainted data, and $path is assigned
    in src/phpFastCache/Core/Pool/IO/PathSeekerTrait.php on line 144
  8. PathSeekerTrait::getFilePath() returns tainted data, and $file_path is assigned
    in src/phpFastCache/Drivers/Files/Driver.php on line 119

General Strategies to prevent injection

In general, it is advisable to prevent any user-data to reach this point. This can be done by white-listing certain values:

if ( ! in_array($value, array('this-is-allowed', 'and-this-too'), true)) {
    throw new \InvalidArgumentException('This input is not allowed.');
}

For numeric data, we recommend to explicitly cast the data:

$sanitized = (integer) $tainted;
Loading history...
121
                return true;
122
            } else {
123
                return false;
124
            }
125
        } else {
126
            throw new \InvalidArgumentException('Cross-Driver type confusion detected');
127
        }
128
    }
129
130
    /**
131
     * @return bool
132
     */
133
    protected function driverClear()
134
    {
135
        return (bool) Directory::rrmdir($this->getPath(true));
136
    }
137
138
    /**
139
     * @return bool
140
     */
141
    protected function driverConnect()
142
    {
143
        return true;
144
    }
145
146
    /**
147
     * @param string $optionName
148
     * @param mixed $optionValue
149
     * @return bool
150
     * @throws \InvalidArgumentException
151
     */
152
    public static function isValidOption($optionName, $optionValue)
153
    {
154
        DriverBaseTrait::isValidOption($optionName, $optionValue);
155
        switch ($optionName) {
156
            case 'path':
157
                return is_string($optionValue);
158
                break;
159
160
            case 'default_chmod':
161
                return is_numeric($optionValue);
162
                break;
163
164
            case 'securityKey':
165
                return is_string($optionValue);
166
                break;
167
            case 'htaccess':
168
                return is_bool($optionValue);
169
                break;
170
            default:
171
                return false;
172
                break;
173
        }
174
    }
175
176
    /**
177
     * @return array
178
     */
179
    public static function getValidOptions()
180
    {
181
        return ['path', 'default_chmod', 'securityKey', 'htaccess'];
182
    }
183
184
    /**
185
     * @return array
186
     */
187
    public static function getRequiredOptions()
188
    {
189
        return ['path'];
190
    }
191
192
    /********************
193
     *
194
     * PSR-6 Extended Methods
195
     *
196
     *******************/
197
198
    /**
199
     * @return driverStatistic
200
     * @throws \phpFastCache\Exceptions\phpFastCacheCoreException
201
     * @throws \phpFastCache\Exceptions\phpFastCacheDriverException
202
     */
203 View Code Duplication
    public function getStats()
1 ignored issue
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
204
    {
205
        $stat = new driverStatistic();
206
        $path = $this->getFilePath(false);
207
208
        if (!is_dir($path)) {
209
            throw new phpFastCacheDriverException("Can't read PATH:" . $path, 94);
210
        }
211
212
        $stat->setData(implode(', ', array_keys($this->itemInstances)))
213
          ->setRawData([])
214
          ->setSize(Directory::dirSize($path))
215
          ->setInfo('Number of files used to build the cache: ' . Directory::getFileCount($path));
216
217
        return $stat;
218
    }
219
}