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