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