Completed
Push — master ( 87527d...6b8782 )
by Jan
03:58
created

AttachmentHelper::getFileSize()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 3
nc 2
nop 1
dl 0
loc 7
rs 10
c 1
b 0
f 0
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;
33
34
35
use App\Entity\Attachments\Attachment;
36
use App\Entity\Attachments\PartAttachment;
37
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
38
use Symfony\Component\Filesystem\Filesystem;
39
use Symfony\Component\HttpFoundation\File\UploadedFile;
40
use Symfony\Component\HttpKernel\KernelInterface;
41
42
class AttachmentHelper
43
{
44
    /**
45
     * @var string The folder where the attachments are saved. By default this is data/media in the project root string
46
     */
47
    protected $base_path;
48
49
    public function __construct(ParameterBagInterface $params, KernelInterface $kernel)
50
    {
51
        $tmp_base_path = $params->get('media_directory');
52
53
        $fs = new Filesystem();
54
55
        //Determine if it is an absolute path, or if we need to create a real absolute one out of it
56
        if ($fs->isAbsolutePath($tmp_base_path)) {
57
            $this->base_path = $tmp_base_path;
58
        } else {
59
            $this->base_path = realpath($kernel->getProjectDir() . DIRECTORY_SEPARATOR . $tmp_base_path);
60
        }
61
    }
62
63
    /**
64
     * Returns the absolute path to the folder where all attachments are saved.
65
     * @return string
66
     */
67
    public function getMediaPath() : string
68
    {
69
        return $this->base_path;
70
    }
71
72
    /**
73
     * Gets an SPLFileInfo object representing the file associated with the attachment.
74
     * @param Attachment $attachment The attachment for which the file should be generated
75
     * @return \SplFileInfo|null The fileinfo for the attachment file. Null, if the attachment is external or has
76
     * invalid file.
77
     */
78
    public function attachmentToFile(Attachment $attachment) : ?\SplFileInfo
79
    {
80
        if ($attachment->isExternal() || !$this->isFileExisting($attachment)) {
81
            return null;
82
        }
83
84
        return new \SplFileInfo($this->toAbsoluteFilePath($attachment));
85
    }
86
87
    /**
88
     * Converts an relative placeholder filepath (with %MEDIA% or older %BASE%) to an absolute filepath on disk.
89
     * @param string $placeholder_path The filepath with placeholder for which the real path should be determined.
90
     * @return string The absolute real path of the file
91
     */
92
    public function placeholderToRealPath(string $placeholder_path) : string
93
    {
94
        //The new attachments use %MEDIA% as placeholders, which is the directory set in media_directory
95
        $placeholder_path = str_replace("%MEDIA%", $this->base_path, $placeholder_path);
96
97
        //Older path entries are given via %BASE% which was the project root
98
        $placeholder_path = str_replace("%BASE%/data/media", $this->base_path, $placeholder_path);
99
100
        //Normalize path
101
        $placeholder_path = str_replace('\\', '/', $placeholder_path);
102
103
        return $placeholder_path;
104
    }
105
106
    /**
107
     * Converts an real absolute filepath to a placeholder version.
108
     * @param string $real_path The absolute path, for which the placeholder version should be generated.
109
     * @param bool $old_version By default the %MEDIA% placeholder is used, which is directly replaced with the
110
     * media directory. If set to true, the old version with %BASE% will be used, which is the project directory.
111
     * @return string The placeholder version of the filepath
112
     */
113
    public function realPathToPlaceholder(string $real_path, bool $old_version = false) : string
114
    {
115
        if ($old_version) {
116
            $real_path = str_replace($this->base_path, "%BASE%/data/media", $real_path);
117
        } else {
118
            $real_path = str_replace($this->base_path, "%MEDIA%", $real_path);
119
        }
120
121
        //Normalize path
122
        $real_path = str_replace('\\', '/', $real_path);
123
        return $real_path;
124
    }
125
126
    /**
127
     * Returns the absolute filepath of the attachment. Null is returned, if the attachment is externally saved.
128
     * @param Attachment $attachment The attachment for which the filepath should be determined
129
     * @return string|null
130
     */
131
    public function toAbsoluteFilePath(Attachment $attachment): ?string
132
    {
133
        if (empty($attachment->getPath())) {
134
            return null;
135
        }
136
137
        if ($attachment->isExternal()) {
138
            return null;
139
        }
140
141
        $path = $attachment->getPath();
142
        $path = $this->placeholderToRealPath($path);
143
        return realpath($path);
144
    }
145
146
    /**
147
     * Checks if the file in this attachement is existing. This works for files on the HDD, and for URLs
148
     * (it's not checked if the ressource behind the URL is really existing, so for every external attachment true is returned).
149
     *
150
     * @param Attachment $attachment The attachment for which the existence should be checked
151
     *
152
     * @return bool True if the file is existing.
153
     */
154
    public function isFileExisting(Attachment $attachment): bool
155
    {
156
        if (empty($attachment->getPath())) {
157
            return false;
158
        }
159
160
        return file_exists($this->toAbsoluteFilePath($attachment)) || $attachment->isExternal();
161
    }
162
163
    /**
164
     * Returns the filesize of the attachments in bytes.
165
     * For external attachments, null is returned.
166
     *
167
     * @param Attachment $attachment The filesize for which the filesize should be calculated.
168
     * @return int|null
169
     */
170
    public function getFileSize(Attachment $attachment): ?int
171
    {
172
        if ($attachment->isExternal()) {
173
            return null;
174
        }
175
176
        return filesize($this->toAbsoluteFilePath($attachment));
177
    }
178
179
    /**
180
     * Returns a human readable version of the attachment file size.
181
     * For external attachments, null is returned.
182
     *
183
     * @param Attachment $attachment
184
     * @param int $decimals The number of decimals numbers that should be printed
185
     * @return string|null A string like 1.3M
186
     */
187
    public function getHumanFileSize(Attachment $attachment, $decimals = 2): ?string
188
    {
189
        $bytes = $this->getFileSize($attachment);
190
191
        if ($bytes == null) {
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing $bytes of type integer|null against null; this is ambiguous if the integer can be zero. Consider using a strict comparison === instead.
Loading history...
192
            return null;
193
        }
194
195
        //Format filesize for human reading
196
        //Taken from: https://www.php.net/manual/de/function.filesize.php#106569 and slightly modified
197
198
        $sz = 'BKMGTP';
199
        $factor = (int) floor((strlen($bytes) - 1) / 3);
200
        return sprintf("%.{$decimals}f", $bytes / 1024 ** $factor) . @$sz[$factor];
201
    }
202
203
    /**
204
     * Generate a path to a folder, where this attachment can save its file.
205
     * @param Attachment $attachment The attachment for which the folder should be generated
206
     * @return string The path to the folder (without trailing slash)
207
     */
208
    public function generateFolderForAttachment(Attachment $attachment) : string
209
    {
210
        $mapping = [PartAttachment::class => 'part'];
211
212
        $path = $this->base_path . DIRECTORY_SEPARATOR . $mapping[get_class($attachment)] . DIRECTORY_SEPARATOR . $attachment->getElement()->getID();
213
        return $path;
214
    }
215
216
    /**
217
     * Moves the given uploaded file to a permanent place and saves it into the attachment
218
     * @param Attachment $attachment The attachment in which the file should be saved
219
     * @param UploadedFile|null $file The file which was uploaded
220
     * @return Attachment The attachment with the new filepath
221
     */
222
    public function upload(Attachment $attachment, ?UploadedFile $file) : Attachment
223
    {
224
        //If file is null, do nothing (helpful, so we dont have to check if the file was reuploaded in controller)
225
        if (!$file) {
226
            return $attachment;
227
        }
228
229
        $folder = $this->generateFolderForAttachment($attachment);
230
231
        //Sanatize filename
232
        $originalFilename = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
233
        $safeFilename = transliterator_transliterate('Any-Latin; Latin-ASCII; [^A-Za-z0-9_] remove; Lower()', $originalFilename);
234
        $newFilename = $safeFilename . '.' . $file->getClientOriginalExtension();
235
236
        //If a file with this name is already existing add a number to the filename
237
        if (file_exists($folder . DIRECTORY_SEPARATOR . $newFilename)) {
238
            $bak = $newFilename;
0 ignored issues
show
Unused Code introduced by
The assignment to $bak is dead and can be removed.
Loading history...
239
240
            $number = 1;
241
            $newFilename = $folder . DIRECTORY_SEPARATOR . $safeFilename . '-' . $number . '.' . $file->getClientOriginalExtension();
242
            while (file_exists($newFilename)) {
243
                $number++;
244
                $newFilename = $folder . DIRECTORY_SEPARATOR . $safeFilename . '-' . $number . '.' . $file->getClientOriginalExtension();
245
            }
246
        }
247
248
        //Move our temporay attachment to its final location
249
        $file_path = $file->move($folder, $newFilename)->getRealPath();
250
251
        //Make our file path relative to %BASE%
252
        $file_path = $this->realPathToPlaceholder($file_path);
253
254
        //Save the path to the attachment
255
        $attachment->setPath($file_path);
256
257
        return $attachment;
258
    }
259
260
}