xref: /webtrees/app/Services/MediaFileService.php (revision 94db7d2d27c3ad6a04fceebbdcb98e28e97649b3)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2021 webtrees development team
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <https://www.gnu.org/licenses/>.
16 */
17
18declare(strict_types=1);
19
20namespace Fisharebest\Webtrees\Services;
21
22use Fisharebest\Webtrees\Exceptions\FileUploadException;
23use Fisharebest\Webtrees\FlashMessages;
24use Fisharebest\Webtrees\I18N;
25use Fisharebest\Webtrees\Registry;
26use Fisharebest\Webtrees\Tree;
27use Fisharebest\Webtrees\Validator;
28use Illuminate\Database\Capsule\Manager as DB;
29use Illuminate\Database\Query\Expression;
30use Illuminate\Database\Query\JoinClause;
31use Illuminate\Support\Collection;
32use InvalidArgumentException;
33use League\Flysystem\FilesystemException;
34use League\Flysystem\FilesystemOperator;
35use League\Flysystem\FilesystemReader;
36use League\Flysystem\StorageAttributes;
37use Psr\Http\Message\ServerRequestInterface;
38use RuntimeException;
39
40use function array_combine;
41use function array_diff;
42use function array_intersect;
43use function dirname;
44use function explode;
45use function ini_get;
46use function intdiv;
47use function min;
48use function pathinfo;
49use function sha1;
50use function sort;
51use function str_contains;
52use function strtolower;
53use function strtr;
54use function substr;
55use function trim;
56
57use const PATHINFO_EXTENSION;
58use const UPLOAD_ERR_OK;
59
60/**
61 * Managing media files.
62 */
63class MediaFileService
64{
65    public const EXTENSION_TO_FORM = [
66        'jpeg' => 'jpg',
67        'tiff' => 'tif',
68    ];
69
70    private const IGNORE_FOLDERS = [
71        // Old versions of webtrees
72        'thumbs',
73        'watermarks',
74        // Windows
75        'Thumbs.db',
76        // Synology
77        '@eaDir',
78        // QNAP,
79        '.@__thumb',
80    ];
81
82    /**
83     * What is the largest file a user may upload?
84     */
85    public function maxUploadFilesize(): string
86    {
87        $sizePostMax   = $this->parseIniFileSize((string) ini_get('post_max_size'));
88        $sizeUploadMax = $this->parseIniFileSize((string) ini_get('upload_max_filesize'));
89
90        $bytes = min($sizePostMax, $sizeUploadMax);
91        $kb    = intdiv($bytes + 1023, 1024);
92
93        return I18N::translate('%s KB', I18N::number($kb));
94    }
95
96    /**
97     * Returns the given size from an ini value in bytes.
98     *
99     * @param string $size
100     *
101     * @return int
102     */
103    private function parseIniFileSize(string $size): int
104    {
105        $number = (int) $size;
106
107        switch (substr($size, -1)) {
108            case 'g':
109            case 'G':
110                return $number * 1073741824;
111            case 'm':
112            case 'M':
113                return $number * 1048576;
114            case 'k':
115            case 'K':
116                return $number * 1024;
117            default:
118                return $number;
119        }
120    }
121
122    /**
123     * A list of media files not already linked to a media object.
124     *
125     * @param Tree               $tree
126     * @param FilesystemOperator $data_filesystem
127     *
128     * @return array<string>
129     */
130    public function unusedFiles(Tree $tree, FilesystemOperator $data_filesystem): array
131    {
132        $used_files = DB::table('media_file')
133            ->where('m_file', '=', $tree->id())
134            ->where('multimedia_file_refn', 'NOT LIKE', 'http://%')
135            ->where('multimedia_file_refn', 'NOT LIKE', 'https://%')
136            ->pluck('multimedia_file_refn')
137            ->all();
138
139        $media_filesystem = $tree->mediaFilesystem($data_filesystem);
140        $disk_files       = $this->allFilesOnDisk($media_filesystem, '', FilesystemReader::LIST_DEEP)->all();
141        $unused_files     = array_diff($disk_files, $used_files);
142
143        sort($unused_files);
144
145        return array_combine($unused_files, $unused_files);
146    }
147
148    /**
149     * Store an uploaded file (or URL), either to be added to a media object
150     * or to create a media object.
151     *
152     * @param ServerRequestInterface $request
153     *
154     * @return string The value to be stored in the 'FILE' field of the media object.
155     * @throws FilesystemException
156     */
157    public function uploadFile(ServerRequestInterface $request): string
158    {
159        $tree = Validator::attributes($request)->tree();
160
161        $data_filesystem = Registry::filesystem()->data();
162
163        $params        = (array) $request->getParsedBody();
164        $file_location = $params['file_location'];
165
166        switch ($file_location) {
167            case 'url':
168                $remote = $params['remote'];
169
170                if (str_contains($remote, '://')) {
171                    return $remote;
172                }
173
174                return '';
175
176            case 'unused':
177                $unused = $params['unused'];
178
179                if ($tree->mediaFilesystem($data_filesystem)->fileExists($unused)) {
180                    return $unused;
181                }
182
183                return '';
184
185            case 'upload':
186            default:
187                $folder   = $params['folder'];
188                $auto     = $params['auto'];
189                $new_file = $params['new_file'];
190
191                $uploaded_file = $request->getUploadedFiles()['file'] ?? null;
192
193                if ($uploaded_file === null || $uploaded_file->getError() !== UPLOAD_ERR_OK) {
194                    throw new FileUploadException($uploaded_file);
195                }
196
197                // The filename
198                $new_file = strtr($new_file, ['\\' => '/']);
199                if ($new_file !== '' && !str_contains($new_file, '/')) {
200                    $file = $new_file;
201                } else {
202                    $file = $uploaded_file->getClientFilename();
203                }
204
205                // The folder
206                $folder = strtr($folder, ['\\' => '/']);
207                $folder = trim($folder, '/');
208                if ($folder !== '') {
209                    $folder .= '/';
210                }
211
212                // Generate a unique name for the file?
213                if ($auto === '1' || $tree->mediaFilesystem($data_filesystem)->fileExists($folder . $file)) {
214                    $folder    = '';
215                    $extension = pathinfo($uploaded_file->getClientFilename(), PATHINFO_EXTENSION);
216                    $file      = sha1((string) $uploaded_file->getStream()) . '.' . $extension;
217                }
218
219                try {
220                    $tree->mediaFilesystem($data_filesystem)->writeStream($folder . $file, $uploaded_file->getStream()->detach());
221
222                    return $folder . $file;
223                } catch (RuntimeException | InvalidArgumentException $ex) {
224                    FlashMessages::addMessage(I18N::translate('There was an error uploading your file.'));
225
226                    return '';
227                }
228        }
229    }
230
231    /**
232     * Convert the media file attributes into GEDCOM format.
233     *
234     * @param string $file
235     * @param string $type
236     * @param string $title
237     * @param string $note
238     *
239     * @return string
240     */
241    public function createMediaFileGedcom(string $file, string $type, string $title, string $note): string
242    {
243        $gedcom = '1 FILE ' . $file;
244
245        $format = strtolower(pathinfo($file, PATHINFO_EXTENSION));
246        $format = self::EXTENSION_TO_FORM[$format] ?? $format;
247
248        if ($format !== '') {
249            $gedcom .= "\n2 FORM " . $format;
250        } elseif ($type !== '') {
251            $gedcom .= "\n2 FORM";
252        }
253
254        if ($type !== '') {
255            $gedcom .= "\n3 TYPE " . $type;
256        }
257
258        if ($title !== '') {
259            $gedcom .= "\n2 TITL " . $title;
260        }
261
262        if ($note !== '') {
263            // Convert HTML line endings to GEDCOM continuations
264            $gedcom .= "\n1 NOTE " . strtr($note, ["\r\n" => "\n2 CONT "]);
265        }
266
267        return $gedcom;
268    }
269
270    /**
271     * Fetch a list of all files on disk (in folders used by any tree).
272     *
273     * @param FilesystemOperator $filesystem $filesystem to search
274     * @param string             $folder     Root folder
275     * @param bool               $subfolders Include subfolders
276     *
277     * @return Collection<int,string>
278     */
279    public function allFilesOnDisk(FilesystemOperator $filesystem, string $folder, bool $subfolders): Collection
280    {
281        try {
282            $files = $filesystem
283                ->listContents($folder, $subfolders)
284                ->filter(fn (StorageAttributes $attributes): bool => $attributes->isFile())
285                ->filter(fn (StorageAttributes $attributes): bool => !$this->ignorePath($attributes->path()))
286                ->map(fn (StorageAttributes $attributes): string => $attributes->path())
287                ->toArray();
288        } catch (FilesystemException $ex) {
289            $files = [];
290        }
291
292        return new Collection($files);
293    }
294
295    /**
296     * Fetch a list of all files on in the database.
297     *
298     * @param string $media_folder Root folder
299     * @param bool   $subfolders   Include subfolders
300     *
301     * @return Collection<int,string>
302     */
303    public function allFilesInDatabase(string $media_folder, bool $subfolders): Collection
304    {
305        $query = DB::table('media_file')
306            ->join('gedcom_setting', 'gedcom_id', '=', 'm_file')
307            ->where('setting_name', '=', 'MEDIA_DIRECTORY')
308            //->where('multimedia_file_refn', 'LIKE', '%/%')
309            ->where('multimedia_file_refn', 'NOT LIKE', 'http://%')
310            ->where('multimedia_file_refn', 'NOT LIKE', 'https://%')
311            ->where(new Expression('setting_value || multimedia_file_refn'), 'LIKE', $media_folder . '%')
312            ->select(new Expression('setting_value || multimedia_file_refn AS path'))
313            ->orderBy(new Expression('setting_value || multimedia_file_refn'));
314
315        if (!$subfolders) {
316            $query->where(new Expression('setting_value || multimedia_file_refn'), 'NOT LIKE', $media_folder . '%/%');
317        }
318
319        return $query->pluck('path');
320    }
321
322    /**
323     * Generate a list of all folders used by a tree.
324     *
325     * @param Tree $tree
326     *
327     * @return Collection<int,string>
328     * @throws FilesystemException
329     */
330    public function mediaFolders(Tree $tree): Collection
331    {
332        $folders = Registry::filesystem()->media($tree)
333            ->listContents('', FilesystemReader::LIST_DEEP)
334            ->filter(fn (StorageAttributes $attributes): bool => $attributes->isDir())
335            ->filter(fn (StorageAttributes $attributes): bool => !$this->ignorePath($attributes->path()))
336            ->map(fn (StorageAttributes $attributes): string => $attributes->path())
337            ->toArray();
338
339        return new Collection($folders);
340    }
341
342    /**
343     * Generate a list of all folders in either the database or the filesystem.
344     *
345     * @param FilesystemOperator $data_filesystem
346     *
347     * @return Collection<array-key,string>
348     * @throws FilesystemException
349     */
350    public function allMediaFolders(FilesystemOperator $data_filesystem): Collection
351    {
352        $db_folders = DB::table('media_file')
353            ->leftJoin('gedcom_setting', static function (JoinClause $join): void {
354                $join
355                    ->on('gedcom_id', '=', 'm_file')
356                    ->where('setting_name', '=', 'MEDIA_DIRECTORY');
357            })
358            ->where('multimedia_file_refn', 'NOT LIKE', 'http://%')
359            ->where('multimedia_file_refn', 'NOT LIKE', 'https://%')
360            ->select(new Expression("COALESCE(setting_value, 'media/') || multimedia_file_refn AS path"))
361            ->pluck('path')
362            ->map(static function (string $path): string {
363                return dirname($path) . '/';
364            });
365
366        $media_roots = DB::table('gedcom')
367            ->leftJoin('gedcom_setting', static function (JoinClause $join): void {
368                $join
369                    ->on('gedcom.gedcom_id', '=', 'gedcom_setting.gedcom_id')
370                    ->where('setting_name', '=', 'MEDIA_DIRECTORY');
371            })
372            ->where('gedcom.gedcom_id', '>', '0')
373            ->pluck(new Expression("COALESCE(setting_value, 'media/')"))
374            ->uniqueStrict();
375
376        $disk_folders = new Collection($media_roots);
377
378        foreach ($media_roots as $media_folder) {
379            $tmp = $data_filesystem
380                ->listContents($media_folder, FilesystemReader::LIST_DEEP)
381                ->filter(fn (StorageAttributes $attributes): bool => $attributes->isDir())
382                ->filter(fn (StorageAttributes $attributes): bool => !$this->ignorePath($attributes->path()))
383                ->map(fn (StorageAttributes $attributes): string => $attributes->path() . '/')
384                ->toArray();
385
386            $disk_folders = $disk_folders->concat($tmp);
387        }
388
389        return $disk_folders->concat($db_folders)
390            ->uniqueStrict()
391            ->mapWithKeys(static function (string $folder): array {
392                return [$folder => $folder];
393            });
394    }
395
396    /**
397     * Ignore special media folders.
398     *
399     * @param string $path
400     *
401     * @return bool
402     */
403    private function ignorePath(string $path): bool
404    {
405        return array_intersect(self::IGNORE_FOLDERS, explode('/', $path)) !== [];
406    }
407}
408