xref: /webtrees/app/Http/RequestHandlers/ExportGedcomClient.php (revision 541cf44d763a8aa5906f3fce58ca6b0ac3a25986)
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\Encodings\ANSEL;
24use Fisharebest\Webtrees\Encodings\ASCII;
25use Fisharebest\Webtrees\Encodings\UTF16BE;
26use Fisharebest\Webtrees\Encodings\UTF8;
27use Fisharebest\Webtrees\Encodings\Windows1252;
28use Fisharebest\Webtrees\GedcomRecord;
29use Fisharebest\Webtrees\Http\ViewResponseTrait;
30use Fisharebest\Webtrees\Registry;
31use Fisharebest\Webtrees\Services\GedcomExportService;
32use Fisharebest\Webtrees\Validator;
33use Illuminate\Database\Capsule\Manager as DB;
34use League\Flysystem\Filesystem;
35use League\Flysystem\FilesystemException;
36use League\Flysystem\ZipArchive\FilesystemZipArchiveProvider;
37use League\Flysystem\ZipArchive\ZipArchiveAdapter;
38use Psr\Http\Message\ResponseFactoryInterface;
39use Psr\Http\Message\ResponseInterface;
40use Psr\Http\Message\ServerRequestInterface;
41use Psr\Http\Message\StreamFactoryInterface;
42use Psr\Http\Server\RequestHandlerInterface;
43
44use function addcslashes;
45use function fclose;
46use function pathinfo;
47use function strtolower;
48use function tmpfile;
49
50use const PATHINFO_EXTENSION;
51
52/**
53 * Download a GEDCOM file to the client.
54 */
55class ExportGedcomClient implements RequestHandlerInterface
56{
57    use ViewResponseTrait;
58
59    private GedcomExportService $gedcom_export_service;
60
61    private ResponseFactoryInterface $response_factory;
62
63    private StreamFactoryInterface $stream_factory;
64
65    /**
66     * ExportGedcomServer constructor.
67     *
68     * @param GedcomExportService      $gedcom_export_service
69     * @param ResponseFactoryInterface $response_factory
70     * @param StreamFactoryInterface   $stream_factory
71     */
72    public function __construct(
73        GedcomExportService $gedcom_export_service,
74        ResponseFactoryInterface $response_factory,
75        StreamFactoryInterface $stream_factory
76    ) {
77        $this->gedcom_export_service = $gedcom_export_service;
78        $this->response_factory = $response_factory;
79        $this->stream_factory = $stream_factory;
80    }
81
82    /**
83     * @param ServerRequestInterface $request
84     *
85     * @return ResponseInterface
86     * @throws FilesystemException
87     */
88    public function handle(ServerRequestInterface $request): ResponseInterface
89    {
90        $tree = Validator::attributes($request)->tree();
91
92        $data_filesystem = Registry::filesystem()->data();
93
94        $format       = Validator::parsedBody($request)->isInArray(['gedcom', 'zip'])->string('format');
95        $privacy      = Validator::parsedBody($request)->isInArray(['none', 'gedadmin', 'user', 'visitor'])->string('privacy');
96        $encoding     = Validator::parsedBody($request)->isInArray([UTF8::NAME, UTF16BE::NAME, ANSEL::NAME, ASCII::NAME, Windows1252::NAME])->string('encoding');
97        $line_endings = Validator::parsedBody($request)->isInArray(['CRLF', 'LF'])->string('line_endings');
98        $media_path   = Validator::parsedBody($request)->string('media_path');
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[$privacy];
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 ($format === 'zip') {
118            $resource = $this->gedcom_export_service->export($tree, true, $encoding, $access_level, $media_path, $line_endings);
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            $media_filesystem = $tree->mediaFilesystem($data_filesystem);
131
132            $records = DB::table('media')
133                ->where('m_file', '=', $tree->id())
134                ->get()
135                ->map(Registry::mediaFactory()->mapper($tree))
136                ->filter(GedcomRecord::accessFilter());
137
138            foreach ($records as $record) {
139                foreach ($record->mediaFiles() as $media_file) {
140                    $from = $media_file->filename();
141                    $to   = $path . $media_file->filename();
142                    if (!$media_file->isExternal() && $media_filesystem->fileExists($from) && !$zip_filesystem->fileExists($to)) {
143                        $zip_filesystem->writeStream($to, $media_filesystem->readStream($from));
144                    }
145                }
146            }
147
148            $stream   = $this->stream_factory->createStreamFromFile($temp_zip_file);
149            $filename = addcslashes($download_filename, '"') . '.zip';
150
151            return $this->response_factory->createResponse()
152                ->withBody($stream)
153                ->withHeader('Content-Type', 'application/zip')
154                ->withHeader('Content-Disposition', 'attachment; filename="' . $filename . '"');
155        }
156
157        $resource = $this->gedcom_export_service->export($tree, true, $encoding, $access_level, $media_path);
158        $stream   = $this->stream_factory->createStreamFromResource($resource);
159
160        return $this->response_factory->createResponse()
161            ->withBody($stream)
162            ->withHeader('Content-Type', 'text/x-gedcom; charset=' . UTF8::NAME)
163            ->withHeader('Content-Disposition', 'attachment; filename="' . addcslashes($download_filename, '"') . '"');
164    }
165}
166