Completed
Push — master ( ac238c...da4625 )
by Jan
04:59
created

AttachmentPathResolver::parameterToAbsolutePath()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 27
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 12
c 1
b 0
f 0
nc 5
nop 1
dl 0
loc 27
rs 9.5555
1
<?php
2
/**
3
 *
4
 * part-db version 0.1
5
 * Copyright (C) 2005 Christoph Lechner
6
 * http://www.cl-projects.de/
7
 *
8
 * part-db version 0.2+
9
 * Copyright (C) 2009 K. Jacobs and others (see authors.php)
10
 * http://code.google.com/p/part-db/
11
 *
12
 * Part-DB Version 0.4+
13
 * Copyright (C) 2016 - 2019 Jan Böhmer
14
 * https://github.com/jbtronics
15
 *
16
 * This program is free software; you can redistribute it and/or
17
 * modify it under the terms of the GNU General Public License
18
 * as published by the Free Software Foundation; either version 2
19
 * of the License, or (at your option) any later version.
20
 *
21
 * This program is distributed in the hope that it will be useful,
22
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
23
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24
 * GNU General Public License for more details.
25
 *
26
 * You should have received a copy of the GNU General Public License
27
 * along with this program; if not, write to the Free Software
28
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
29
 *
30
 */
31
32
namespace App\Services\Attachments;
33
34
35
use Symfony\Component\Filesystem\Filesystem;
36
use Symfony\Component\HttpKernel\KernelInterface;
37
38
/**
39
 * This service converts the relative pathes for attachments saved in database (like %MEDIA%/img.jpg) to real pathes
40
 * an vice versa.
41
 * @package App\Services\Attachments
42
 */
43
class AttachmentPathResolver
44
{
45
    protected $project_dir;
46
47
    protected $media_path;
48
    protected $footprints_path;
49
    protected $models_path;
50
51
    protected $placeholders;
52
    protected $pathes;
53
    protected $placeholders_regex;
54
    protected $pathes_regex;
55
56
    /**
57
     * AttachmentPathResolver constructor.
58
     * @param string $project_dir The kernel that should be used to resolve the project dir.
59
     * @param string $media_path The path where uploaded attachments should be stored.
60
     * @param string|null $footprints_path The path where builtin attachments are stored.
61
     * Set to null if this ressource should be disabled.
62
     * @param string|null $models_path Set to null if this ressource should be disabled.
63
     */
64
    public function __construct(string $project_dir, string $media_path, ?string $footprints_path, ?string $models_path)
65
    {
66
        $this->project_dir = $project_dir;
67
68
        //Determine the path for our ressources
69
        $this->media_path = $this->parameterToAbsolutePath($media_path);
70
        /* if ($this->media_path === null) {
71
            throw new \RuntimeException("MediaPath is not existing/valid! This parameter is not allowed!");
72
        } */
73
        $this->footprints_path = $this->parameterToAbsolutePath($footprints_path);
74
        $this->models_path = $this->parameterToAbsolutePath($models_path);
75
76
        //Here we define the valid placeholders and their replacement values
77
        $this->placeholders = ['%MEDIA%', '%BASE%/data/media', '%FOOTPRINTS%', '%FOOTPRINTS_3D%'];
78
        $this->pathes = [$this->media_path, $this->media_path, $this->footprints_path, $this->models_path];
79
80
        //Remove all disabled placeholders
81
        foreach ($this->pathes as $key => $path) {
82
            if ($path === null) {
83
                unset($this->placeholders[$key], $this->pathes[$key]);
84
            }
85
        }
86
87
        //Create the regex arrays
88
        $this->placeholders_regex = $this->arrayToRegexArray($this->placeholders);
89
        $this->pathes_regex = $this->arrayToRegexArray($this->pathes);
90
    }
91
92
    /**
93
     * Converts a path passed by parameter from services.yaml (which can be an absolute path or relative to project dir)
94
     * to an absolute path. When a relative path is passed, the directory must exist or null is returned.
95
     * @internal
96
     * @param string|null $param_path The parameter value that should be converted to a absolute path
97
     * @return string|null
98
     */
99
    public function parameterToAbsolutePath(?string $param_path) : ?string
100
    {
101
        if ($param_path === null) {
102
            return null;
103
        }
104
105
        $fs = new Filesystem();
106
        //If current string is already an absolute path, then we have nothing to do
107
        if ($fs->isAbsolutePath($param_path)) {
108
            $tmp = realpath($param_path);
109
            //Disable ressource if path is not existing
110
            if ($tmp === false) {
111
                return null;
112
            }
113
            return $tmp;
114
        }
115
116
        //Otherwise prepend the project path
117
        $tmp = realpath($this->project_dir . DIRECTORY_SEPARATOR . $param_path);
118
119
        //If path does not exist then disable the placeholder
120
        if ($tmp === false) {
121
            return null;
122
        }
123
124
        //Otherwise return resolved path
125
        return $tmp;
126
    }
127
128
    /**
129
     * Create an array usable for preg_replace out of an array of placeholders or pathes.
130
     * Slashes and other chars become escaped.
131
     * For example: '%TEST%' becomes '/^%TEST%/'.
132
     * @param array $array
133
     * @return array
134
     */
135
    protected function arrayToRegexArray(array $array) : array
136
    {
137
        $ret = [];
138
139
        foreach ($array as $item) {
140
            $item = str_replace(['\\'], ['/'], $item);
141
            $ret[] = '/' . preg_quote($item, '/') . '/';
142
        }
143
144
        return $ret;
145
    }
146
147
148
    /**
149
     * Converts an relative placeholder filepath (with %MEDIA% or older %BASE%) to an absolute filepath on disk.
150
     * The directory separator is always /. Relative pathes are not realy possible (.. is striped)
151
     * @param string $placeholder_path The filepath with placeholder for which the real path should be determined.
152
     * @return string|null The absolute real path of the file, or null if the placeholder path is invalid
153
     */
154
    public function placeholderToRealPath(string $placeholder_path) : ?string
155
    {
156
        //The new attachments use %MEDIA% as placeholders, which is the directory set in media_directory
157
        //Older path entries are given via %BASE% which was the project root
158
159
        $count = 0;
160
        $placeholder_path = preg_replace($this->placeholders_regex, $this->pathes, $placeholder_path,-1,$count);
161
162
        //A valid placeholder can have only one
163
        if ($count !== 1) {
164
            return null;
165
        }
166
167
        //If we have now have a placeholder left, the string is invalid:
168
        if (preg_match('/%\w+%/', $placeholder_path)) {
169
            return null;
170
        }
171
172
        //Path is invalid if path is directory traversal
173
        if (strpos($placeholder_path, '..') !== false) {
174
            return null;
175
        }
176
177
        //Normalize path and remove .. (to prevent directory traversal attack)
178
        $placeholder_path = str_replace(['\\'], ['/'], $placeholder_path);
179
180
        return $placeholder_path;
181
    }
182
183
    /**
184
     * Converts an real absolute filepath to a placeholder version.
185
     * @param string $real_path The absolute path, for which the placeholder version should be generated.
186
     * @param bool $old_version By default the %MEDIA% placeholder is used, which is directly replaced with the
187
     * media directory. If set to true, the old version with %BASE% will be used, which is the project directory.
188
     * @return string The placeholder version of the filepath
189
     */
190
    public function realPathToPlaceholder(string $real_path, bool $old_version = false) : ?string
191
    {
192
        $count = 0;
193
194
        //Normalize path
195
        $real_path = str_replace('\\', '/', $real_path);
196
197
        if ($old_version) {
198
            //We need to remove the %MEDIA% placeholder (element 0)
199
            $pathes = $this->pathes_regex;
200
            $placeholders = $this->placeholders;
201
            unset($pathes[0], $placeholders[0]);
202
            $real_path = preg_replace($pathes, $placeholders, $real_path, -1, $count);
203
        } else {
204
            $real_path = preg_replace($this->pathes_regex, $this->placeholders, $real_path, -1, $count);
205
        }
206
207
        if ($count !== 1) {
208
            return null;
209
        }
210
211
        //If the new string does not begin with a placeholder, it is invalid
212
        if (!preg_match('/^%\w+%/', $real_path)) {
213
            return null;
214
        }
215
216
        return $real_path;
217
    }
218
219
    /**
220
     * The path where uploaded attachments is stored.
221
     * @return string The absolute path to the media folder.
222
     */
223
    public function getMediaPath() : string
224
    {
225
        return $this->media_path;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->media_path could return the type null which is incompatible with the type-hinted return string. Consider adding an additional type-check to rule them out.
Loading history...
226
    }
227
228
    /**
229
     * The string where the builtin footprints are stored
230
     * @return string|null The absolute path to the footprints folder. Null if built footprints were disabled.
231
     */
232
    public function getFootprintsPath() : ?string
233
    {
234
        return $this->footprints_path;
235
    }
236
237
    /**
238
     * The string where the builtin 3D models are stored
239
     * @return string|null The absolute path to the models folder. Null if builtin models were disabled.
240
     */
241
    public function getModelsPath() : ?string
242
    {
243
        return $this->models_path;
244
    }
245
}