xref: /webtrees/app/Module/RelationshipsChartModule.php (revision e381f98dae35059b6db6d6f34db84bb55bd35a4a)
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\RouterContainer;
23use Closure;
24use Fig\Http\Message\RequestMethodInterface;
25use Fisharebest\Algorithm\Dijkstra;
26use Fisharebest\Webtrees\Auth;
27use Fisharebest\Webtrees\Family;
28use Fisharebest\Webtrees\FlashMessages;
29use Fisharebest\Webtrees\Functions\Functions;
30use Fisharebest\Webtrees\I18N;
31use Fisharebest\Webtrees\Individual;
32use Fisharebest\Webtrees\Menu;
33use Fisharebest\Webtrees\Services\TreeService;
34use Fisharebest\Webtrees\Tree;
35use Illuminate\Database\Capsule\Manager as DB;
36use Illuminate\Database\Query\JoinClause;
37use Psr\Http\Message\ResponseInterface;
38use Psr\Http\Message\ServerRequestInterface;
39use Psr\Http\Server\RequestHandlerInterface;
40
41use function app;
42use function assert;
43use function is_string;
44use function redirect;
45use function route;
46use function view;
47
48/**
49 * Class RelationshipsChartModule
50 */
51class RelationshipsChartModule extends AbstractModule implements ModuleChartInterface, RequestHandlerInterface
52{
53    use ModuleChartTrait;
54    use ModuleConfigTrait;
55
56    private const ROUTE_NAME = 'relationships';
57    private 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     * ModuleController constructor.
77     *
78     * @param TreeService   $tree_service
79     */
80    public function __construct(TreeService $tree_service)
81    {
82        $this->tree_service = $tree_service;
83    }
84
85    /**
86     * Initialization.
87     *
88     * @return void
89     */
90    public function boot(): void
91    {
92        $router_container = app(RouterContainer::class);
93        assert($router_container instanceof RouterContainer);
94
95        $router_container->getMap()
96            ->get(self::ROUTE_NAME, self::ROUTE_URL, $this)
97            ->allows(RequestMethodInterface::METHOD_POST)
98            ->tokens([
99                'ancestors' => '\d+',
100                'recursion' => '\d+',
101            ]);
102    }
103
104    /**
105     * A sentence describing what this module does.
106     *
107     * @return string
108     */
109    public function description(): string
110    {
111        /* I18N: Description of the “RelationshipsChart” module */
112        return I18N::translate('A chart displaying relationships between two individuals.');
113    }
114
115    /**
116     * Return a menu item for this chart - for use in individual boxes.
117     *
118     * @param Individual $individual
119     *
120     * @return Menu|null
121     */
122    public function chartBoxMenu(Individual $individual): ?Menu
123    {
124        return $this->chartMenu($individual);
125    }
126
127    /**
128     * A main menu item for this chart.
129     *
130     * @param Individual $individual
131     *
132     * @return Menu
133     */
134    public function chartMenu(Individual $individual): Menu
135    {
136        $gedcomid = $individual->tree()->getUserPreference(Auth::user(), 'gedcomid');
137
138        if ($gedcomid !== '' && $gedcomid !== $individual->xref()) {
139            return new Menu(
140                I18N::translate('Relationship to me'),
141                $this->chartUrl($individual, ['xref2' => $gedcomid]),
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(self::ROUTE_NAME, [
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            return redirect(route(self::ROUTE_NAME, [
215                'ancestors' => $request->getParsedBody()['ancestors'],
216                'recursion' => $request->getParsedBody()['recursion'],
217                'tree'      => $tree->name(),
218                'xref'      => $request->getParsedBody()['xref'],
219                'xref2'     => $request->getParsedBody()['xref2'],
220            ]));
221        }
222
223        $individual1 = Individual::getInstance($xref, $tree);
224        $individual2 = Individual::getInstance($xref2, $tree);
225
226        $ancestors_only = (int) $tree->getPreference('RELATIONSHIP_ANCESTORS', static::DEFAULT_ANCESTORS);
227        $max_recursion  = (int) $tree->getPreference('RELATIONSHIP_RECURSION', static::DEFAULT_RECURSION);
228
229        $recursion = min($recursion, $max_recursion);
230
231        if ($tree->getPreference('SHOW_PRIVATE_RELATIONSHIPS') !== '1') {
232            if ($individual1 instanceof Individual) {
233                $individual1 = Auth::checkIndividualAccess($individual1);
234            }
235
236            if ($individual2 instanceof Individual) {
237                $individual2 = Auth::checkIndividualAccess($individual2);
238            }
239        }
240
241        Auth::checkComponentAccess($this, 'chart', $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 (empty($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], Individual::getInstance($path[$n - 1], $tree), Individual::getInstance($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], Individual::getInstance($path[$n - 1], $tree), Individual::getInstance($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], Individual::getInstance($path[$n - 1], $tree), Individual::getInstance($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], Individual::getInstance($path[$n - 1], $tree), Individual::getInstance($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], Individual::getInstance($path[$n - 1], $tree), Individual::getInstance($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    = Individual::getInstance($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        foreach ($this->tree_service->all() as $tree) {
421            $recursion = $request->getParsedBody()['relationship-recursion-' . $tree->id()] ?? '';
422            $ancestors = $request->getParsedBody()['relationship-ancestors-' . $tree->id()] ?? '';
423
424            $tree->setPreference('RELATIONSHIP_RECURSION', $recursion);
425            $tree->setPreference('RELATIONSHIP_ANCESTORS', $ancestors);
426        }
427
428        FlashMessages::addMessage(I18N::translate('The preferences for the module “%s” have been updated.', $this->title()), 'success');
429
430        return redirect($this->getConfigLink());
431    }
432
433    /**
434     * Possible options for the ancestors option
435     *
436     * @return string[]
437     */
438    private function ancestorsOptions(): array
439    {
440        return [
441            0 => I18N::translate('Find any relationship'),
442            1 => I18N::translate('Find relationships via ancestors'),
443        ];
444    }
445
446    /**
447     * Possible options for the recursion option
448     *
449     * @return string[]
450     */
451    private function recursionConfigOptions(): array
452    {
453        return [
454            0                         => I18N::translate('none'),
455            1                         => I18N::number(1),
456            2                         => I18N::number(2),
457            3                         => I18N::number(3),
458            self::UNLIMITED_RECURSION => I18N::translate('unlimited'),
459        ];
460    }
461
462    /**
463     * Calculate the shortest paths - or all paths - between two individuals.
464     *
465     * @param Individual $individual1
466     * @param Individual $individual2
467     * @param int        $recursion How many levels of recursion to use
468     * @param bool       $ancestor  Restrict to relationships via a common ancestor
469     *
470     * @return string[][]
471     */
472    private function calculateRelationships(Individual $individual1, Individual $individual2, $recursion, $ancestor = false): array
473    {
474        $tree = $individual1->tree();
475
476        $rows = DB::table('link')
477            ->where('l_file', '=', $tree->id())
478            ->whereIn('l_type', ['FAMS', 'FAMC'])
479            ->select(['l_from', 'l_to'])
480            ->get();
481
482        // Optionally restrict the graph to the ancestors of the individuals.
483        if ($ancestor) {
484            $ancestors = $this->allAncestors($individual1->xref(), $individual2->xref(), $tree->id());
485            $exclude   = $this->excludeFamilies($individual1->xref(), $individual2->xref(), $tree->id());
486        } else {
487            $ancestors = [];
488            $exclude   = [];
489        }
490
491        $graph = [];
492
493        foreach ($rows as $row) {
494            if (empty($ancestors) || in_array($row->l_from, $ancestors, true) && !in_array($row->l_to, $exclude, true)) {
495                $graph[$row->l_from][$row->l_to] = 1;
496                $graph[$row->l_to][$row->l_from] = 1;
497            }
498        }
499
500        $xref1    = $individual1->xref();
501        $xref2    = $individual2->xref();
502        $dijkstra = new Dijkstra($graph);
503        $paths    = $dijkstra->shortestPaths($xref1, $xref2);
504
505        // Only process each exclusion list once;
506        $excluded = [];
507
508        $queue = [];
509        foreach ($paths as $path) {
510            // Insert the paths into the queue, with an exclusion list.
511            $queue[] = [
512                'path'    => $path,
513                'exclude' => [],
514            ];
515            // While there are un-extended paths
516            for ($next = current($queue); $next !== false; $next = next($queue)) {
517                // For each family on the path
518                for ($n = count($next['path']) - 2; $n >= 1; $n -= 2) {
519                    $exclude = $next['exclude'];
520                    if (count($exclude) >= $recursion) {
521                        continue;
522                    }
523                    $exclude[] = $next['path'][$n];
524                    sort($exclude);
525                    $tmp = implode('-', $exclude);
526                    if (in_array($tmp, $excluded, true)) {
527                        continue;
528                    }
529
530                    $excluded[] = $tmp;
531                    // Add any new path to the queue
532                    foreach ($dijkstra->shortestPaths($xref1, $xref2, $exclude) as $new_path) {
533                        $queue[] = [
534                            'path'    => $new_path,
535                            'exclude' => $exclude,
536                        ];
537                    }
538                }
539            }
540        }
541        // Extract the paths from the queue.
542        $paths = [];
543        foreach ($queue as $next) {
544            // The Dijkstra library does not use strict types, and converts
545            // numeric array keys (XREFs) from strings to integers;
546            $path = array_map($this->stringMapper(), $next['path']);
547
548            // Remove duplicates
549            $paths[implode('-', $next['path'])] = $path;
550        }
551
552        return $paths;
553    }
554
555    /**
556     * Convert numeric values to strings
557     *
558     * @return Closure
559     */
560    private function stringMapper(): Closure
561    {
562        return static function ($xref) {
563            return (string) $xref;
564        };
565    }
566
567    /**
568     * Find all ancestors of a list of individuals
569     *
570     * @param string $xref1
571     * @param string $xref2
572     * @param int    $tree_id
573     *
574     * @return string[]
575     */
576    private function allAncestors($xref1, $xref2, $tree_id): array
577    {
578        $ancestors = [
579            $xref1,
580            $xref2,
581        ];
582
583        $queue = [
584            $xref1,
585            $xref2,
586        ];
587        while (!empty($queue)) {
588            $parents = DB::table('link AS l1')
589                ->join('link AS l2', static function (JoinClause $join): void {
590                    $join
591                        ->on('l1.l_to', '=', 'l2.l_to')
592                        ->on('l1.l_file', '=', 'l2.l_file');
593                })
594                ->where('l1.l_file', '=', $tree_id)
595                ->where('l1.l_type', '=', 'FAMC')
596                ->where('l2.l_type', '=', 'FAMS')
597                ->whereIn('l1.l_from', $queue)
598                ->pluck('l2.l_from');
599
600            $queue = [];
601            foreach ($parents as $parent) {
602                if (!in_array($parent, $ancestors, true)) {
603                    $ancestors[] = $parent;
604                    $queue[]     = $parent;
605                }
606            }
607        }
608
609        return $ancestors;
610    }
611
612    /**
613     * Find all families of two individuals
614     *
615     * @param string $xref1
616     * @param string $xref2
617     * @param int    $tree_id
618     *
619     * @return string[]
620     */
621    private function excludeFamilies($xref1, $xref2, $tree_id): array
622    {
623        return DB::table('link AS l1')
624            ->join('link AS l2', static function (JoinClause $join): void {
625                $join
626                    ->on('l1.l_to', '=', 'l2.l_to')
627                    ->on('l1.l_type', '=', 'l2.l_type')
628                    ->on('l1.l_file', '=', 'l2.l_file');
629            })
630            ->where('l1.l_file', '=', $tree_id)
631            ->where('l1.l_type', '=', 'FAMS')
632            ->where('l1.l_from', '=', $xref1)
633            ->where('l2.l_from', '=', $xref2)
634            ->pluck('l1.l_to')
635            ->all();
636    }
637
638    /**
639     * Convert a path (list of XREFs) to an "old-style" string of relationships.
640     * Return an empty array, if privacy rules prevent us viewing any node.
641     *
642     * @param Tree     $tree
643     * @param string[] $path Alternately Individual / Family
644     *
645     * @return string[]
646     */
647    private function oldStyleRelationshipPath(Tree $tree, array $path): array
648    {
649        $spouse_codes  = [
650            'M' => 'hus',
651            'F' => 'wif',
652            'U' => 'spo',
653        ];
654        $parent_codes  = [
655            'M' => 'fat',
656            'F' => 'mot',
657            'U' => 'par',
658        ];
659        $child_codes   = [
660            'M' => 'son',
661            'F' => 'dau',
662            'U' => 'chi',
663        ];
664        $sibling_codes = [
665            'M' => 'bro',
666            'F' => 'sis',
667            'U' => 'sib',
668        ];
669        $relationships = [];
670
671        for ($i = 1, $count = count($path); $i < $count; $i += 2) {
672            $family = Family::getInstance($path[$i], $tree);
673            $prev   = Individual::getInstance($path[$i - 1], $tree);
674            $next   = Individual::getInstance($path[$i + 1], $tree);
675            if (preg_match('/\n\d (HUSB|WIFE|CHIL) @' . $prev->xref() . '@/', $family->gedcom(), $match)) {
676                $rel1 = $match[1];
677            } else {
678                return [];
679            }
680            if (preg_match('/\n\d (HUSB|WIFE|CHIL) @' . $next->xref() . '@/', $family->gedcom(), $match)) {
681                $rel2 = $match[1];
682            } else {
683                return [];
684            }
685            if (($rel1 === 'HUSB' || $rel1 === 'WIFE') && ($rel2 === 'HUSB' || $rel2 === 'WIFE')) {
686                $relationships[$i] = $spouse_codes[$next->sex()];
687            } elseif (($rel1 === 'HUSB' || $rel1 === 'WIFE') && $rel2 === 'CHIL') {
688                $relationships[$i] = $child_codes[$next->sex()];
689            } elseif ($rel1 === 'CHIL' && ($rel2 === 'HUSB' || $rel2 === 'WIFE')) {
690                $relationships[$i] = $parent_codes[$next->sex()];
691            } elseif ($rel1 === 'CHIL' && $rel2 === 'CHIL') {
692                $relationships[$i] = $sibling_codes[$next->sex()];
693            }
694        }
695
696        return $relationships;
697    }
698
699    /**
700     * Possible options for the recursion option
701     *
702     * @param int $max_recursion
703     *
704     * @return string[]
705     */
706    private function recursionOptions(int $max_recursion): array
707    {
708        if ($max_recursion === static::UNLIMITED_RECURSION) {
709            $text = I18N::translate('Find all possible relationships');
710        } else {
711            $text = I18N::translate('Find other relationships');
712        }
713
714        return [
715            '0'            => I18N::translate('Find the closest relationships'),
716            $max_recursion => $text,
717        ];
718    }
719}
720