xref: /webtrees/app/Http/RequestHandlers/ExportGedcomClient.php (revision c4943cff72f95a28fbb9404e3c20b169ff098e5c)
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\Http\RequestHandlers;
21
22use Fisharebest\Webtrees\Auth;
23use Fisharebest\Webtrees\GedcomRecord;
24use Fisharebest\Webtrees\Http\ViewResponseTrait;
25use Fisharebest\Webtrees\Registry;
26use Fisharebest\Webtrees\Services\GedcomExportService;
27use Fisharebest\Webtrees\Tree;
28use Illuminate\Database\Capsule\Manager as DB;
29use League\Flysystem\Filesystem;
30use League\Flysystem\FilesystemException;
31use League\Flysystem\ZipArchive\FilesystemZipArchiveProvider;
32use League\Flysystem\ZipArchive\ZipArchiveAdapter;
33use Psr\Http\Message\ResponseFactoryInterface;
34use Psr\Http\Message\ResponseInterface;
35use Psr\Http\Message\ServerRequestInterface;
36use Psr\Http\Message\StreamFactoryInterface;
37use Psr\Http\Server\RequestHandlerInterface;
38use RuntimeException;
39
40use function addcslashes;
41use function app;
42use function assert;
43use function fclose;
44use function fopen;
45use function pathinfo;
46use function rewind;
47use function strtolower;
48use function tmpfile;
49
50use const PATHINFO_EXTENSION;
51
52/**
53 * Download a GEDCOM file to the client.
54 */
55class ExportGedcomClient implements RequestHandlerInterface
56{
57    use ViewResponseTrait;
58
59    private GedcomExportService $gedcom_export_service;
60
61    /**
62     * ExportGedcomServer constructor.
63     *
64     * @param GedcomExportService $gedcom_export_service
65     */
66    public function __construct(GedcomExportService $gedcom_export_service)
67    {
68        $this->gedcom_export_service = $gedcom_export_service;
69    }
70
71    /**
72     * @param ServerRequestInterface $request
73     *
74     * @return ResponseInterface
75     * @throws FilesystemException
76     */
77    public function handle(ServerRequestInterface $request): ResponseInterface
78    {
79        $tree = $request->getAttribute('tree');
80        assert($tree instanceof Tree);
81
82        $data_filesystem = Registry::filesystem()->data();
83
84        $params = (array) $request->getParsedBody();
85
86        $convert          = (bool) ($params['convert'] ?? false);
87        $zip              = (bool) ($params['zip'] ?? false);
88        $media            = (bool) ($params['media'] ?? false);
89        $media_path       = $params['media-path'] ?? '';
90        $privatize_export = $params['privatize_export'];
91
92        $access_levels = [
93            'gedadmin' => Auth::PRIV_NONE,
94            'user'     => Auth::PRIV_USER,
95            'visitor'  => Auth::PRIV_PRIVATE,
96            'none'     => Auth::PRIV_HIDE,
97        ];
98
99        $access_level = $access_levels[$privatize_export];
100        $encoding     = $convert ? 'ANSI' : 'UTF-8';
101
102        // What to call the downloaded file
103        $download_filename = $tree->name();
104
105        // Force a ".ged" suffix
106        if (strtolower(pathinfo($download_filename, PATHINFO_EXTENSION)) !== 'ged') {
107            $download_filename .= '.ged';
108        }
109
110        if ($zip || $media) {
111            // Export the GEDCOM to an in-memory stream.
112            $tmp_stream = fopen('php://temp', 'wb+');
113
114            if ($tmp_stream === false) {
115                throw new RuntimeException('Failed to create temporary stream');
116            }
117
118            $this->gedcom_export_service->export($tree, $tmp_stream, true, $encoding, $access_level, $media_path);
119
120            rewind($tmp_stream);
121
122            $path = $tree->getPreference('MEDIA_DIRECTORY', 'media/');
123
124            // Create a new/empty .ZIP file
125            $temp_zip_file  = stream_get_meta_data(tmpfile())['uri'];
126            $zip_provider   = new FilesystemZipArchiveProvider($temp_zip_file, 0755);
127            $zip_adapter    = new ZipArchiveAdapter($zip_provider);
128            $zip_filesystem = new Filesystem($zip_adapter);
129            $zip_filesystem->writeStream($download_filename, $tmp_stream);
130            fclose($tmp_stream);
131
132            if ($media) {
133                $media_filesystem = $tree->mediaFilesystem($data_filesystem);
134
135                $records = DB::table('media')
136                    ->where('m_file', '=', $tree->id())
137                    ->get()
138                    ->map(Registry::mediaFactory()->mapper($tree))
139                    ->filter(GedcomRecord::accessFilter());
140
141                foreach ($records as $record) {
142                    foreach ($record->mediaFiles() as $media_file) {
143                        $from = $media_file->filename();
144                        $to   = $path . $media_file->filename();
145                        if (!$media_file->isExternal() && $media_filesystem->fileExists($from) && !$zip_filesystem->fileExists($to)) {
146                            $zip_filesystem->writeStream($to, $media_filesystem->readStream($from));
147                        }
148                    }
149                }
150            }
151
152            // Use a stream, so that we do not have to load the entire file into memory.
153            $stream_factory = app(StreamFactoryInterface::class);
154            assert($stream_factory instanceof StreamFactoryInterface);
155
156            $http_stream   = $stream_factory->createStreamFromFile($temp_zip_file);
157            $filename = addcslashes($download_filename, '"') . '.zip';
158
159            /** @var ResponseFactoryInterface $response_factory */
160            $response_factory = app(ResponseFactoryInterface::class);
161
162            return $response_factory->createResponse()
163                ->withBody($http_stream)
164                ->withHeader('Content-Type', 'application/zip')
165                ->withHeader('Content-Disposition', 'attachment; filename="' . $filename . '"');
166        }
167
168        $resource = fopen('php://temp', 'wb+');
169
170        if ($resource === false) {
171            throw new RuntimeException('Failed to create temporary stream');
172        }
173
174        $this->gedcom_export_service->export($tree, $resource, true, $encoding, $access_level, $media_path);
175        rewind($resource);
176
177        $charset = $convert ? 'ISO-8859-1' : 'UTF-8';
178
179        $stream_factory = app(StreamFactoryInterface::class);
180        assert($stream_factory instanceof StreamFactoryInterface);
181
182        $http_stream = $stream_factory->createStreamFromResource($resource);
183
184        /** @var ResponseFactoryInterface $response_factory */
185        $response_factory = app(ResponseFactoryInterface::class);
186
187        return $response_factory->createResponse()
188            ->withBody($http_stream)
189            ->withHeader('Content-Type', 'text/x-gedcom; charset=' . $charset)
190            ->withHeader('Content-Disposition', 'attachment; filename="' . addcslashes($download_filename, '"') . '"');
191    }
192}
193