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