xref: /webtrees/app/Http/RequestHandlers/ExportGedcomClient.php (revision f221c7f7051ab4fff9243d1e8c155f5f70b8aaf9)
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\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 = $request->getAttribute('filesystem.data');
82        assert($data_filesystem instanceof FilesystemInterface);
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_adapter    = new ZipArchiveAdapter($temp_zip_file);
127            $zip_filesystem = new Filesystem($zip_adapter);
128            $zip_filesystem->putStream($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(Factory::media()->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->has($from) && !$zip_filesystem->has($to)) {
145                            $zip_filesystem->writeStream($to, $media_filesystem->readStream($from));
146                        }
147                    }
148                }
149            }
150
151            // Need to force-close ZipArchive filesystems.
152            $zip_adapter->getArchive()->close();
153
154            // Use a stream, so that we do not have to load the entire file into memory.
155            $stream_factory = app(StreamFactoryInterface::class);
156            assert($stream_factory instanceof StreamFactoryInterface);
157
158            $http_stream   = $stream_factory->createStreamFromFile($temp_zip_file);
159            $filename = addcslashes($download_filename, '"') . '.zip';
160
161            /** @var ResponseFactoryInterface $response_factory */
162            $response_factory = app(ResponseFactoryInterface::class);
163
164            return $response_factory->createResponse()
165                ->withBody($http_stream)
166                ->withHeader('Content-Type', 'application/zip')
167                ->withHeader('Content-Disposition', 'attachment; filename="' . $filename . '"');
168        }
169
170        $resource = fopen('php://temp', 'wb+');
171
172        if ($resource === false) {
173            throw new RuntimeException('Failed to create temporary stream');
174        }
175
176        $this->gedcom_export_service->export($tree, $resource, true, $encoding, $access_level, $media_path);
177        rewind($resource);
178
179        $charset = $convert ? 'ISO-8859-1' : 'UTF-8';
180
181        $stream_factory = app(StreamFactoryInterface::class);
182        assert($stream_factory instanceof StreamFactoryInterface);
183
184        $http_stream = $stream_factory->createStreamFromResource($resource);
185
186        /** @var ResponseFactoryInterface $response_factory */
187        $response_factory = app(ResponseFactoryInterface::class);
188
189        return $response_factory->createResponse()
190            ->withBody($http_stream)
191            ->withHeader('Content-Type', 'text/x-gedcom; charset=' . $charset)
192            ->withHeader('Content-Disposition', 'attachment; filename="' . addcslashes($download_filename, '"') . '"');
193    }
194}
195