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