xref: /webtrees/app/Http/RequestHandlers/ExportGedcomClient.php (revision c82bd01cdd2eabcbf00ea99e1cddc578ce91b455)
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\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\ZipArchiveAdapter;
31use Psr\Http\Message\ResponseFactoryInterface;
32use Psr\Http\Message\ResponseInterface;
33use Psr\Http\Message\ServerRequestInterface;
34use Psr\Http\Message\StreamFactoryInterface;
35use Psr\Http\Server\RequestHandlerInterface;
36use RuntimeException;
37
38use function addcslashes;
39use function app;
40use function assert;
41use function fclose;
42use function fopen;
43use function pathinfo;
44use function rewind;
45use function strtolower;
46use function tmpfile;
47
48use const PATHINFO_EXTENSION;
49
50/**
51 * Download a GEDCOM file to the client.
52 */
53class ExportGedcomClient implements RequestHandlerInterface
54{
55    use ViewResponseTrait;
56
57    /** @var GedcomExportService */
58    private $gedcom_export_service;
59
60    /**
61     * ExportGedcomServer constructor.
62     *
63     * @param GedcomExportService $gedcom_export_service
64     */
65    public function __construct(GedcomExportService $gedcom_export_service)
66    {
67        $this->gedcom_export_service = $gedcom_export_service;
68    }
69
70    /**
71     * @param ServerRequestInterface $request
72     *
73     * @return ResponseInterface
74     */
75    public function handle(ServerRequestInterface $request): ResponseInterface
76    {
77        $tree = $request->getAttribute('tree');
78        assert($tree instanceof Tree);
79
80        $data_filesystem = Registry::filesystem()->data();
81
82        $params = (array) $request->getParsedBody();
83
84        $convert          = (bool) ($params['convert'] ?? false);
85        $zip              = (bool) ($params['zip'] ?? false);
86        $media            = (bool) ($params['media'] ?? false);
87        $media_path       = $params['media-path'] ?? '';
88        $privatize_export = $params['privatize_export'];
89
90        $access_levels = [
91            'gedadmin' => Auth::PRIV_NONE,
92            'user'     => Auth::PRIV_USER,
93            'visitor'  => Auth::PRIV_PRIVATE,
94            'none'     => Auth::PRIV_HIDE,
95        ];
96
97        $access_level = $access_levels[$privatize_export];
98        $encoding     = $convert ? 'ANSI' : 'UTF-8';
99
100        // What to call the downloaded file
101        $download_filename = $tree->name();
102
103        // Force a ".ged" suffix
104        if (strtolower(pathinfo($download_filename, PATHINFO_EXTENSION)) !== 'ged') {
105            $download_filename .= '.ged';
106        }
107
108        if ($zip || $media) {
109            // Export the GEDCOM to an in-memory stream.
110            $tmp_stream = fopen('php://temp', 'wb+');
111
112            if ($tmp_stream === false) {
113                throw new RuntimeException('Failed to create temporary stream');
114            }
115
116            $this->gedcom_export_service->export($tree, $tmp_stream, true, $encoding, $access_level, $media_path);
117
118            rewind($tmp_stream);
119
120            $path = $tree->getPreference('MEDIA_DIRECTORY', 'media/');
121
122            // Create a new/empty .ZIP file
123            $temp_zip_file  = stream_get_meta_data(tmpfile())['uri'];
124            $zip_adapter    = new ZipArchiveAdapter($temp_zip_file);
125            $zip_filesystem = new Filesystem($zip_adapter);
126            $zip_filesystem->putStream($download_filename, $tmp_stream);
127            fclose($tmp_stream);
128
129            if ($media) {
130                $media_filesystem = $tree->mediaFilesystem($data_filesystem);
131
132                $records = DB::table('media')
133                    ->where('m_file', '=', $tree->id())
134                    ->get()
135                    ->map(Registry::mediaFactory()->mapper($tree))
136                    ->filter(GedcomRecord::accessFilter());
137
138                foreach ($records as $record) {
139                    foreach ($record->mediaFiles() as $media_file) {
140                        $from = $media_file->filename();
141                        $to   = $path . $media_file->filename();
142                        if (!$media_file->isExternal() && $media_filesystem->has($from) && !$zip_filesystem->has($to)) {
143                            $zip_filesystem->writeStream($to, $media_filesystem->readStream($from));
144                        }
145                    }
146                }
147            }
148
149            // Need to force-close ZipArchive filesystems.
150            $zip_adapter->getArchive()->close();
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