xref: /webtrees/app/Module/RelationshipsChartModule.php (revision e2c25bff1df9f73d83f52064d425e7d2c31fb5fe)
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\Module;
21
22use Aura\Router\RouterContainer;
23use Closure;
24use Fig\Http\Message\RequestMethodInterface;
25use Fisharebest\Algorithm\Dijkstra;
26use Fisharebest\Webtrees\Auth;
27use Fisharebest\Webtrees\Contracts\UserInterface;
28use Fisharebest\Webtrees\Registry;
29use Fisharebest\Webtrees\FlashMessages;
30use Fisharebest\Webtrees\Functions\Functions;
31use Fisharebest\Webtrees\I18N;
32use Fisharebest\Webtrees\Individual;
33use Fisharebest\Webtrees\Menu;
34use Fisharebest\Webtrees\Services\TreeService;
35use Fisharebest\Webtrees\Tree;
36use Illuminate\Database\Capsule\Manager as DB;
37use Illuminate\Database\Query\JoinClause;
38use Psr\Http\Message\ResponseInterface;
39use Psr\Http\Message\ServerRequestInterface;
40use Psr\Http\Server\RequestHandlerInterface;
41
42use function app;
43use function assert;
44use function is_string;
45use function redirect;
46use function route;
47use function view;
48
49/**
50 * Class RelationshipsChartModule
51 */
52class RelationshipsChartModule extends AbstractModule implements ModuleChartInterface, ModuleConfigInterface, RequestHandlerInterface
53{
54    use ModuleChartTrait;
55    use ModuleConfigTrait;
56
57    protected const ROUTE_URL = '/tree/{tree}/relationships-{ancestors}-{recursion}/{xref}{/xref2}';
58
59    /** It would be more correct to use PHP_INT_MAX, but this isn't friendly in URLs */
60    public const UNLIMITED_RECURSION = 99;
61
62    /** By default new trees allow unlimited recursion */
63    public const DEFAULT_RECURSION = '99';
64
65    /** By default new trees search for all relationships (not via ancestors) */
66    public const DEFAULT_ANCESTORS  = '0';
67    public const DEFAULT_PARAMETERS = [
68        'ancestors' => self::DEFAULT_ANCESTORS,
69        'recursion' => self::DEFAULT_RECURSION,
70    ];
71
72    /** @var TreeService */
73    private $tree_service;
74
75    /**
76     * @param TreeService   $tree_service
77     */
78    public function __construct(TreeService $tree_service)
79    {
80        $this->tree_service = $tree_service;
81    }
82
83    /**
84     * Initialization.
85     *
86     * @return void
87     */
88    public function boot(): void
89    {
90        $router_container = app(RouterContainer::class);
91        assert($router_container instanceof RouterContainer);
92
93        $router_container->getMap()
94            ->get(static::class, static::ROUTE_URL, $this)
95            ->allows(RequestMethodInterface::METHOD_POST)
96            ->tokens([
97                'ancestors' => '\d+',
98                'recursion' => '\d+',
99            ]);
100    }
101
102    /**
103     * A sentence describing what this module does.
104     *
105     * @return string
106     */
107    public function description(): string
108    {
109        /* I18N: Description of the “RelationshipsChart” module */
110        return I18N::translate('A chart displaying relationships between two individuals.');
111    }
112
113    /**
114     * Return a menu item for this chart - for use in individual boxes.
115     *
116     * @param Individual $individual
117     *
118     * @return Menu|null
119     */
120    public function chartBoxMenu(Individual $individual): ?Menu
121    {
122        return $this->chartMenu($individual);
123    }
124
125    /**
126     * A main menu item for this chart.
127     *
128     * @param Individual $individual
129     *
130     * @return Menu
131     */
132    public function chartMenu(Individual $individual): Menu
133    {
134        $my_xref = $individual->tree()->getUserPreference(Auth::user(), UserInterface::PREF_TREE_ACCOUNT_XREF);
135
136        if ($my_xref !== '' && $my_xref !== $individual->xref()) {
137            $my_record = Registry::individualFactory()->make($my_xref, $individual->tree());
138
139            return new Menu(
140                I18N::translate('Relationship to me'),
141                $this->chartUrl($my_record, ['xref2' => $individual->xref()]),
142                $this->chartMenuClass(),
143                $this->chartUrlAttributes()
144            );
145        }
146
147        return new Menu(
148            $this->title(),
149            $this->chartUrl($individual),
150            $this->chartMenuClass(),
151            $this->chartUrlAttributes()
152        );
153    }
154
155    /**
156     * CSS class for the URL.
157     *
158     * @return string
159     */
160    public function chartMenuClass(): string
161    {
162        return 'menu-chart-relationship';
163    }
164
165    /**
166     * How should this module be identified in the control panel, etc.?
167     *
168     * @return string
169     */
170    public function title(): string
171    {
172        /* I18N: Name of a module/chart */
173        return I18N::translate('Relationships');
174    }
175
176    /**
177     * The URL for a page showing chart options.
178     *
179     * @param Individual $individual
180     * @param mixed[]    $parameters
181     *
182     * @return string
183     */
184    public function chartUrl(Individual $individual, array $parameters = []): string
185    {
186        return route(static::class, [
187                'xref' => $individual->xref(),
188                'tree' => $individual->tree()->name(),
189            ] + $parameters + self::DEFAULT_PARAMETERS);
190    }
191
192    /**
193     * @param ServerRequestInterface $request
194     *
195     * @return ResponseInterface
196     */
197    public function handle(ServerRequestInterface $request): ResponseInterface
198    {
199        $tree = $request->getAttribute('tree');
200        assert($tree instanceof Tree);
201
202        $xref = $request->getAttribute('xref');
203        assert(is_string($xref));
204
205        $xref2 = $request->getAttribute('xref2') ?? '';
206
207        $ajax      = $request->getQueryParams()['ajax'] ?? '';
208        $ancestors = (int) $request->getAttribute('ancestors');
209        $recursion = (int) $request->getAttribute('recursion');
210        $user      = $request->getAttribute('user');
211
212        // Convert POST requests into GET requests for pretty URLs.
213        if ($request->getMethod() === RequestMethodInterface::METHOD_POST) {
214            $params = (array) $request->getParsedBody();
215
216            return redirect(route(static::class, [
217                'ancestors' => $params['ancestors'],
218                'recursion' => $params['recursion'],
219                'tree'      => $tree->name(),
220                'xref'      => $params['xref'],
221                'xref2'     => $params['xref2'],
222            ]));
223        }
224
225        $individual1 = Registry::individualFactory()->make($xref, $tree);
226        $individual2 = Registry::individualFactory()->make($xref2, $tree);
227
228        $ancestors_only = (int) $tree->getPreference('RELATIONSHIP_ANCESTORS', static::DEFAULT_ANCESTORS);
229        $max_recursion  = (int) $tree->getPreference('RELATIONSHIP_RECURSION', static::DEFAULT_RECURSION);
230
231        $recursion = min($recursion, $max_recursion);
232
233        if ($individual1 instanceof Individual) {
234            $individual1 = Auth::checkIndividualAccess($individual1, false, true);
235        }
236
237        if ($individual2 instanceof Individual) {
238            $individual2 = Auth::checkIndividualAccess($individual2, false, true);
239        }
240
241        Auth::checkComponentAccess($this, ModuleChartInterface::class, $tree, $user);
242
243        if ($individual1 instanceof Individual && $individual2 instanceof Individual) {
244            if ($ajax === '1') {
245                return $this->chart($individual1, $individual2, $recursion, $ancestors);
246            }
247
248            /* I18N: %s are individual’s names */
249            $title    = I18N::translate('Relationships between %1$s and %2$s', $individual1->fullName(), $individual2->fullName());
250            $ajax_url = $this->chartUrl($individual1, [
251                'ajax'      => true,
252                'ancestors' => $ancestors,
253                'recursion' => $recursion,
254                'xref2'     => $individual2->xref(),
255            ]);
256        } else {
257            $title    = I18N::translate('Relationships');
258            $ajax_url = '';
259        }
260
261        return $this->viewResponse('modules/relationships-chart/page', [
262            'ajax_url'          => $ajax_url,
263            'ancestors'         => $ancestors,
264            'ancestors_only'    => $ancestors_only,
265            'ancestors_options' => $this->ancestorsOptions(),
266            'individual1'       => $individual1,
267            'individual2'       => $individual2,
268            'max_recursion'     => $max_recursion,
269            'module'            => $this->name(),
270            'recursion'         => $recursion,
271            'recursion_options' => $this->recursionOptions($max_recursion),
272            'title'             => $title,
273            'tree'              => $tree,
274        ]);
275    }
276
277    /**
278     * @param Individual $individual1
279     * @param Individual $individual2
280     * @param int        $recursion
281     * @param int        $ancestors
282     *
283     * @return ResponseInterface
284     */
285    public function chart(Individual $individual1, Individual $individual2, int $recursion, int $ancestors): ResponseInterface
286    {
287        $tree = $individual1->tree();
288
289        $max_recursion = (int) $tree->getPreference('RELATIONSHIP_RECURSION', static::DEFAULT_RECURSION);
290
291        $recursion = min($recursion, $max_recursion);
292
293        $paths = $this->calculateRelationships($individual1, $individual2, $recursion, (bool) $ancestors);
294
295        ob_start();
296        if (I18N::direction() === 'ltr') {
297            $diagonal1 = asset('css/images/dline.png');
298            $diagonal2 = asset('css/images/dline2.png');
299        } else {
300            $diagonal1 = asset('css/images/dline2.png');
301            $diagonal2 = asset('css/images/dline.png');
302        }
303
304        $num_paths = 0;
305        foreach ($paths as $path) {
306            // Extract the relationship names between pairs of individuals
307            $relationships = $this->oldStyleRelationshipPath($tree, $path);
308            if ($relationships === []) {
309                // Cannot see one of the families/individuals, due to privacy;
310                continue;
311            }
312            echo '<h3>', I18N::translate('Relationship: %s', Functions::getRelationshipNameFromPath(implode('', $relationships), $individual1, $individual2)), '</h3>';
313            $num_paths++;
314
315            // Use a table/grid for layout.
316            $table = [];
317            // Current position in the grid.
318            $x = 0;
319            $y = 0;
320            // Extent of the grid.
321            $min_y = 0;
322            $max_y = 0;
323            $max_x = 0;
324            // For each node in the path.
325            foreach ($path as $n => $xref) {
326                if ($n % 2 === 1) {
327                    switch ($relationships[$n]) {
328                        case 'hus':
329                        case 'wif':
330                        case 'spo':
331                        case 'bro':
332                        case 'sis':
333                        case 'sib':
334                            $table[$x + 1][$y] = '<div style="background:url(' . e(asset('css/images/hline.png')) . ') repeat-x center;  width: 94px; text-align: center"><div class="hline-text" style="height: 32px;">' . Functions::getRelationshipNameFromPath($relationships[$n], Registry::individualFactory()->make($path[$n - 1], $tree), Registry::individualFactory()->make($path[$n + 1], $tree)) . '</div><div style="height: 32px;">' . view('icons/arrow-right') . '</div></div>';
335                            $x += 2;
336                            break;
337                        case 'son':
338                        case 'dau':
339                        case 'chi':
340                            if ($n > 2 && preg_match('/fat|mot|par/', $relationships[$n - 2])) {
341                                $table[$x + 1][$y - 1] = '<div style="background:url(' . $diagonal2 . '); width: 64px; height: 64px; text-align: center;"><div style="height: 32px; text-align: end;">' . Functions::getRelationshipNameFromPath($relationships[$n], Registry::individualFactory()->make($path[$n - 1], $tree), Registry::individualFactory()->make($path[$n + 1], $tree)) . '</div><div style="height: 32px; text-align: start;">' . view('icons/arrow-down') . '</div></div>';
342                                $x += 2;
343                            } else {
344                                $table[$x][$y - 1] = '<div style="background:url(' . e('"' . asset('css/images/vline.png') . '"') . ') repeat-y center; height: 64px; text-align: center;"><div class="vline-text" style="display: inline-block; width:50%; line-height: 64px;">' . Functions::getRelationshipNameFromPath($relationships[$n], Registry::individualFactory()->make($path[$n - 1], $tree), Registry::individualFactory()->make($path[$n + 1], $tree)) . '</div><div style="display: inline-block; width:50%; line-height: 64px;">' . view('icons/arrow-down') . '</div></div>';
345                            }
346                            $y -= 2;
347                            break;
348                        case 'fat':
349                        case 'mot':
350                        case 'par':
351                            if ($n > 2 && preg_match('/son|dau|chi/', $relationships[$n - 2])) {
352                                $table[$x + 1][$y + 1] = '<div style="background:url(' . $diagonal1 . '); background-position: top right; width: 64px; height: 64px; text-align: center;"><div style="height: 32px; text-align: start;">' . Functions::getRelationshipNameFromPath($relationships[$n], Registry::individualFactory()->make($path[$n - 1], $tree), Registry::individualFactory()->make($path[$n + 1], $tree)) . '</div><div style="height: 32px; text-align: end;">' . view('icons/arrow-down') . '</div></div>';
353                                $x += 2;
354                            } else {
355                                $table[$x][$y + 1] = '<div style="background:url(' . e('"' . asset('css/images/vline.png') . '"') . ') repeat-y center; height: 64px; text-align:center; "><div class="vline-text" style="display: inline-block; width: 50%; line-height: 64px;">' . Functions::getRelationshipNameFromPath($relationships[$n], Registry::individualFactory()->make($path[$n - 1], $tree), Registry::individualFactory()->make($path[$n + 1], $tree)) . '</div><div style="display: inline-block; width: 50%; line-height: 32px">' . view('icons/arrow-up') . '</div></div>';
356                            }
357                            $y += 2;
358                            break;
359                    }
360                    $max_x = max($max_x, $x);
361                    $min_y = min($min_y, $y);
362                    $max_y = max($max_y, $y);
363                } else {
364                    $individual    = Registry::individualFactory()->make($xref, $tree);
365                    $table[$x][$y] = view('chart-box', ['individual' => $individual]);
366                }
367            }
368            echo '<div class="wt-chart wt-chart-relationships">';
369            echo '<table style="border-collapse: collapse; margin: 20px 50px;">';
370            for ($y = $max_y; $y >= $min_y; --$y) {
371                echo '<tr>';
372                for ($x = 0; $x <= $max_x; ++$x) {
373                    echo '<td style="padding: 0;">';
374                    if (isset($table[$x][$y])) {
375                        echo $table[$x][$y];
376                    }
377                    echo '</td>';
378                }
379                echo '</tr>';
380            }
381            echo '</table>';
382            echo '</div>';
383        }
384
385        if (!$num_paths) {
386            echo '<p>', I18N::translate('No link between the two individuals could be found.'), '</p>';
387        }
388
389        $html = ob_get_clean();
390
391        return response($html);
392    }
393
394    /**
395     * @param ServerRequestInterface $request
396     *
397     * @return ResponseInterface
398     */
399    public function getAdminAction(ServerRequestInterface $request): ResponseInterface
400    {
401        $this->layout = 'layouts/administration';
402
403        return $this->viewResponse('modules/relationships-chart/config', [
404            'all_trees'         => $this->tree_service->all(),
405            'ancestors_options' => $this->ancestorsOptions(),
406            'default_ancestors' => self::DEFAULT_ANCESTORS,
407            'default_recursion' => self::DEFAULT_RECURSION,
408            'recursion_options' => $this->recursionConfigOptions(),
409            'title'             => I18N::translate('Chart preferences') . ' — ' . $this->title(),
410        ]);
411    }
412
413    /**
414     * @param ServerRequestInterface $request
415     *
416     * @return ResponseInterface
417     */
418    public function postAdminAction(ServerRequestInterface $request): ResponseInterface
419    {
420        $params = (array) $request->getParsedBody();
421
422        foreach ($this->tree_service->all() as $tree) {
423            $recursion = $params['relationship-recursion-' . $tree->id()] ?? '';
424            $ancestors = $params['relationship-ancestors-' . $tree->id()] ?? '';
425
426            $tree->setPreference('RELATIONSHIP_RECURSION', $recursion);
427            $tree->setPreference('RELATIONSHIP_ANCESTORS', $ancestors);
428        }
429
430        FlashMessages::addMessage(I18N::translate('The preferences for the module “%s” have been updated.', $this->title()), 'success');
431
432        return redirect($this->getConfigLink());
433    }
434
435    /**
436     * Possible options for the ancestors option
437     *
438     * @return array<int,string>
439     */
440    private function ancestorsOptions(): array
441    {
442        return [
443            0 => I18N::translate('Find any relationship'),
444            1 => I18N::translate('Find relationships via ancestors'),
445        ];
446    }
447
448    /**
449     * Possible options for the recursion option
450     *
451     * @return array<int,string>
452     */
453    private function recursionConfigOptions(): array
454    {
455        return [
456            0                         => I18N::translate('none'),
457            1                         => I18N::number(1),
458            2                         => I18N::number(2),
459            3                         => I18N::number(3),
460            self::UNLIMITED_RECURSION => I18N::translate('unlimited'),
461        ];
462    }
463
464    /**
465     * Calculate the shortest paths - or all paths - between two individuals.
466     *
467     * @param Individual $individual1
468     * @param Individual $individual2
469     * @param int        $recursion How many levels of recursion to use
470     * @param bool       $ancestor  Restrict to relationships via a common ancestor
471     *
472     * @return array<array<string>>
473     */
474    private function calculateRelationships(
475        Individual $individual1,
476        Individual $individual2,
477        int $recursion,
478        bool $ancestor = false
479    ): array {
480        $tree = $individual1->tree();
481
482        $rows = DB::table('link')
483            ->where('l_file', '=', $tree->id())
484            ->whereIn('l_type', ['FAMS', 'FAMC'])
485            ->select(['l_from', 'l_to'])
486            ->get();
487
488        // Optionally restrict the graph to the ancestors of the individuals.
489        if ($ancestor) {
490            $ancestors = $this->allAncestors($individual1->xref(), $individual2->xref(), $tree->id());
491            $exclude   = $this->excludeFamilies($individual1->xref(), $individual2->xref(), $tree->id());
492        } else {
493            $ancestors = [];
494            $exclude   = [];
495        }
496
497        $graph = [];
498
499        foreach ($rows as $row) {
500            if ($ancestors === [] || in_array($row->l_from, $ancestors, true) && !in_array($row->l_to, $exclude, true)) {
501                $graph[$row->l_from][$row->l_to] = 1;
502                $graph[$row->l_to][$row->l_from] = 1;
503            }
504        }
505
506        $xref1    = $individual1->xref();
507        $xref2    = $individual2->xref();
508        $dijkstra = new Dijkstra($graph);
509        $paths    = $dijkstra->shortestPaths($xref1, $xref2);
510
511        // Only process each exclusion list once;
512        $excluded = [];
513
514        $queue = [];
515        foreach ($paths as $path) {
516            // Insert the paths into the queue, with an exclusion list.
517            $queue[] = [
518                'path'    => $path,
519                'exclude' => [],
520            ];
521            // While there are un-extended paths
522            for ($next = current($queue); $next !== false; $next = next($queue)) {
523                // For each family on the path
524                for ($n = count($next['path']) - 2; $n >= 1; $n -= 2) {
525                    $exclude = $next['exclude'];
526                    if (count($exclude) >= $recursion) {
527                        continue;
528                    }
529                    $exclude[] = $next['path'][$n];
530                    sort($exclude);
531                    $tmp = implode('-', $exclude);
532                    if (in_array($tmp, $excluded, true)) {
533                        continue;
534                    }
535
536                    $excluded[] = $tmp;
537                    // Add any new path to the queue
538                    foreach ($dijkstra->shortestPaths($xref1, $xref2, $exclude) as $new_path) {
539                        $queue[] = [
540                            'path'    => $new_path,
541                            'exclude' => $exclude,
542                        ];
543                    }
544                }
545            }
546        }
547        // Extract the paths from the queue.
548        $paths = [];
549        foreach ($queue as $next) {
550            // The Dijkstra library does not use strict types, and converts
551            // numeric array keys (XREFs) from strings to integers;
552            $path = array_map($this->stringMapper(), $next['path']);
553
554            // Remove duplicates
555            $paths[implode('-', $next['path'])] = $path;
556        }
557
558        return $paths;
559    }
560
561    /**
562     * Convert numeric values to strings
563     *
564     * @return Closure
565     */
566    private function stringMapper(): Closure
567    {
568        return static function ($xref) {
569            return (string) $xref;
570        };
571    }
572
573    /**
574     * Find all ancestors of a list of individuals
575     *
576     * @param string $xref1
577     * @param string $xref2
578     * @param int    $tree_id
579     *
580     * @return array<string>
581     */
582    private function allAncestors(string $xref1, string $xref2, int $tree_id): array
583    {
584        $ancestors = [
585            $xref1,
586            $xref2,
587        ];
588
589        $queue = [
590            $xref1,
591            $xref2,
592        ];
593        while ($queue !== []) {
594            $parents = DB::table('link AS l1')
595                ->join('link AS l2', static function (JoinClause $join): void {
596                    $join
597                        ->on('l1.l_to', '=', 'l2.l_to')
598                        ->on('l1.l_file', '=', 'l2.l_file');
599                })
600                ->where('l1.l_file', '=', $tree_id)
601                ->where('l1.l_type', '=', 'FAMC')
602                ->where('l2.l_type', '=', 'FAMS')
603                ->whereIn('l1.l_from', $queue)
604                ->pluck('l2.l_from');
605
606            $queue = [];
607            foreach ($parents as $parent) {
608                if (!in_array($parent, $ancestors, true)) {
609                    $ancestors[] = $parent;
610                    $queue[]     = $parent;
611                }
612            }
613        }
614
615        return $ancestors;
616    }
617
618    /**
619     * Find all families of two individuals
620     *
621     * @param string $xref1
622     * @param string $xref2
623     * @param int    $tree_id
624     *
625     * @return array<string>
626     */
627    private function excludeFamilies(string $xref1, string $xref2, int $tree_id): array
628    {
629        return DB::table('link AS l1')
630            ->join('link AS l2', static function (JoinClause $join): void {
631                $join
632                    ->on('l1.l_to', '=', 'l2.l_to')
633                    ->on('l1.l_type', '=', 'l2.l_type')
634                    ->on('l1.l_file', '=', 'l2.l_file');
635            })
636            ->where('l1.l_file', '=', $tree_id)
637            ->where('l1.l_type', '=', 'FAMS')
638            ->where('l1.l_from', '=', $xref1)
639            ->where('l2.l_from', '=', $xref2)
640            ->pluck('l1.l_to')
641            ->all();
642    }
643
644    /**
645     * Convert a path (list of XREFs) to an "old-style" string of relationships.
646     * Return an empty array, if privacy rules prevent us viewing any node.
647     *
648     * @param Tree     $tree
649     * @param string[] $path Alternately Individual / Family
650     *
651     * @return array<string>
652     */
653    private function oldStyleRelationshipPath(Tree $tree, array $path): array
654    {
655        $spouse_codes = [
656            'M' => 'hus',
657            'F' => 'wif',
658            'U' => 'spo',
659        ];
660        $parent_codes = [
661            'M' => 'fat',
662            'F' => 'mot',
663            'U' => 'par',
664        ];
665        $child_codes = [
666            'M' => 'son',
667            'F' => 'dau',
668            'U' => 'chi',
669        ];
670        $sibling_codes = [
671            'M' => 'bro',
672            'F' => 'sis',
673            'U' => 'sib',
674        ];
675        $relationships = [];
676
677        for ($i = 1, $count = count($path); $i < $count; $i += 2) {
678            $family = Registry::familyFactory()->make($path[$i], $tree);
679            $prev   = Registry::individualFactory()->make($path[$i - 1], $tree);
680            $next   = Registry::individualFactory()->make($path[$i + 1], $tree);
681            if (preg_match('/\n\d (HUSB|WIFE|CHIL) @' . $prev->xref() . '@/', $family->gedcom(), $match)) {
682                $rel1 = $match[1];
683            } else {
684                return [];
685            }
686            if (preg_match('/\n\d (HUSB|WIFE|CHIL) @' . $next->xref() . '@/', $family->gedcom(), $match)) {
687                $rel2 = $match[1];
688            } else {
689                return [];
690            }
691            if (($rel1 === 'HUSB' || $rel1 === 'WIFE') && ($rel2 === 'HUSB' || $rel2 === 'WIFE')) {
692                $relationships[$i] = $spouse_codes[$next->sex()];
693            } elseif (($rel1 === 'HUSB' || $rel1 === 'WIFE') && $rel2 === 'CHIL') {
694                $relationships[$i] = $child_codes[$next->sex()];
695            } elseif ($rel1 === 'CHIL' && ($rel2 === 'HUSB' || $rel2 === 'WIFE')) {
696                $relationships[$i] = $parent_codes[$next->sex()];
697            } elseif ($rel1 === 'CHIL' && $rel2 === 'CHIL') {
698                $relationships[$i] = $sibling_codes[$next->sex()];
699            }
700        }
701
702        return $relationships;
703    }
704
705    /**
706     * Possible options for the recursion option
707     *
708     * @param int $max_recursion
709     *
710     * @return array<string>
711     */
712    private function recursionOptions(int $max_recursion): array
713    {
714        if ($max_recursion === static::UNLIMITED_RECURSION) {
715            $text = I18N::translate('Find all possible relationships');
716        } else {
717            $text = I18N::translate('Find other relationships');
718        }
719
720        return [
721            '0'            => I18N::translate('Find the closest relationships'),
722            $max_recursion => $text,
723        ];
724    }
725}
726