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