xref: /webtrees/app/Http/RequestHandlers/ExportGedcomClient.php (revision 6f59525087dd4ee1d17c7375524d95ace7942861)
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;
38
39use function addcslashes;
40use function assert;
41use function fclose;
42use function pathinfo;
43use function strtolower;
44use function tmpfile;
45
46use const PATHINFO_EXTENSION;
47
48/**
49 * Download a GEDCOM file to the client.
50 */
51class ExportGedcomClient implements RequestHandlerInterface
52{
53    use ViewResponseTrait;
54
55    private GedcomExportService $gedcom_export_service;
56
57    private ResponseFactoryInterface $response_factory;
58
59    private StreamFactoryInterface $stream_factory;
60
61    /**
62     * ExportGedcomServer constructor.
63     *
64     * @param GedcomExportService      $gedcom_export_service
65     * @param ResponseFactoryInterface $response_factory
66     * @param StreamFactoryInterface   $stream_factory
67     */
68    public function __construct(
69        GedcomExportService $gedcom_export_service,
70        ResponseFactoryInterface $response_factory,
71        StreamFactoryInterface $stream_factory
72    ) {
73        $this->gedcom_export_service = $gedcom_export_service;
74        $this->response_factory = $response_factory;
75        $this->stream_factory = $stream_factory;
76    }
77
78    /**
79     * @param ServerRequestInterface $request
80     *
81     * @return ResponseInterface
82     * @throws FilesystemException
83     */
84    public function handle(ServerRequestInterface $request): ResponseInterface
85    {
86        $tree = $request->getAttribute('tree');
87        assert($tree instanceof Tree);
88
89        $data_filesystem = Registry::filesystem()->data();
90
91        $params = (array) $request->getParsedBody();
92
93        $convert          = (bool) ($params['convert'] ?? false);
94        $zip              = (bool) ($params['zip'] ?? false);
95        $media            = (bool) ($params['media'] ?? false);
96        $media_path       = $params['media-path'] ?? '';
97        $privatize_export = $params['privatize_export'];
98
99        $access_levels = [
100            'gedadmin' => Auth::PRIV_NONE,
101            'user'     => Auth::PRIV_USER,
102            'visitor'  => Auth::PRIV_PRIVATE,
103            'none'     => Auth::PRIV_HIDE,
104        ];
105
106        $access_level = $access_levels[$privatize_export];
107        $encoding     = $convert ? 'ANSI' : 'UTF-8';
108
109        // What to call the downloaded file
110        $download_filename = $tree->name();
111
112        // Force a ".ged" suffix
113        if (strtolower(pathinfo($download_filename, PATHINFO_EXTENSION)) !== 'ged') {
114            $download_filename .= '.ged';
115        }
116
117        if ($zip || $media) {
118            $resource = $this->gedcom_export_service->export($tree, true, $encoding, $access_level, $media_path);
119
120            $path = $tree->getPreference('MEDIA_DIRECTORY');
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, $resource);
128            fclose($resource);
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            $stream   = $this->stream_factory->createStreamFromFile($temp_zip_file);
151            $filename = addcslashes($download_filename, '"') . '.zip';
152
153            return $this->response_factory->createResponse()
154                ->withBody($stream)
155                ->withHeader('Content-Type', 'application/zip')
156                ->withHeader('Content-Disposition', 'attachment; filename="' . $filename . '"');
157        }
158
159        $resource = $this->gedcom_export_service->export($tree, true, $encoding, $access_level, $media_path);
160
161        $charset = $convert ? 'ISO-8859-1' : 'UTF-8';
162        $stream  = $this->stream_factory->createStreamFromResource($resource);
163
164        return $this->response_factory->createResponse()
165            ->withBody($stream)
166            ->withHeader('Content-Type', 'text/x-gedcom; charset=' . $charset)
167            ->withHeader('Content-Disposition', 'attachment; filename="' . addcslashes($download_filename, '"') . '"');
168    }
169}
170