xref: /webtrees/app/Services/MediaFileService.php (revision 5d32b84ff60f08e5f1c1f1b1e8152f4309d82428)
1d4265d07SGreg Roach<?php
2d4265d07SGreg Roach
3d4265d07SGreg Roach/**
4d4265d07SGreg Roach * webtrees: online genealogy
5d4265d07SGreg Roach * Copyright (C) 2019 webtrees development team
6d4265d07SGreg Roach * This program is free software: you can redistribute it and/or modify
7d4265d07SGreg Roach * it under the terms of the GNU General Public License as published by
8d4265d07SGreg Roach * the Free Software Foundation, either version 3 of the License, or
9d4265d07SGreg Roach * (at your option) any later version.
10d4265d07SGreg Roach * This program is distributed in the hope that it will be useful,
11d4265d07SGreg Roach * but WITHOUT ANY WARRANTY; without even the implied warranty of
12d4265d07SGreg Roach * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13d4265d07SGreg Roach * GNU General Public License for more details.
14d4265d07SGreg Roach * You should have received a copy of the GNU General Public License
15d4265d07SGreg Roach * along with this program. If not, see <http://www.gnu.org/licenses/>.
16d4265d07SGreg Roach */
17d4265d07SGreg Roach
18d4265d07SGreg Roachdeclare(strict_types=1);
19d4265d07SGreg Roach
20d4265d07SGreg Roachnamespace Fisharebest\Webtrees\Services;
21d4265d07SGreg Roach
22d4265d07SGreg Roachuse Fisharebest\Webtrees\FlashMessages;
23d4265d07SGreg Roachuse Fisharebest\Webtrees\GedcomTag;
24d4265d07SGreg Roachuse Fisharebest\Webtrees\I18N;
25d4265d07SGreg Roachuse Fisharebest\Webtrees\Tree;
26d4265d07SGreg Roachuse Illuminate\Database\Capsule\Manager as DB;
2713aa75d8SGreg Roachuse Illuminate\Database\Query\Expression;
2813aa75d8SGreg Roachuse Illuminate\Support\Collection;
29d4265d07SGreg Roachuse InvalidArgumentException;
30a04bb9a2SGreg Roachuse League\Flysystem\FilesystemInterface;
31d4265d07SGreg Roachuse Psr\Http\Message\ServerRequestInterface;
32d4265d07SGreg Roachuse Psr\Http\Message\UploadedFileInterface;
33d4265d07SGreg Roachuse RuntimeException;
34d4265d07SGreg Roach
35d4265d07SGreg Roachuse function array_combine;
36d4265d07SGreg Roachuse function array_diff;
37d4265d07SGreg Roachuse function array_filter;
38d4265d07SGreg Roachuse function array_map;
39d4265d07SGreg Roachuse function assert;
4013aa75d8SGreg Roachuse function dirname;
41d501c45dSGreg Roachuse function ini_get;
42d4265d07SGreg Roachuse function intdiv;
43d501c45dSGreg Roachuse function min;
44d4265d07SGreg Roachuse function pathinfo;
45d4265d07SGreg Roachuse function preg_match;
46d4265d07SGreg Roachuse function sha1;
47d4265d07SGreg Roachuse function sort;
48d4265d07SGreg Roachuse function str_replace;
49d4265d07SGreg Roachuse function strpos;
50d4265d07SGreg Roachuse function strtolower;
51d501c45dSGreg Roachuse function substr;
52d4265d07SGreg Roachuse function trim;
53d4265d07SGreg Roach
54d4265d07SGreg Roachuse const PATHINFO_EXTENSION;
55d4265d07SGreg Roachuse const UPLOAD_ERR_OK;
56d4265d07SGreg Roach
57d4265d07SGreg Roach/**
58d4265d07SGreg Roach * Managing media files.
59d4265d07SGreg Roach */
60d4265d07SGreg Roachclass MediaFileService
61d4265d07SGreg Roach{
62d4265d07SGreg Roach    public const EDIT_RESTRICTIONS = [
63d4265d07SGreg Roach        'locked',
64d4265d07SGreg Roach    ];
65d4265d07SGreg Roach
66d4265d07SGreg Roach    public const PRIVACY_RESTRICTIONS = [
67d4265d07SGreg Roach        'none',
68d4265d07SGreg Roach        'privacy',
69d4265d07SGreg Roach        'confidential',
70d4265d07SGreg Roach    ];
71d4265d07SGreg Roach
72d4265d07SGreg Roach    /**
73d4265d07SGreg Roach     * What is the largest file a user may upload?
74d4265d07SGreg Roach     */
75d4265d07SGreg Roach    public function maxUploadFilesize(): string
76d4265d07SGreg Roach    {
77d501c45dSGreg Roach        $sizePostMax = $this->parseIniFileSize(ini_get('post_max_size'));
78d501c45dSGreg Roach        $sizeUploadMax = $this->parseIniFileSize(ini_get('upload_max_filesize'));
79d501c45dSGreg Roach
80d501c45dSGreg Roach        $bytes =  min($sizePostMax, $sizeUploadMax);
81d4265d07SGreg Roach        $kb    = intdiv($bytes + 1023, 1024);
82d4265d07SGreg Roach
83d4265d07SGreg Roach        return I18N::translate('%s KB', I18N::number($kb));
84d4265d07SGreg Roach    }
85d4265d07SGreg Roach
86d4265d07SGreg Roach    /**
87d501c45dSGreg Roach     * Returns the given size from an ini value in bytes.
88d501c45dSGreg Roach     *
89284014f8SGreg Roach     * @param string $size
90d501c45dSGreg Roach     *
91d501c45dSGreg Roach     * @return int
92d501c45dSGreg Roach     */
93284014f8SGreg Roach    private function parseIniFileSize(string $size): int
94d501c45dSGreg Roach    {
95d501c45dSGreg Roach        $number = (int) $size;
96d501c45dSGreg Roach
97d501c45dSGreg Roach        switch (substr($size, -1)) {
98d501c45dSGreg Roach            case 't':
99d501c45dSGreg Roach            case 'T':
100d501c45dSGreg Roach                return $number * 1024 ** 4;
101d501c45dSGreg Roach            case 'g':
102d501c45dSGreg Roach            case 'G':
103d501c45dSGreg Roach                return $number * 1024 ** 3;
104d501c45dSGreg Roach            case 'm':
105d501c45dSGreg Roach            case 'M':
106d501c45dSGreg Roach                return $number * 1024 ** 2;
107d501c45dSGreg Roach            case 'k':
108d501c45dSGreg Roach            case 'K':
109d501c45dSGreg Roach                return $number * 1024;
110d501c45dSGreg Roach            default:
111d501c45dSGreg Roach                return $number;
112d501c45dSGreg Roach        }
113d501c45dSGreg Roach    }
114d501c45dSGreg Roach
115d501c45dSGreg Roach    /**
116d4265d07SGreg Roach     * A list of key/value options for media types.
117d4265d07SGreg Roach     *
118d4265d07SGreg Roach     * @param string $current
119d4265d07SGreg Roach     *
120d4265d07SGreg Roach     * @return array
121d4265d07SGreg Roach     */
122d4265d07SGreg Roach    public function mediaTypes($current = ''): array
123d4265d07SGreg Roach    {
124d4265d07SGreg Roach        $media_types = GedcomTag::getFileFormTypes();
125d4265d07SGreg Roach
126d4265d07SGreg Roach        $media_types = ['' => ''] + [$current => $current] + $media_types;
127d4265d07SGreg Roach
128d4265d07SGreg Roach        return $media_types;
129d4265d07SGreg Roach    }
130d4265d07SGreg Roach
131d4265d07SGreg Roach    /**
132d4265d07SGreg Roach     * A list of media files not already linked to a media object.
133d4265d07SGreg Roach     *
134d4265d07SGreg Roach     * @param Tree                $tree
135a04bb9a2SGreg Roach     * @param FilesystemInterface $data_filesystem
136d4265d07SGreg Roach     *
137d4265d07SGreg Roach     * @return array
138d4265d07SGreg Roach     */
139a04bb9a2SGreg Roach    public function unusedFiles(Tree $tree, FilesystemInterface $data_filesystem): array
140d4265d07SGreg Roach    {
141d4265d07SGreg Roach        $used_files = DB::table('media_file')
142d4265d07SGreg Roach            ->where('m_file', '=', $tree->id())
143d4265d07SGreg Roach            ->where('multimedia_file_refn', 'NOT LIKE', 'http://%')
144d4265d07SGreg Roach            ->where('multimedia_file_refn', 'NOT LIKE', 'https://%')
145d4265d07SGreg Roach            ->pluck('multimedia_file_refn')
146d4265d07SGreg Roach            ->all();
147d4265d07SGreg Roach
148a04bb9a2SGreg Roach        $disk_files = $tree->mediaFilesystem($data_filesystem)->listContents('', true);
149d4265d07SGreg Roach
150d4265d07SGreg Roach        $disk_files = array_filter($disk_files, static function (array $item) {
151d4265d07SGreg Roach            // Older versions of webtrees used a couple of special folders.
152d4265d07SGreg Roach            return
153d4265d07SGreg Roach                $item['type'] === 'file' &&
154d4265d07SGreg Roach                strpos($item['path'], '/thumbs/') === false &&
155d4265d07SGreg Roach                strpos($item['path'], '/watermarks/') === false;
156d4265d07SGreg Roach        });
157d4265d07SGreg Roach
158d4265d07SGreg Roach        $disk_files = array_map(static function (array $item): string {
159d4265d07SGreg Roach            return $item['path'];
160d4265d07SGreg Roach        }, $disk_files);
161d4265d07SGreg Roach
162d4265d07SGreg Roach        $unused_files = array_diff($disk_files, $used_files);
163d4265d07SGreg Roach
164d4265d07SGreg Roach        sort($unused_files);
165d4265d07SGreg Roach
166d4265d07SGreg Roach        return array_combine($unused_files, $unused_files);
167d4265d07SGreg Roach    }
168d4265d07SGreg Roach
169d4265d07SGreg Roach    /**
170d4265d07SGreg Roach     * Store an uploaded file (or URL), either to be added to a media object
171d4265d07SGreg Roach     * or to create a media object.
172d4265d07SGreg Roach     *
173d4265d07SGreg Roach     * @param ServerRequestInterface $request
174d4265d07SGreg Roach     *
175d4265d07SGreg Roach     * @return string The value to be stored in the 'FILE' field of the media object.
176d4265d07SGreg Roach     */
177d4265d07SGreg Roach    public function uploadFile(ServerRequestInterface $request): string
178d4265d07SGreg Roach    {
179d4265d07SGreg Roach        $tree = $request->getAttribute('tree');
180d4265d07SGreg Roach        assert($tree instanceof Tree);
181d4265d07SGreg Roach
182a04bb9a2SGreg Roach        $data_filesystem = $request->getAttribute('filesystem.data');
183a04bb9a2SGreg Roach        assert($data_filesystem instanceof FilesystemInterface);
184a04bb9a2SGreg Roach
185b46c87bdSGreg Roach        $params        = (array) $request->getParsedBody();
186d4265d07SGreg Roach        $file_location = $params['file_location'];
187d4265d07SGreg Roach
188d4265d07SGreg Roach        switch ($file_location) {
189d4265d07SGreg Roach            case 'url':
190d4265d07SGreg Roach                $remote = $params['remote'];
191d4265d07SGreg Roach
192d4265d07SGreg Roach                if (strpos($remote, '://') !== false) {
193d4265d07SGreg Roach                    return $remote;
194d4265d07SGreg Roach                }
195d4265d07SGreg Roach
196d4265d07SGreg Roach                return '';
197d4265d07SGreg Roach
198d4265d07SGreg Roach            case 'unused':
199d4265d07SGreg Roach                $unused = $params['unused'];
200d4265d07SGreg Roach
201a04bb9a2SGreg Roach                if ($tree->mediaFilesystem($data_filesystem)->has($unused)) {
202d4265d07SGreg Roach                    return $unused;
203d4265d07SGreg Roach                }
204d4265d07SGreg Roach
205d4265d07SGreg Roach                return '';
206d4265d07SGreg Roach
207d4265d07SGreg Roach            case 'upload':
208d4265d07SGreg Roach            default:
209d4265d07SGreg Roach                $folder   = $params['folder'];
210d4265d07SGreg Roach                $auto     = $params['auto'];
211d4265d07SGreg Roach                $new_file = $params['new_file'];
212d4265d07SGreg Roach
213d4265d07SGreg Roach                /** @var UploadedFileInterface|null $uploaded_file */
214d4265d07SGreg Roach                $uploaded_file = $request->getUploadedFiles()['file'];
215d4265d07SGreg Roach                if ($uploaded_file === null || $uploaded_file->getError() !== UPLOAD_ERR_OK) {
216d4265d07SGreg Roach                    return '';
217d4265d07SGreg Roach                }
218d4265d07SGreg Roach
219d4265d07SGreg Roach                // The filename
220d4265d07SGreg Roach                $new_file = str_replace('\\', '/', $new_file);
221d4265d07SGreg Roach                if ($new_file !== '' && strpos($new_file, '/') === false) {
222d4265d07SGreg Roach                    $file = $new_file;
223d4265d07SGreg Roach                } else {
224d4265d07SGreg Roach                    $file = $uploaded_file->getClientFilename();
225d4265d07SGreg Roach                }
226d4265d07SGreg Roach
227d4265d07SGreg Roach                // The folder
228d4265d07SGreg Roach                $folder = str_replace('\\', '/', $folder);
229d4265d07SGreg Roach                $folder = trim($folder, '/');
230d4265d07SGreg Roach                if ($folder !== '') {
231d4265d07SGreg Roach                    $folder .= '/';
232d4265d07SGreg Roach                }
233d4265d07SGreg Roach
234d4265d07SGreg Roach                // Generate a unique name for the file?
235a04bb9a2SGreg Roach                if ($auto === '1' || $tree->mediaFilesystem($data_filesystem)->has($folder . $file)) {
236d4265d07SGreg Roach                    $folder    = '';
237d4265d07SGreg Roach                    $extension = pathinfo($uploaded_file->getClientFilename(), PATHINFO_EXTENSION);
238d4265d07SGreg Roach                    $file      = sha1((string) $uploaded_file->getStream()) . '.' . $extension;
239d4265d07SGreg Roach                }
240d4265d07SGreg Roach
241d4265d07SGreg Roach                try {
242a04bb9a2SGreg Roach                    $tree->mediaFilesystem($data_filesystem)->writeStream($folder . $file, $uploaded_file->getStream()->detach());
243d4265d07SGreg Roach
244d4265d07SGreg Roach                    return $folder . $file;
245d4265d07SGreg Roach                } catch (RuntimeException | InvalidArgumentException $ex) {
246d4265d07SGreg Roach                    FlashMessages::addMessage(I18N::translate('There was an error uploading your file.'));
247d4265d07SGreg Roach
248d4265d07SGreg Roach                    return '';
249d4265d07SGreg Roach                }
250d4265d07SGreg Roach        }
251d4265d07SGreg Roach    }
252d4265d07SGreg Roach
253d4265d07SGreg Roach    /**
254d4265d07SGreg Roach     * Convert the media file attributes into GEDCOM format.
255d4265d07SGreg Roach     *
256d4265d07SGreg Roach     * @param string $file
257d4265d07SGreg Roach     * @param string $type
258d4265d07SGreg Roach     * @param string $title
259d4265d07SGreg Roach     *
260d4265d07SGreg Roach     * @return string
261d4265d07SGreg Roach     */
262d4265d07SGreg Roach    public function createMediaFileGedcom(string $file, string $type, string $title): string
263d4265d07SGreg Roach    {
264d4265d07SGreg Roach        if (preg_match('/\.([a-z0-9]+)/i', $file, $match)) {
265d4265d07SGreg Roach            $extension = strtolower($match[1]);
266d4265d07SGreg Roach            $extension = str_replace('jpg', 'jpeg', $extension);
267d4265d07SGreg Roach            $extension = ' ' . $extension;
268d4265d07SGreg Roach        } else {
269d4265d07SGreg Roach            $extension = '';
270d4265d07SGreg Roach        }
271d4265d07SGreg Roach
272d4265d07SGreg Roach        $gedcom = '1 FILE ' . $file;
273d4265d07SGreg Roach        if ($type !== '') {
274d4265d07SGreg Roach            $gedcom .= "\n2 FORM" . $extension . "\n3 TYPE " . $type;
275d4265d07SGreg Roach        }
276d4265d07SGreg Roach        if ($title !== '') {
277d4265d07SGreg Roach            $gedcom .= "\n2 TITL " . $title;
278d4265d07SGreg Roach        }
279d4265d07SGreg Roach
280d4265d07SGreg Roach        return $gedcom;
281d4265d07SGreg Roach    }
28213aa75d8SGreg Roach
28313aa75d8SGreg Roach    /**
28413aa75d8SGreg Roach     * Fetch a list of all files on disk (in folders used by any tree).
28513aa75d8SGreg Roach     *
28613aa75d8SGreg Roach     * @param FilesystemInterface $data_filesystem Fileystem to search
28713aa75d8SGreg Roach     * @param string              $media_folder    Root folder
28813aa75d8SGreg Roach     * @param bool                $subfolders      Include subfolders
28913aa75d8SGreg Roach     *
290b5c8fd7eSGreg Roach     * @return Collection<string>
29113aa75d8SGreg Roach     */
29213aa75d8SGreg Roach    public function allFilesOnDisk(FilesystemInterface $data_filesystem, string $media_folder, bool $subfolders): Collection
29313aa75d8SGreg Roach    {
29413aa75d8SGreg Roach        $array = $data_filesystem->listContents($media_folder, $subfolders);
29513aa75d8SGreg Roach
29613aa75d8SGreg Roach        return Collection::make($array)
29713aa75d8SGreg Roach            ->filter(static function (array $metadata): bool {
29813aa75d8SGreg Roach                return
29913aa75d8SGreg Roach                    $metadata['type'] === 'file' &&
30013aa75d8SGreg Roach                    strpos($metadata['path'], '/thumbs/') === false &&
30113aa75d8SGreg Roach                    strpos($metadata['path'], '/watermark/') === false;
30213aa75d8SGreg Roach            })
30313aa75d8SGreg Roach            ->map(static function (array $metadata): string {
30413aa75d8SGreg Roach                return $metadata['path'];
30513aa75d8SGreg Roach            });
30613aa75d8SGreg Roach    }
30713aa75d8SGreg Roach
30813aa75d8SGreg Roach    /**
30913aa75d8SGreg Roach     * Fetch a list of all files on in the database.
31013aa75d8SGreg Roach     *
31113aa75d8SGreg Roach     * @param string $media_folder Root folder
31213aa75d8SGreg Roach     * @param bool   $subfolders   Include subfolders
31313aa75d8SGreg Roach     *
314b5c8fd7eSGreg Roach     * @return Collection<string>
31513aa75d8SGreg Roach     */
31613aa75d8SGreg Roach    public function allFilesInDatabase(string $media_folder, bool $subfolders): Collection
31713aa75d8SGreg Roach    {
31813aa75d8SGreg Roach        $query = DB::table('media_file')
31913aa75d8SGreg Roach            ->join('gedcom_setting', 'gedcom_id', '=', 'm_file')
32013aa75d8SGreg Roach            ->where('setting_name', '=', 'MEDIA_DIRECTORY')
32113aa75d8SGreg Roach            //->where('multimedia_file_refn', 'LIKE', '%/%')
32213aa75d8SGreg Roach            ->where('multimedia_file_refn', 'NOT LIKE', 'http://%')
32313aa75d8SGreg Roach            ->where('multimedia_file_refn', 'NOT LIKE', 'https://%')
32413aa75d8SGreg Roach            ->where(new Expression('setting_value || multimedia_file_refn'), 'LIKE', $media_folder . '%')
32513aa75d8SGreg Roach            ->select(new Expression('setting_value || multimedia_file_refn AS path'))
32613aa75d8SGreg Roach            ->orderBy(new Expression('setting_value || multimedia_file_refn'));
32713aa75d8SGreg Roach
32813aa75d8SGreg Roach        if (!$subfolders) {
32913aa75d8SGreg Roach            $query->where(new Expression('setting_value || multimedia_file_refn'), 'NOT LIKE', $media_folder . '%/%');
33013aa75d8SGreg Roach        }
33113aa75d8SGreg Roach
33213aa75d8SGreg Roach        return $query->pluck('path');
33313aa75d8SGreg Roach    }
33413aa75d8SGreg Roach
33513aa75d8SGreg Roach    /**
33613aa75d8SGreg Roach     * Generate a list of all folders in either the database or the filesystem.
33713aa75d8SGreg Roach     *
33813aa75d8SGreg Roach     * @param FilesystemInterface $data_filesystem
33913aa75d8SGreg Roach     *
340b5c8fd7eSGreg Roach     * @return Collection<string,string>
34113aa75d8SGreg Roach     */
34213aa75d8SGreg Roach    public function allMediaFolders(FilesystemInterface $data_filesystem): Collection
34313aa75d8SGreg Roach    {
34413aa75d8SGreg Roach        $db_folders = DB::table('media_file')
34513aa75d8SGreg Roach            ->join('gedcom_setting', 'gedcom_id', '=', 'm_file')
34613aa75d8SGreg Roach            ->where('setting_name', '=', 'MEDIA_DIRECTORY')
34713aa75d8SGreg Roach            ->where('multimedia_file_refn', 'NOT LIKE', 'http://%')
34813aa75d8SGreg Roach            ->where('multimedia_file_refn', 'NOT LIKE', 'https://%')
34913aa75d8SGreg Roach            ->select(new Expression('setting_value || multimedia_file_refn AS path'))
35013aa75d8SGreg Roach            ->pluck('path')
35113aa75d8SGreg Roach            ->map(static function (string $path): string {
35213aa75d8SGreg Roach                return dirname($path) . '/';
35313aa75d8SGreg Roach            });
35413aa75d8SGreg Roach
35513aa75d8SGreg Roach        $media_roots = DB::table('gedcom_setting')
35613aa75d8SGreg Roach            ->where('setting_name', '=', 'MEDIA_DIRECTORY')
357*5d32b84fSGreg Roach            ->where('gedcom_id', '>', '0')
35813aa75d8SGreg Roach            ->pluck('setting_value')
3598c627a69SGreg Roach            ->uniqueStrict();
36013aa75d8SGreg Roach
36113aa75d8SGreg Roach        $disk_folders = new Collection($media_roots);
36213aa75d8SGreg Roach
36313aa75d8SGreg Roach        foreach ($media_roots as $media_folder) {
36413aa75d8SGreg Roach            $tmp = Collection::make($data_filesystem->listContents($media_folder, true))
36513aa75d8SGreg Roach                ->filter(static function (array $metadata) {
36613aa75d8SGreg Roach                    return $metadata['type'] === 'dir';
36713aa75d8SGreg Roach                })
36813aa75d8SGreg Roach                ->map(static function (array $metadata): string {
36913aa75d8SGreg Roach                    return $metadata['path'] . '/';
37013aa75d8SGreg Roach                })
37113aa75d8SGreg Roach                ->filter(static function (string $dir): bool {
37213aa75d8SGreg Roach                    return strpos($dir, '/thumbs/') === false && strpos($dir, 'watermarks') === false;
37313aa75d8SGreg Roach                });
37413aa75d8SGreg Roach
37513aa75d8SGreg Roach            $disk_folders = $disk_folders->concat($tmp);
37613aa75d8SGreg Roach        }
37713aa75d8SGreg Roach
37813aa75d8SGreg Roach        return $disk_folders->concat($db_folders)
3798c627a69SGreg Roach            ->uniqueStrict()
38013aa75d8SGreg Roach            ->mapWithKeys(static function (string $folder): array {
38113aa75d8SGreg Roach                return [$folder => $folder];
38213aa75d8SGreg Roach            });
38313aa75d8SGreg Roach    }
384d4265d07SGreg Roach}
385