Completed
Push — v5 ( 0b505a...012ddd )
by Georges
02:41
created

PathSeekerTrait::getFileDir()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 1
eloc 2
c 1
b 1
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\Core;
16
17
use phpFastCache\Exceptions\phpFastCacheCoreException;
18
use phpFastCache\Exceptions\phpFastCacheDriverException;
19
20
trait PathSeekerTrait
21
{
22
    /**
23
     * @var array
24
     */
25
    public $tmp = [];
26
27
    /**
28
     * @param bool $skip_create_path
0 ignored issues
show
Bug introduced by
There is no parameter named $skip_create_path. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
29
     * @param $config
30
     * @return string
31
     * @throws \Exception
32
     */
33
    public function getPath($getBasePath = false)
34
    {
35
        $tmp_dir = ini_get('upload_tmp_dir') ? ini_get('upload_tmp_dir') : sys_get_temp_dir();
36
37
        if (!isset($this->config[ 'path' ]) || $this->config[ 'path' ] == '') {
38
            if (self::isPHPModule()) {
39
                $path = $tmp_dir;
40
            } else {
41
                $document_root_path = rtrim($_SERVER[ 'DOCUMENT_ROOT' ], '/') . '/../';
42
                $path = isset($_SERVER[ 'DOCUMENT_ROOT' ]) && is_writable($document_root_path) ? $document_root_path : rtrim(__DIR__, '/') . '/';
43
            }
44
45
            if ($this->config[ 'path' ] != '') {
46
                $path = $this->config[ 'path' ];
1 ignored issue
show
Bug introduced by
The property config does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
47
            }
48
49
        } else {
50
            $path = $this->config[ 'path' ];
51
        }
52
53
        if($getBasePath === true)
54
        {
55
            return $path;
56
        }
57
58
        $securityKey = array_key_exists('securityKey', $this->config) ? $this->config[ 'securityKey' ] : '';
59
        if ($securityKey == "" || $securityKey == 'auto') {
60
            $securityKey = $this->config[ 'securityKey' ];
61
            if ($securityKey == 'auto' || $securityKey == '') {
62
                $securityKey = isset($_SERVER[ 'HTTP_HOST' ]) ? preg_replace('/^www./', '', strtolower($_SERVER[ 'HTTP_HOST' ])) : "default";
63
            }
64
        }
65
        if ($securityKey != '') {
66
            $securityKey .= '/';
67
        }
68
69
        $securityKey = $this->cleanFileName($securityKey);
70
71
        $full_path = rtrim($path, '/') .'/' . $securityKey;
72
        $full_pathx = md5($full_path);
73
74
75
        if (!isset($this->tmp[ $full_pathx ])) {
76
77
            if (!@file_exists($full_path) || !@is_writable($full_path)) {
78
                if (!@file_exists($full_path)) {
79
                    @mkdir($full_path, $this->setChmodAuto(), true);
1 ignored issue
show
Security File Manipulation introduced by
$full_path can contain request data and is used in file manipulation context(s) leading to a potential security vulnerability.

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...
80
                }
81
                if (!@is_writable($full_path)) {
82
                    @chmod($full_path, $this->setChmodAuto());
1 ignored issue
show
Security File Manipulation introduced by
$full_path can contain request data and is used in file manipulation context(s) leading to a potential security vulnerability.

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...
83
                }
84
                if (!@is_writable($full_path)) {
85
                    // switch back to tmp dir again if the path is not writeable
86
                    $full_path = rtrim($tmp_dir, '/') . '/' . $securityKey;
87
                    if (!@file_exists($full_path)) {
88
                        @mkdir($full_path, $this->setChmodAuto(), true);
1 ignored issue
show
Security File Manipulation introduced by
$full_path can contain request data and is used in file manipulation context(s) leading to a potential security vulnerability.

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...
89
                    }
90
                    if (!@is_writable($full_path)) {
91
                        @chmod($full_path, $this->setChmodAuto());
1 ignored issue
show
Security File Manipulation introduced by
$full_path can contain request data and is used in file manipulation context(s) leading to a potential security vulnerability.

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...
92
                    }
93
                }
94
                if (!@file_exists($full_path) || !@is_writable($full_path)) {
95
                    throw new phpFastCacheCoreException('PLEASE CREATE OR CHMOD ' . $full_path . ' - 0777 OR ANY WRITABLE PERMISSION!', 92);
96
                }
97
            }
98
99
            $this->tmp[ $full_pathx ] = true;
100
            $this->htaccessGen($full_path, array_key_exists('htaccess', $this->config) ? $this->config[ 'htaccess' ] : false);
101
        }
102
103
        return realpath($full_path);
104
    }
105
106
    /**
107
     * @param $keyword
108
     * @return string
109
     */
110
    protected function encodeFilename($keyword)
111
    {
112
        return md5($keyword);
113
    }
114
115
    /**
116
     * @return bool
117
     */
118
    public function isExpired()
119
    {
120
        trigger_error(__FUNCTION__ . '() is deprecated, use ExtendedCacheItemInterface::isExpired() instead.', E_USER_DEPRECATED);
121
122
        return true;
123
    }
124
125
126
    /**
127
     * @return string
128
     * @throws \phpFastCache\Exceptions\phpFastCacheCoreException
129
     */
130
    public function getFileDir()
131
    {
132
        return $this->getPath() . DIRECTORY_SEPARATOR . self::FILE_DIR;
133
    }
134
135
    /**
136
     * @param $keyword
137
     * @param bool $skip
138
     * @return string
139
     * @throws phpFastCacheDriverException
140
     */
141
    private function getFilePath($keyword, $skip = false)
142
    {
143
        $path = $this->getFileDir();
144
145
        if($keyword === false)
146
        {
147
            return $path;
148
        }
149
150
        $filename = $this->encodeFilename($keyword);
151
        $folder = substr($filename, 0, 2);
152
        $path = rtrim($path, '/') . '/' . $folder;
153
        /**
154
         * Skip Create Sub Folders;
155
         */
156
        if ($skip == false) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
157
            if (!file_exists($path)) {
158
                if (@!mkdir($path, $this->setChmodAuto(), true)) {
1 ignored issue
show
Security File Manipulation introduced by
$path can contain request data and is used in file manipulation context(s) leading to a potential security vulnerability.

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...
159
                    throw new phpFastCacheDriverException('PLEASE CHMOD ' . $this->getPath() . ' - ' . $this->setChmodAuto() . ' OR ANY WRITABLE PERMISSION!');
160
                }
161
            }
162
        }
163
164
        return $path . '/' . $filename . '.txt';
165
    }
166
167
168
    /**
169
     * @param $this ->config
170
     * @return int
171
     */
172
    public function setChmodAuto()
173
    {
174
        if (!isset($this->config[ 'default_chmod' ]) || $this->config[ 'default_chmod' ] == '' || is_null($this->config[ 'default_chmod' ])) {
175
            return 0777;
176
        } else {
177
            return $this->config[ 'default_chmod' ];
178
        }
179
    }
180
181
    /**
182
     * @param $filename
183
     * @return mixed
184
     */
185
    protected static function cleanFileName($filename)
186
    {
187
        $regex = [
188
          '/[\?\[\]\/\\\=\<\>\:\;\,\'\"\&\$\#\*\(\)\|\~\`\!\{\}]/',
189
          '/\.$/',
190
          '/^\./',
191
        ];
192
        $replace = ['-', '', ''];
193
194
        return trim(preg_replace($regex, $replace, trim($filename)), '-');
195
    }
196
197
    /**
198
     * @param $path
199
     * @param bool $create
200
     * @throws \Exception
201
     */
202
    protected function htaccessGen($path, $create = true)
203
    {
204
        if ($create == true) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
205
            if (!is_writable($path)) {
206
                try {
207
                    chmod($path, 0777);
1 ignored issue
show
Security File Manipulation introduced by
$path can contain request data and is used in file manipulation context(s) leading to a potential security vulnerability.

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...
208
                } catch (phpFastCacheDriverException $e) {
209
                    throw new phpFastCacheDriverException('PLEASE CHMOD ' . $path . ' - 0777 OR ANY WRITABLE PERMISSION!',
210
                      92);
211
                }
212
            }
213
214
            if (!file_exists($path . "/.htaccess")) {
215
                //   echo "write me";
216
                $html = "order deny, allow \r\n
217
deny from all \r\n
218
allow from 127.0.0.1";
219
220
                $file = @fopen($path . '/.htaccess', 'w+');
221
                if (!$file) {
222
                    throw new phpFastCacheDriverException('PLEASE CHMOD ' . $path . ' - 0777 OR ANY WRITABLE PERMISSION!');
223
                }
224
                fwrite($file, $html);
225
                fclose($file);
226
            }
227
        }
228
    }
229
}