xref: /webtrees/app/Http/RequestHandlers/ExportGedcomClient.php (revision e3c147d0d53873311b7c137c41b4439e01d4189e)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2019 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\Functions\FunctionsExport;
24use Fisharebest\Webtrees\GedcomRecord;
25use Fisharebest\Webtrees\Http\ViewResponseTrait;
26use Fisharebest\Webtrees\Media;
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;
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 sys_get_temp_dir;
48use function tempnam;
49use function tmpfile;
50
51use const PATHINFO_EXTENSION;
52
53/**
54 * Download a GEDCOM file to the client.
55 */
56class ExportGedcomClient implements RequestHandlerInterface
57{
58    use ViewResponseTrait;
59
60    /**
61     * @param ServerRequestInterface $request
62     *
63     * @return ResponseInterface
64     */
65    public function handle(ServerRequestInterface $request): ResponseInterface
66    {
67        $tree = $request->getAttribute('tree');
68        assert($tree instanceof Tree);
69
70        $data_filesystem = $request->getAttribute('filesystem.data');
71        assert($data_filesystem instanceof FilesystemInterface);
72
73        $params = (array) $request->getParsedBody();
74
75        $convert          = (bool) ($params['convert'] ?? false);
76        $zip              = (bool) ($params['zip'] ?? false);
77        $media            = (bool) ($params['media'] ?? false);
78        $media_path       = $params['media-path'] ?? '';
79        $privatize_export = $params['privatize_export'];
80
81        $access_levels = [
82            'gedadmin' => Auth::PRIV_NONE,
83            'user'     => Auth::PRIV_USER,
84            'visitor'  => Auth::PRIV_PRIVATE,
85            'none'     => Auth::PRIV_HIDE,
86        ];
87
88        $access_level = $access_levels[$privatize_export];
89        $encoding     = $convert ? 'ANSI' : 'UTF-8';
90
91        // What to call the downloaded file
92        $download_filename = $tree->name();
93
94        // Force a ".ged" suffix
95        if (strtolower(pathinfo($download_filename, PATHINFO_EXTENSION)) !== 'ged') {
96            $download_filename .= '.ged';
97        }
98
99        if ($zip || $media) {
100            // Export the GEDCOM to an in-memory stream.
101            $tmp_stream = tmpfile();
102            FunctionsExport::exportGedcom($tree, $tmp_stream, $access_level, $media_path, $encoding);
103            rewind($tmp_stream);
104
105            $path = $tree->getPreference('MEDIA_DIRECTORY', 'media/');
106
107            // Create a new/empty .ZIP file
108            $temp_zip_file  = tempnam(sys_get_temp_dir(), 'webtrees-zip-');
109            $zip_adapter    = new ZipArchiveAdapter($temp_zip_file);
110            $zip_filesystem = new Filesystem($zip_adapter);
111            $zip_filesystem->writeStream($download_filename, $tmp_stream);
112            fclose($tmp_stream);
113
114            if ($media) {
115                $manager = new MountManager([
116                    'media' => $tree->mediaFilesystem($data_filesystem),
117                    'zip'   => $zip_filesystem,
118                ]);
119
120                $records = DB::table('media')
121                    ->where('m_file', '=', $tree->id())
122                    ->get()
123                    ->map(Media::rowMapper($tree))
124                    ->filter(GedcomRecord::accessFilter());
125
126                foreach ($records as $record) {
127                    foreach ($record->mediaFiles() as $media_file) {
128                        $from = 'media://' . $media_file->filename();
129                        $to   = 'zip://' . $path . $media_file->filename();
130                        if (!$media_file->isExternal() && $manager->has($from)) {
131                            $manager->copy($from, $to);
132                        }
133                    }
134                }
135            }
136
137            // Need to force-close ZipArchive filesystems.
138            $zip_adapter->getArchive()->close();
139
140            // Use a stream, so that we do not have to load the entire file into memory.
141            $stream   = app(StreamFactoryInterface::class)->createStreamFromFile($temp_zip_file);
142            $filename = addcslashes($download_filename, '"') . '.zip';
143
144            /** @var ResponseFactoryInterface $response_factory */
145            $response_factory = app(ResponseFactoryInterface::class);
146
147            return $response_factory->createResponse()
148                ->withBody($stream)
149                ->withHeader('Content-Type', 'application/zip')
150                ->withHeader('Content-Disposition', 'attachment; filename="' . $filename . '"');
151        }
152
153        $resource = fopen('php://temp', 'wb+');
154        FunctionsExport::exportGedcom($tree, $resource, $access_level, $media_path, $encoding);
155        rewind($resource);
156
157        $charset = $convert ? 'ISO-8859-1' : 'UTF-8';
158
159        /** @var StreamFactoryInterface $response_factory */
160        $stream_factory = app(StreamFactoryInterface::class);
161
162        $stream = $stream_factory->createStreamFromResource($resource);
163
164        /** @var ResponseFactoryInterface $response_factory */
165        $response_factory = app(ResponseFactoryInterface::class);
166
167        return $response_factory->createResponse()
168            ->withBody($stream)
169            ->withHeader('Content-Type', 'text/x-gedcom; charset=' . $charset)
170            ->withHeader('Content-Disposition', 'attachment; filename="' . addcslashes($download_filename, '"') . '"');
171    }
172}
173