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