xref: /webtrees/app/Http/RequestHandlers/ExportGedcomClient.php (revision 7ecd4bd5c574a93e67125849e979f569ca026bf4)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2020 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 <http://www.gnu.org/licenses/>.
16 */
17
18declare(strict_types=1);
19
20namespace Fisharebest\Webtrees\Http\RequestHandlers;
21
22use Fisharebest\Webtrees\Auth;
23use Fisharebest\Webtrees\Factory;
24use Fisharebest\Webtrees\GedcomRecord;
25use Fisharebest\Webtrees\Http\ViewResponseTrait;
26use Fisharebest\Webtrees\Services\GedcomExportService;
27use Fisharebest\Webtrees\Tree;
28use Illuminate\Database\Capsule\Manager as DB;
29use League\Flysystem\Filesystem;
30use League\Flysystem\FilesystemInterface;
31use League\Flysystem\MountManager;
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     */
77    public function handle(ServerRequestInterface $request): ResponseInterface
78    {
79        $tree = $request->getAttribute('tree');
80        assert($tree instanceof Tree);
81
82        $data_filesystem = $request->getAttribute('filesystem.data');
83        assert($data_filesystem instanceof FilesystemInterface);
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_adapter    = new ZipArchiveAdapter($temp_zip_file);
128            $zip_filesystem = new Filesystem($zip_adapter);
129            $zip_filesystem->putStream($download_filename, $tmp_stream);
130            fclose($tmp_stream);
131
132            if ($media) {
133                $manager = new MountManager([
134                    'media' => $tree->mediaFilesystem($data_filesystem),
135                    'zip'   => $zip_filesystem,
136                ]);
137
138                $records = DB::table('media')
139                    ->where('m_file', '=', $tree->id())
140                    ->get()
141                    ->map(Factory::media()->mapper($tree))
142                    ->filter(GedcomRecord::accessFilter());
143
144                foreach ($records as $record) {
145                    foreach ($record->mediaFiles() as $media_file) {
146                        $from = 'media://' . $media_file->filename();
147                        $to   = 'zip://' . $path . $media_file->filename();
148                        if (!$media_file->isExternal() && $manager->has($from)) {
149                            $manager->copy($from, $to);
150                        }
151                    }
152                }
153            }
154
155            // Need to force-close ZipArchive filesystems.
156            $zip_adapter->getArchive()->close();
157
158            // Use a stream, so that we do not have to load the entire file into memory.
159            $stream_factory = app(StreamFactoryInterface::class);
160            assert($stream_factory instanceof StreamFactoryInterface);
161
162            $http_stream   = $stream_factory->createStreamFromFile($temp_zip_file);
163            $filename = addcslashes($download_filename, '"') . '.zip';
164
165            /** @var ResponseFactoryInterface $response_factory */
166            $response_factory = app(ResponseFactoryInterface::class);
167
168            return $response_factory->createResponse()
169                ->withBody($http_stream)
170                ->withHeader('Content-Type', 'application/zip')
171                ->withHeader('Content-Disposition', 'attachment; filename="' . $filename . '"');
172        }
173
174        $resource = fopen('php://temp', 'wb+');
175
176        if ($resource === false) {
177            throw new RuntimeException('Failed to create temporary stream');
178        }
179
180        $this->gedcom_export_service->export($tree, $resource, true, $encoding, $access_level, $media_path);
181        rewind($resource);
182
183        $charset = $convert ? 'ISO-8859-1' : 'UTF-8';
184
185        $stream_factory = app(StreamFactoryInterface::class);
186        assert($stream_factory instanceof StreamFactoryInterface);
187
188        $http_stream = $stream_factory->createStreamFromResource($resource);
189
190        /** @var ResponseFactoryInterface $response_factory */
191        $response_factory = app(ResponseFactoryInterface::class);
192
193        return $response_factory->createResponse()
194            ->withBody($http_stream)
195            ->withHeader('Content-Type', 'text/x-gedcom; charset=' . $charset)
196            ->withHeader('Content-Disposition', 'attachment; filename="' . addcslashes($download_filename, '"') . '"');
197    }
198}
199