Completed
Push — v5 ( 9120d0...3fd0ee )
by Georges
02:35
created

PathSeekerTrait::encodeFilename()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 1
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()
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
        $securityKey = array_key_exists('securityKey', $this->config) ? $this->config[ 'securityKey' ] : '';
54
        if ($securityKey == "" || $securityKey == 'auto') {
55
            $securityKey = $this->config[ 'securityKey' ];
56
            if ($securityKey == 'auto' || $securityKey == '') {
57
                $securityKey = isset($_SERVER[ 'HTTP_HOST' ]) ? preg_replace('/^www./', '', strtolower($_SERVER[ 'HTTP_HOST' ])) : "default";
58
            }
59
        }
60
        if ($securityKey != '') {
61
            $securityKey .= '/';
62
        }
63
64
        $securityKey = $this->cleanFileName($securityKey);
65
66
        $full_path = rtrim($path, '/') . '/' . $securityKey;
67
        $full_pathx = md5($full_path);
68
69
70
        if (!isset($this->tmp[ $full_pathx ])) {
71
72
            if (!@file_exists($full_path) || !@is_writable($full_path)) {
73
                if (!@file_exists($full_path)) {
74
                    @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...
75
                }
76
                if (!@is_writable($full_path)) {
77
                    @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...
78
                }
79
                if (!@is_writable($full_path)) {
80
                    // switch back to tmp dir again if the path is not writeable
81
                    $full_path = rtrim($tmp_dir, '/') . '/' . $securityKey;
82
                    if (!@file_exists($full_path)) {
83
                        @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...
84
                    }
85
                    if (!@is_writable($full_path)) {
86
                        @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...
87
                    }
88
                }
89
                if (!@file_exists($full_path) || !@is_writable($full_path)) {
90
                    throw new phpFastCacheCoreException('PLEASE CREATE OR CHMOD ' . $full_path . ' - 0777 OR ANY WRITABLE PERMISSION!', 92);
91
                }
92
            }
93
94
            $this->tmp[ $full_pathx ] = true;
95
            $this->htaccessGen($full_path, array_key_exists('htaccess', $this->config) ? $this->config[ 'htaccess' ] : false);
96
        }
97
98
        return realpath($full_path);
99
    }
100
101
    /**
102
     * @param $keyword
103
     * @return string
104
     */
105
    protected function encodeFilename($keyword)
106
    {
107
        return md5($keyword);
108
    }
109
110
    /**
111
     * @return bool
112
     */
113
    public function isExpired()
114
    {
115
        trigger_error(__FUNCTION__ . '() is deprecated, use ExtendedCacheItemInterface::isExpired() instead.', E_USER_DEPRECATED);
116
117
        return true;
118
    }
119
120
    /**
121
     * @param $keyword
122
     * @param bool $skip
123
     * @return string
124
     * @throws phpFastCacheDriverException
125
     */
126
    private function getFilePath($keyword, $skip = false)
127
    {
128
        $path = $this->getPath() . '/files';
129
130
        if($keyword === false)
131
        {
132
            return $path;
133
        }
134
135
        $filename = $this->encodeFilename($keyword);
136
        $folder = substr($filename, 0, 2);
137
        $path = rtrim($path, '/') . '/' . $folder;
138
        /**
139
         * Skip Create Sub Folders;
140
         */
141
        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...
142
            if (!file_exists($path)) {
143
                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...
144
                    throw new phpFastCacheDriverException('PLEASE CHMOD ' . $this->getPath() . ' - ' . $this->setChmodAuto() . ' OR ANY WRITABLE PERMISSION!');
145
                }
146
            }
147
        }
148
149
        return $path . '/' . $filename . '.txt';
150
    }
151
152
153
    /**
154
     * @param $this ->config
155
     * @return int
156
     */
157
    public function setChmodAuto()
158
    {
159
        if (!isset($this->config[ 'default_chmod' ]) || $this->config[ 'default_chmod' ] == '' || is_null($this->config[ 'default_chmod' ])) {
160
            return 0777;
161
        } else {
162
            return $this->config[ 'default_chmod' ];
163
        }
164
    }
165
166
    /**
167
     * @param $filename
168
     * @return mixed
169
     */
170
    protected static function cleanFileName($filename)
171
    {
172
        $regex = [
173
          '/[\?\[\]\/\\\=\<\>\:\;\,\'\"\&\$\#\*\(\)\|\~\`\!\{\}]/',
174
          '/\.$/',
175
          '/^\./',
176
        ];
177
        $replace = ['-', '', ''];
178
179
        return trim(preg_replace($regex, $replace, trim($filename)), '-');
180
    }
181
182
    /**
183
     * @param $path
184
     * @param bool $create
185
     * @throws \Exception
186
     */
187
    protected function htaccessGen($path, $create = true)
188
    {
189
        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...
190
            if (!is_writable($path)) {
191
                try {
192
                    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...
193
                } catch (phpFastCacheDriverException $e) {
194
                    throw new phpFastCacheDriverException('PLEASE CHMOD ' . $path . ' - 0777 OR ANY WRITABLE PERMISSION!',
195
                      92);
196
                }
197
            }
198
199
            if (!file_exists($path . "/.htaccess")) {
200
                //   echo "write me";
201
                $html = "order deny, allow \r\n
202
deny from all \r\n
203
allow from 127.0.0.1";
204
205
                $file = @fopen($path . '/.htaccess', 'w+');
206
                if (!$file) {
207
                    throw new phpFastCacheDriverException('PLEASE CHMOD ' . $path . ' - 0777 OR ANY WRITABLE PERMISSION!');
208
                }
209
                fwrite($file, $html);
210
                fclose($file);
211
            }
212
        }
213
    }
214
}