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