xref: /webtrees/app/Http/RequestHandlers/ExportGedcomClient.php (revision 56afe05fa72eb037740c3a05c02828a7ba30f9a9)
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\ResponseInterface;
34use Psr\Http\Message\ServerRequestInterface;
35use Psr\Http\Server\RequestHandlerInterface;
36use RuntimeException;
37
38use function addcslashes;
39use function assert;
40use function fclose;
41use function fopen;
42use function pathinfo;
43use function rewind;
44use function strtolower;
45use function tmpfile;
46
47use const PATHINFO_EXTENSION;
48
49/**
50 * Download a GEDCOM file to the client.
51 */
52class ExportGedcomClient implements RequestHandlerInterface
53{
54    use ViewResponseTrait;
55
56    /** @var GedcomExportService */
57    private $gedcom_export_service;
58
59    /**
60     * ExportGedcomServer constructor.
61     *
62     * @param GedcomExportService $gedcom_export_service
63     */
64    public function __construct(GedcomExportService $gedcom_export_service)
65    {
66        $this->gedcom_export_service = $gedcom_export_service;
67    }
68
69    /**
70     * @param ServerRequestInterface $request
71     *
72     * @return ResponseInterface
73     * @throws FilesystemException
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_provider   = new FilesystemZipArchiveProvider($temp_zip_file, 0755);
125            $zip_adapter    = new ZipArchiveAdapter($zip_provider);
126            $zip_filesystem = new Filesystem($zip_adapter);
127            $zip_filesystem->writeStream($download_filename, $tmp_stream);
128            fclose($tmp_stream);
129
130            if ($media) {
131                $media_filesystem = $tree->mediaFilesystem($data_filesystem);
132
133                $records = DB::table('media')
134                    ->where('m_file', '=', $tree->id())
135                    ->get()
136                    ->map(Registry::mediaFactory()->mapper($tree))
137                    ->filter(GedcomRecord::accessFilter());
138
139                foreach ($records as $record) {
140                    foreach ($record->mediaFiles() as $media_file) {
141                        $from = $media_file->filename();
142                        $to   = $path . $media_file->filename();
143                        if (!$media_file->isExternal() && $media_filesystem->fileExists($from) && !$zip_filesystem->fileExists($to)) {
144                            $zip_filesystem->writeStream($to, $media_filesystem->readStream($from));
145                        }
146                    }
147                }
148            }
149
150            // Use a stream, so that we do not have to load the entire file into memory.
151            $http_stream = Registry::streamFactory()->createStreamFromFile($temp_zip_file);
152            $filename    = addcslashes($download_filename, '"') . '.zip';
153
154            return Registry::responseFactory()
155                ->createResponse()
156                ->withBody($http_stream)
157                ->withHeader('Content-Type', 'application/zip')
158                ->withHeader('Content-Disposition', 'attachment; filename="' . $filename . '"');
159        }
160
161        $resource = fopen('php://temp', 'wb+');
162
163        if ($resource === false) {
164            throw new RuntimeException('Failed to create temporary stream');
165        }
166
167        $this->gedcom_export_service->export($tree, $resource, true, $encoding, $access_level, $media_path);
168        rewind($resource);
169
170        $charset = $convert ? 'ISO-8859-1' : 'UTF-8';
171
172        $http_stream = Registry::streamFactory()->createStreamFromResource($resource);
173
174        return Registry::responseFactory()
175            ->createResponse()
176            ->withBody($http_stream)
177            ->withHeader('Content-Type', 'text/x-gedcom; charset=' . $charset)
178            ->withHeader('Content-Disposition', 'attachment; filename="' . addcslashes($download_filename, '"') . '"');
179    }
180}
181