xref: /webtrees/app/Module/ClippingsCartModule.php (revision 3bd0642964543723af30cd34772e464137543717)
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\Module;
21
22use Aura\Router\Route;
23use Fisharebest\Webtrees\Auth;
24use Fisharebest\Webtrees\Exceptions\FamilyNotFoundException;
25use Fisharebest\Webtrees\Exceptions\IndividualNotFoundException;
26use Fisharebest\Webtrees\Exceptions\MediaNotFoundException;
27use Fisharebest\Webtrees\Exceptions\NoteNotFoundException;
28use Fisharebest\Webtrees\Exceptions\RepositoryNotFoundException;
29use Fisharebest\Webtrees\Exceptions\SourceNotFoundException;
30use Fisharebest\Webtrees\Family;
31use Fisharebest\Webtrees\Functions\FunctionsExport;
32use Fisharebest\Webtrees\Gedcom;
33use Fisharebest\Webtrees\GedcomRecord;
34use Fisharebest\Webtrees\Http\RequestHandlers\FamilyPage;
35use Fisharebest\Webtrees\Http\RequestHandlers\IndividualPage;
36use Fisharebest\Webtrees\Http\RequestHandlers\MediaPage;
37use Fisharebest\Webtrees\Http\RequestHandlers\NotePage;
38use Fisharebest\Webtrees\Http\RequestHandlers\RepositoryPage;
39use Fisharebest\Webtrees\Http\RequestHandlers\SourcePage;
40use Fisharebest\Webtrees\I18N;
41use Fisharebest\Webtrees\Individual;
42use Fisharebest\Webtrees\Media;
43use Fisharebest\Webtrees\Menu;
44use Fisharebest\Webtrees\Note;
45use Fisharebest\Webtrees\Repository;
46use Fisharebest\Webtrees\Services\UserService;
47use Fisharebest\Webtrees\Session;
48use Fisharebest\Webtrees\Source;
49use Fisharebest\Webtrees\Tree;
50use League\Flysystem\Filesystem;
51use League\Flysystem\FilesystemInterface;
52use League\Flysystem\MountManager;
53use League\Flysystem\ZipArchive\ZipArchiveAdapter;
54use Psr\Http\Message\ResponseFactoryInterface;
55use Psr\Http\Message\ResponseInterface;
56use Psr\Http\Message\ServerRequestInterface;
57use Psr\Http\Message\StreamFactoryInterface;
58
59use function app;
60use function array_filter;
61use function array_keys;
62use function array_map;
63use function assert;
64use function in_array;
65use function is_string;
66use function key;
67use function preg_match_all;
68use function redirect;
69use function route;
70use function str_replace;
71use function strip_tags;
72use function sys_get_temp_dir;
73use function tempnam;
74use function utf8_decode;
75
76/**
77 * Class ClippingsCartModule
78 */
79class ClippingsCartModule extends AbstractModule implements ModuleMenuInterface
80{
81    use ModuleMenuTrait;
82
83    // Routes that have a record which can be added to the clipboard
84    private const ROUTES_WITH_RECORDS = [
85        'Family' => FamilyPage::class,
86        'Individual' => IndividualPage::class,
87        'Media' => MediaPage::class,
88        'Note' => NotePage::class,
89        'Repository' => RepositoryPage::class,
90        'Source' => SourcePage::class,
91    ];
92
93    /** @var int The default access level for this module.  It can be changed in the control panel. */
94    protected $access_level = Auth::PRIV_USER;
95
96    /**
97     * @var UserService
98     */
99    private $user_service;
100
101    /**
102     * ClippingsCartModule constructor.
103     *
104     * @param UserService $user_service
105     */
106    public function __construct(UserService $user_service)
107    {
108        $this->user_service = $user_service;
109    }
110
111    /**
112     * How should this module be identified in the control panel, etc.?
113     *
114     * @return string
115     */
116    public function title(): string
117    {
118        /* I18N: Name of a module */
119        return I18N::translate('Clippings cart');
120    }
121
122    /**
123     * A sentence describing what this module does.
124     *
125     * @return string
126     */
127    public function description(): string
128    {
129        /* I18N: Description of the “Clippings cart” module */
130        return I18N::translate('Select records from your family tree and save them as a GEDCOM file.');
131    }
132
133    /**
134     * The default position for this menu.  It can be changed in the control panel.
135     *
136     * @return int
137     */
138    public function defaultMenuOrder(): int
139    {
140        return 6;
141    }
142
143    /**
144     * A menu, to be added to the main application menu.
145     *
146     * @param Tree $tree
147     *
148     * @return Menu|null
149     */
150    public function getMenu(Tree $tree): ?Menu
151    {
152        /** @var ServerRequestInterface $request */
153        $request = app(ServerRequestInterface::class);
154
155        $route = $request->getAttribute('route');
156        assert($route instanceof Route);
157
158        $submenus = [
159            new Menu($this->title(), route('module', [
160                'module' => $this->name(),
161                'action' => 'Show',
162                'tree'    => $tree->name(),
163            ]), 'menu-clippings-cart', ['rel' => 'nofollow']),
164        ];
165
166        $action = array_search($route->name, self::ROUTES_WITH_RECORDS, true);
167        if ($action !== false) {
168            $xref = $route->attributes['xref'];
169            assert(is_string($xref));
170
171            $add_route = route('module', [
172                'module' => $this->name(),
173                'action' => 'Add' . $action,
174                'xref'   => $xref,
175                'tree'    => $tree->name(),
176            ]);
177
178            $submenus[] = new Menu(I18N::translate('Add to the clippings cart'), $add_route, 'menu-clippings-add', ['rel' => 'nofollow']);
179        }
180
181        if (!$this->isCartEmpty($tree)) {
182            $submenus[] = new Menu(I18N::translate('Empty the clippings cart'), route('module', [
183                'module' => $this->name(),
184                'action' => 'Empty',
185                'tree'    => $tree->name(),
186            ]), 'menu-clippings-empty', ['rel' => 'nofollow']);
187
188            $submenus[] = new Menu(I18N::translate('Download'), route('module', [
189                'module' => $this->name(),
190                'action' => 'DownloadForm',
191                'tree'    => $tree->name(),
192            ]), 'menu-clippings-download', ['rel' => 'nofollow']);
193        }
194
195        return new Menu($this->title(), '#', 'menu-clippings', ['rel' => 'nofollow'], $submenus);
196    }
197
198    /**
199     * @param ServerRequestInterface $request
200     *
201     * @return ResponseInterface
202     */
203    public function postDownloadAction(ServerRequestInterface $request): ResponseInterface
204    {
205        $tree = $request->getAttribute('tree');
206        assert($tree instanceof Tree);
207
208        $data_filesystem = $request->getAttribute('filesystem.data');
209        assert($data_filesystem instanceof FilesystemInterface);
210
211        $params = (array) $request->getParsedBody();
212
213        $privatize_export = $params['privatize_export'];
214
215        if ($privatize_export === 'none' && !Auth::isManager($tree)) {
216            $privatize_export = 'member';
217        }
218
219        if ($privatize_export === 'gedadmin' && !Auth::isManager($tree)) {
220            $privatize_export = 'member';
221        }
222
223        if ($privatize_export === 'user' && !Auth::isMember($tree)) {
224            $privatize_export = 'visitor';
225        }
226
227        $convert = (bool) ($params['convert'] ?? false);
228
229        $cart = Session::get('cart', []);
230
231        $xrefs = array_keys($cart[$tree->name()] ?? []);
232
233        // Create a new/empty .ZIP file
234        $temp_zip_file  = stream_get_meta_data(tmpfile())['uri'];
235        $zip_adapter    = new ZipArchiveAdapter($temp_zip_file);
236        $zip_filesystem = new Filesystem($zip_adapter);
237
238        $manager = new MountManager([
239            'media' => $tree->mediaFilesystem($data_filesystem),
240            'zip'   => $zip_filesystem,
241        ]);
242
243        // Media file prefix
244        $path = $tree->getPreference('MEDIA_DIRECTORY');
245
246        // GEDCOM file header
247        $filetext = FunctionsExport::gedcomHeader($tree, $convert ? 'ANSI' : 'UTF-8');
248
249        switch ($privatize_export) {
250            case 'gedadmin':
251                $access_level = Auth::PRIV_NONE;
252                break;
253            case 'user':
254                $access_level = Auth::PRIV_USER;
255                break;
256            case 'visitor':
257                $access_level = Auth::PRIV_PRIVATE;
258                break;
259            case 'none':
260            default:
261                $access_level = Auth::PRIV_HIDE;
262                break;
263        }
264
265        foreach ($xrefs as $xref) {
266            $object = GedcomRecord::getInstance($xref, $tree);
267            // The object may have been deleted since we added it to the cart....
268            if ($object instanceof  GedcomRecord) {
269                $record = $object->privatizeGedcom($access_level);
270                // Remove links to objects that aren't in the cart
271                preg_match_all('/\n1 ' . Gedcom::REGEX_TAG . ' @(' . Gedcom::REGEX_XREF . ')@(\n[2-9].*)*/', $record, $matches, PREG_SET_ORDER);
272                foreach ($matches as $match) {
273                    if (!in_array($match[1], $xrefs, true)) {
274                        $record = str_replace($match[0], '', $record);
275                    }
276                }
277                preg_match_all('/\n2 ' . Gedcom::REGEX_TAG . ' @(' . Gedcom::REGEX_XREF . ')@(\n[3-9].*)*/', $record, $matches, PREG_SET_ORDER);
278                foreach ($matches as $match) {
279                    if (!in_array($match[1], $xrefs, true)) {
280                        $record = str_replace($match[0], '', $record);
281                    }
282                }
283                preg_match_all('/\n3 ' . Gedcom::REGEX_TAG . ' @(' . Gedcom::REGEX_XREF . ')@(\n[4-9].*)*/', $record, $matches, PREG_SET_ORDER);
284                foreach ($matches as $match) {
285                    if (!in_array($match[1], $xrefs, true)) {
286                        $record = str_replace($match[0], '', $record);
287                    }
288                }
289
290                if ($object instanceof Individual || $object instanceof Family) {
291                    $filetext .= $record . "\n";
292                    $filetext .= "1 SOUR @WEBTREES@\n";
293                    $filetext .= '2 PAGE ' . $object->url() . "\n";
294                } elseif ($object instanceof Source) {
295                    $filetext .= $record . "\n";
296                    $filetext .= '1 NOTE ' . $object->url() . "\n";
297                } elseif ($object instanceof Media) {
298                    // Add the media files to the archive
299                    foreach ($object->mediaFiles() as $media_file) {
300                        $from = 'media://' . $media_file->filename();
301                        $to   = 'zip://' . $path . $media_file->filename();
302                        if (!$media_file->isExternal() && $manager->has($from) && !$manager->has($to)) {
303                            $manager->copy($from, $to);
304                        }
305                    }
306                    $filetext .= $record . "\n";
307                } else {
308                    $filetext .= $record . "\n";
309                }
310            }
311        }
312
313        $base_url = $request->getAttribute('base_url');
314
315        // Create a source, to indicate the source of the data.
316        $filetext .= "0 @WEBTREES@ SOUR\n1 TITL " . $base_url . "\n";
317        $author   = $this->user_service->find((int) $tree->getPreference('CONTACT_USER_ID'));
318        if ($author !== null) {
319            $filetext .= '1 AUTH ' . $author->realName() . "\n";
320        }
321        $filetext .= "0 TRLR\n";
322
323        // Make sure the preferred line endings are used
324        $filetext = strtr($filetext, ["\n" => Gedcom::EOL]);
325
326        if ($convert) {
327            $filetext = utf8_decode($filetext);
328        }
329
330        // Finally add the GEDCOM file to the .ZIP file.
331        $zip_filesystem->write('clippings.ged', $filetext);
332
333        // Need to force-close ZipArchive filesystems.
334        $zip_adapter->getArchive()->close();
335
336        // Use a stream, so that we do not have to load the entire file into memory.
337        $stream = app(StreamFactoryInterface::class)->createStreamFromFile($temp_zip_file);
338
339        /** @var ResponseFactoryInterface $response_factory */
340        $response_factory = app(ResponseFactoryInterface::class);
341
342        return $response_factory->createResponse()
343            ->withBody($stream)
344            ->withHeader('Content-Type', 'application/zip')
345            ->withHeader('Content-Disposition', 'attachment; filename="clippings.zip');
346    }
347
348    /**
349     * @param ServerRequestInterface $request
350     *
351     * @return ResponseInterface
352     */
353    public function getDownloadFormAction(ServerRequestInterface $request): ResponseInterface
354    {
355        $tree = $request->getAttribute('tree');
356        assert($tree instanceof Tree);
357
358        $user  = $request->getAttribute('user');
359        $title = I18N::translate('Family tree clippings cart') . ' — ' . I18N::translate('Download');
360
361        return $this->viewResponse('modules/clippings/download', [
362            'is_manager' => Auth::isManager($tree, $user),
363            'is_member'  => Auth::isMember($tree, $user),
364            'module'     => $this->name(),
365            'title'      => $title,
366            'tree'       => $tree,
367        ]);
368    }
369
370    /**
371     * @param ServerRequestInterface $request
372     *
373     * @return ResponseInterface
374     */
375    public function getEmptyAction(ServerRequestInterface $request): ResponseInterface
376    {
377        $tree = $request->getAttribute('tree');
378        assert($tree instanceof Tree);
379
380        $cart                = Session::get('cart', []);
381        $cart[$tree->name()] = [];
382        Session::put('cart', $cart);
383
384        $url = route('module', [
385            'module' => $this->name(),
386            'action' => 'Show',
387            'tree'    => $tree->name(),
388        ]);
389
390        return redirect($url);
391    }
392
393    /**
394     * @param ServerRequestInterface $request
395     *
396     * @return ResponseInterface
397     */
398    public function postRemoveAction(ServerRequestInterface $request): ResponseInterface
399    {
400        $tree = $request->getAttribute('tree');
401        assert($tree instanceof Tree);
402
403        $xref = $request->getQueryParams()['xref'];
404
405        $cart = Session::get('cart', []);
406        unset($cart[$tree->name()][$xref]);
407        Session::put('cart', $cart);
408
409        $url = route('module', [
410            'module' => $this->name(),
411            'action' => 'Show',
412            'tree'    => $tree->name(),
413        ]);
414
415        return redirect($url);
416    }
417
418    /**
419     * @param ServerRequestInterface $request
420     *
421     * @return ResponseInterface
422     */
423    public function getShowAction(ServerRequestInterface $request): ResponseInterface
424    {
425        $tree = $request->getAttribute('tree');
426        assert($tree instanceof Tree);
427
428        return $this->viewResponse('modules/clippings/show', [
429            'records' => $this->allRecordsInCart($tree),
430            'title'   => I18N::translate('Family tree clippings cart'),
431            'tree'    => $tree,
432        ]);
433    }
434
435    /**
436     * @param ServerRequestInterface $request
437     *
438     * @return ResponseInterface
439     */
440    public function getAddFamilyAction(ServerRequestInterface $request): ResponseInterface
441    {
442        $tree = $request->getAttribute('tree');
443        assert($tree instanceof Tree);
444
445        $xref = $request->getQueryParams()['xref'];
446
447        $family = Family::getInstance($xref, $tree);
448
449        if ($family === null) {
450            throw new FamilyNotFoundException();
451        }
452
453        $options = $this->familyOptions($family);
454
455        $title = I18N::translate('Add %s to the clippings cart', $family->fullName());
456
457        return $this->viewResponse('modules/clippings/add-options', [
458            'options' => $options,
459            'default' => key($options),
460            'record'  => $family,
461            'title'   => $title,
462            'tree'    => $tree,
463        ]);
464    }
465
466    /**
467     * @param Family $family
468     *
469     * @return string[]
470     */
471    private function familyOptions(Family $family): array
472    {
473        $name = strip_tags($family->fullName());
474
475        return [
476            'parents'     => $name,
477            /* I18N: %s is a family (husband + wife) */
478            'members'     => I18N::translate('%s and their children', $name),
479            /* I18N: %s is a family (husband + wife) */
480            'descendants' => I18N::translate('%s and their descendants', $name),
481        ];
482    }
483
484    /**
485     * @param ServerRequestInterface $request
486     *
487     * @return ResponseInterface
488     */
489    public function postAddFamilyAction(ServerRequestInterface $request): ResponseInterface
490    {
491        $tree = $request->getAttribute('tree');
492        assert($tree instanceof Tree);
493
494        $params = (array) $request->getParsedBody();
495
496        $xref   = $params['xref'];
497        $option = $params['option'];
498
499        $family = Family::getInstance($xref, $tree);
500
501        if ($family === null) {
502            throw new FamilyNotFoundException();
503        }
504
505        switch ($option) {
506            case 'parents':
507                $this->addFamilyToCart($family);
508                break;
509
510            case 'members':
511                $this->addFamilyAndChildrenToCart($family);
512                break;
513
514            case 'descendants':
515                $this->addFamilyAndDescendantsToCart($family);
516                break;
517        }
518
519        return redirect($family->url());
520    }
521
522    /**
523     * @param Family $family
524     *
525     * @return void
526     */
527    private function addFamilyToCart(Family $family): void
528    {
529        $this->addRecordToCart($family);
530
531        foreach ($family->spouses() as $spouse) {
532            $this->addRecordToCart($spouse);
533        }
534    }
535
536    /**
537     * @param Family $family
538     *
539     * @return void
540     */
541    private function addFamilyAndChildrenToCart(Family $family): void
542    {
543        $this->addRecordToCart($family);
544
545        foreach ($family->spouses() as $spouse) {
546            $this->addRecordToCart($spouse);
547        }
548        foreach ($family->children() as $child) {
549            $this->addRecordToCart($child);
550        }
551    }
552
553    /**
554     * @param Family $family
555     *
556     * @return void
557     */
558    private function addFamilyAndDescendantsToCart(Family $family): void
559    {
560        $this->addRecordToCart($family);
561
562        foreach ($family->spouses() as $spouse) {
563            $this->addRecordToCart($spouse);
564        }
565        foreach ($family->children() as $child) {
566            $this->addRecordToCart($child);
567            foreach ($child->spouseFamilies() as $child_family) {
568                $this->addFamilyAndDescendantsToCart($child_family);
569            }
570        }
571    }
572
573    /**
574     * @param ServerRequestInterface $request
575     *
576     * @return ResponseInterface
577     */
578    public function getAddIndividualAction(ServerRequestInterface $request): ResponseInterface
579    {
580        $tree = $request->getAttribute('tree');
581        assert($tree instanceof Tree);
582
583        $xref = $request->getQueryParams()['xref'];
584
585        $individual = Individual::getInstance($xref, $tree);
586
587        if ($individual === null) {
588            throw new IndividualNotFoundException();
589        }
590
591        $options = $this->individualOptions($individual);
592
593        $title = I18N::translate('Add %s to the clippings cart', $individual->fullName());
594
595        return $this->viewResponse('modules/clippings/add-options', [
596            'options' => $options,
597            'default' => key($options),
598            'record'  => $individual,
599            'title'   => $title,
600            'tree'    => $tree,
601        ]);
602    }
603
604    /**
605     * @param Individual $individual
606     *
607     * @return string[]
608     */
609    private function individualOptions(Individual $individual): array
610    {
611        $name = strip_tags($individual->fullName());
612
613        if ($individual->sex() === 'F') {
614            return [
615                'self'              => $name,
616                'parents'           => I18N::translate('%s, her parents and siblings', $name),
617                'spouses'           => I18N::translate('%s, her spouses and children', $name),
618                'ancestors'         => I18N::translate('%s and her ancestors', $name),
619                'ancestor_families' => I18N::translate('%s, her ancestors and their families', $name),
620                'descendants'       => I18N::translate('%s, her spouses and descendants', $name),
621            ];
622        }
623
624        return [
625            'self'              => $name,
626            'parents'           => I18N::translate('%s, his parents and siblings', $name),
627            'spouses'           => I18N::translate('%s, his spouses and children', $name),
628            'ancestors'         => I18N::translate('%s and his ancestors', $name),
629            'ancestor_families' => I18N::translate('%s, his ancestors and their families', $name),
630            'descendants'       => I18N::translate('%s, his spouses and descendants', $name),
631        ];
632    }
633
634    /**
635     * @param ServerRequestInterface $request
636     *
637     * @return ResponseInterface
638     */
639    public function postAddIndividualAction(ServerRequestInterface $request): ResponseInterface
640    {
641        $tree = $request->getAttribute('tree');
642        assert($tree instanceof Tree);
643
644        $params = (array) $request->getParsedBody();
645
646        $xref   = $params['xref'];
647        $option = $params['option'];
648
649        $individual = Individual::getInstance($xref, $tree);
650
651        if ($individual === null) {
652            throw new IndividualNotFoundException();
653        }
654
655        switch ($option) {
656            case 'self':
657                $this->addRecordToCart($individual);
658                break;
659
660            case 'parents':
661                foreach ($individual->childFamilies() as $family) {
662                    $this->addFamilyAndChildrenToCart($family);
663                }
664                break;
665
666            case 'spouses':
667                foreach ($individual->spouseFamilies() as $family) {
668                    $this->addFamilyAndChildrenToCart($family);
669                }
670                break;
671
672            case 'ancestors':
673                $this->addAncestorsToCart($individual);
674                break;
675
676            case 'ancestor_families':
677                $this->addAncestorFamiliesToCart($individual);
678                break;
679
680            case 'descendants':
681                foreach ($individual->spouseFamilies() as $family) {
682                    $this->addFamilyAndDescendantsToCart($family);
683                }
684                break;
685        }
686
687        return redirect($individual->url());
688    }
689
690    /**
691     * @param Individual $individual
692     *
693     * @return void
694     */
695    private function addAncestorsToCart(Individual $individual): void
696    {
697        $this->addRecordToCart($individual);
698
699        foreach ($individual->childFamilies() as $family) {
700            foreach ($family->spouses() as $parent) {
701                $this->addAncestorsToCart($parent);
702            }
703        }
704    }
705
706    /**
707     * @param Individual $individual
708     *
709     * @return void
710     */
711    private function addAncestorFamiliesToCart(Individual $individual): void
712    {
713        foreach ($individual->childFamilies() as $family) {
714            $this->addFamilyAndChildrenToCart($family);
715            foreach ($family->spouses() as $parent) {
716                $this->addAncestorFamiliesToCart($parent);
717            }
718        }
719    }
720
721    /**
722     * @param ServerRequestInterface $request
723     *
724     * @return ResponseInterface
725     */
726    public function getAddMediaAction(ServerRequestInterface $request): ResponseInterface
727    {
728        $tree = $request->getAttribute('tree');
729        assert($tree instanceof Tree);
730
731        $xref = $request->getQueryParams()['xref'];
732
733        $media = Media::getInstance($xref, $tree);
734
735        if ($media === null) {
736            throw new MediaNotFoundException();
737        }
738
739        $options = $this->mediaOptions($media);
740
741        $title = I18N::translate('Add %s to the clippings cart', $media->fullName());
742
743        return $this->viewResponse('modules/clippings/add-options', [
744            'options' => $options,
745            'default' => key($options),
746            'record'  => $media,
747            'title'   => $title,
748            'tree'    => $tree,
749        ]);
750    }
751
752    /**
753     * @param Media $media
754     *
755     * @return string[]
756     */
757    private function mediaOptions(Media $media): array
758    {
759        $name = strip_tags($media->fullName());
760
761        return [
762            'self' => $name,
763        ];
764    }
765
766    /**
767     * @param ServerRequestInterface $request
768     *
769     * @return ResponseInterface
770     */
771    public function postAddMediaAction(ServerRequestInterface $request): ResponseInterface
772    {
773        $tree = $request->getAttribute('tree');
774        assert($tree instanceof Tree);
775
776        $xref = $request->getQueryParams()['xref'];
777
778        $media = Media::getInstance($xref, $tree);
779
780        if ($media === null) {
781            throw new MediaNotFoundException();
782        }
783
784        $this->addRecordToCart($media);
785
786        return redirect($media->url());
787    }
788
789    /**
790     * @param ServerRequestInterface $request
791     *
792     * @return ResponseInterface
793     */
794    public function getAddNoteAction(ServerRequestInterface $request): ResponseInterface
795    {
796        $tree = $request->getAttribute('tree');
797        assert($tree instanceof Tree);
798
799        $xref = $request->getQueryParams()['xref'];
800
801        $note = Note::getInstance($xref, $tree);
802
803        if ($note === null) {
804            throw new NoteNotFoundException();
805        }
806
807        $options = $this->noteOptions($note);
808
809        $title = I18N::translate('Add %s to the clippings cart', $note->fullName());
810
811        return $this->viewResponse('modules/clippings/add-options', [
812            'options' => $options,
813            'default' => key($options),
814            'record'  => $note,
815            'title'   => $title,
816            'tree'    => $tree,
817        ]);
818    }
819
820    /**
821     * @param Note $note
822     *
823     * @return string[]
824     */
825    private function noteOptions(Note $note): array
826    {
827        $name = strip_tags($note->fullName());
828
829        return [
830            'self' => $name,
831        ];
832    }
833
834    /**
835     * @param ServerRequestInterface $request
836     *
837     * @return ResponseInterface
838     */
839    public function postAddNoteAction(ServerRequestInterface $request): ResponseInterface
840    {
841        $tree = $request->getAttribute('tree');
842        assert($tree instanceof Tree);
843
844        $xref = $request->getQueryParams()['xref'];
845
846        $note = Note::getInstance($xref, $tree);
847
848        if ($note === null) {
849            throw new NoteNotFoundException();
850        }
851
852        $this->addRecordToCart($note);
853
854        return redirect($note->url());
855    }
856
857    /**
858     * @param ServerRequestInterface $request
859     *
860     * @return ResponseInterface
861     */
862    public function getAddRepositoryAction(ServerRequestInterface $request): ResponseInterface
863    {
864        $tree = $request->getAttribute('tree');
865        assert($tree instanceof Tree);
866
867        $xref = $request->getQueryParams()['xref'];
868
869        $repository = Repository::getInstance($xref, $tree);
870
871        if ($repository === null) {
872            throw new RepositoryNotFoundException();
873        }
874
875        $options = $this->repositoryOptions($repository);
876
877        $title = I18N::translate('Add %s to the clippings cart', $repository->fullName());
878
879        return $this->viewResponse('modules/clippings/add-options', [
880            'options' => $options,
881            'default' => key($options),
882            'record'  => $repository,
883            'title'   => $title,
884            'tree'    => $tree,
885        ]);
886    }
887
888    /**
889     * @param Repository $repository
890     *
891     * @return string[]
892     */
893    private function repositoryOptions(Repository $repository): array
894    {
895        $name = strip_tags($repository->fullName());
896
897        return [
898            'self' => $name,
899        ];
900    }
901
902    /**
903     * @param ServerRequestInterface $request
904     *
905     * @return ResponseInterface
906     */
907    public function postAddRepositoryAction(ServerRequestInterface $request): ResponseInterface
908    {
909        $tree = $request->getAttribute('tree');
910        assert($tree instanceof Tree);
911
912        $xref = $request->getQueryParams()['xref'];
913
914        $repository = Repository::getInstance($xref, $tree);
915
916        if ($repository === null) {
917            throw new RepositoryNotFoundException();
918        }
919
920        $this->addRecordToCart($repository);
921
922        return redirect($repository->url());
923    }
924
925    /**
926     * @param ServerRequestInterface $request
927     *
928     * @return ResponseInterface
929     */
930    public function getAddSourceAction(ServerRequestInterface $request): ResponseInterface
931    {
932        $tree = $request->getAttribute('tree');
933        assert($tree instanceof Tree);
934
935        $xref = $request->getQueryParams()['xref'];
936
937        $source = Source::getInstance($xref, $tree);
938
939        if ($source === null) {
940            throw new SourceNotFoundException();
941        }
942
943        $options = $this->sourceOptions($source);
944
945        $title = I18N::translate('Add %s to the clippings cart', $source->fullName());
946
947        return $this->viewResponse('modules/clippings/add-options', [
948            'options' => $options,
949            'default' => key($options),
950            'record'  => $source,
951            'title'   => $title,
952            'tree'    => $tree,
953        ]);
954    }
955
956    /**
957     * @param Source $source
958     *
959     * @return string[]
960     */
961    private function sourceOptions(Source $source): array
962    {
963        $name = strip_tags($source->fullName());
964
965        return [
966            'only'   => strip_tags($source->fullName()),
967            'linked' => I18N::translate('%s and the individuals that reference it.', $name),
968        ];
969    }
970
971    /**
972     * @param ServerRequestInterface $request
973     *
974     * @return ResponseInterface
975     */
976    public function postAddSourceAction(ServerRequestInterface $request): ResponseInterface
977    {
978        $tree = $request->getAttribute('tree');
979        assert($tree instanceof Tree);
980
981        $params = (array) $request->getParsedBody();
982
983        $xref   = $params['xref'];
984        $option = $params['option'];
985
986        $source = Source::getInstance($xref, $tree);
987
988        if ($source === null) {
989            throw new SourceNotFoundException();
990        }
991
992        $this->addRecordToCart($source);
993
994        if ($option === 'linked') {
995            foreach ($source->linkedIndividuals('SOUR') as $individual) {
996                $this->addRecordToCart($individual);
997            }
998            foreach ($source->linkedFamilies('SOUR') as $family) {
999                $this->addRecordToCart($family);
1000            }
1001        }
1002
1003        return redirect($source->url());
1004    }
1005
1006    /**
1007     * Get all the records in the cart.
1008     *
1009     * @param Tree $tree
1010     *
1011     * @return GedcomRecord[]
1012     */
1013    private function allRecordsInCart(Tree $tree): array
1014    {
1015        $cart = Session::get('cart', []);
1016
1017        $xrefs = array_keys($cart[$tree->name()] ?? []);
1018
1019        // Fetch all the records in the cart.
1020        $records = array_map(static function (string $xref) use ($tree): ?GedcomRecord {
1021            return GedcomRecord::getInstance($xref, $tree);
1022        }, $xrefs);
1023
1024        // Some records may have been deleted after they were added to the cart.
1025        $records = array_filter($records);
1026
1027        // Group and sort.
1028        uasort($records, static function (GedcomRecord $x, GedcomRecord $y): int {
1029            return $x::RECORD_TYPE <=> $y::RECORD_TYPE ?: GedcomRecord::nameComparator()($x, $y);
1030        });
1031
1032        return $records;
1033    }
1034
1035    /**
1036     * Add a record (and direclty linked sources, notes, etc. to the cart.
1037     *
1038     * @param GedcomRecord $record
1039     *
1040     * @return void
1041     */
1042    private function addRecordToCart(GedcomRecord $record): void
1043    {
1044        $cart = Session::get('cart', []);
1045
1046        $tree_name = $record->tree()->name();
1047
1048        // Add this record
1049        $cart[$tree_name][$record->xref()] = true;
1050
1051        // Add directly linked media, notes, repositories and sources.
1052        preg_match_all('/\n\d (?:OBJE|NOTE|SOUR|REPO) @(' . Gedcom::REGEX_XREF . ')@/', $record->gedcom(), $matches);
1053
1054        foreach ($matches[1] as $match) {
1055            $cart[$tree_name][$match] = true;
1056        }
1057
1058        Session::put('cart', $cart);
1059    }
1060
1061    /**
1062     * @param Tree $tree
1063     *
1064     * @return bool
1065     */
1066    private function isCartEmpty(Tree $tree): bool
1067    {
1068        $cart     = Session::get('cart', []);
1069        $contents = $cart[$tree->name()] ?? [];
1070
1071        return $contents === [];
1072    }
1073}
1074