xref: /webtrees/app/Module/RelationshipsChartModule.php (revision 852ede8c85e501a9df6f3c9d31e5933428e18cc2)
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        // @TODO - convert to views
296        ob_start();
297        if (I18N::direction() === 'ltr') {
298            $diagonal1 = asset('css/images/dline.png');
299            $diagonal2 = asset('css/images/dline2.png');
300        } else {
301            $diagonal1 = asset('css/images/dline2.png');
302            $diagonal2 = asset('css/images/dline.png');
303        }
304
305        $num_paths = 0;
306        foreach ($paths as $path) {
307            // Extract the relationship names between pairs of individuals
308            $relationships = $this->oldStyleRelationshipPath($tree, $path);
309            if (empty($relationships)) {
310                // Cannot see one of the families/individuals, due to privacy;
311                continue;
312            }
313            echo '<h3>', I18N::translate('Relationship: %s', Functions::getRelationshipNameFromPath(implode('', $relationships), $individual1, $individual2)), '</h3>';
314            $num_paths++;
315
316            // Use a table/grid for layout.
317            $table = [];
318            // Current position in the grid.
319            $x = 0;
320            $y = 0;
321            // Extent of the grid.
322            $min_y = 0;
323            $max_y = 0;
324            $max_x = 0;
325            // For each node in the path.
326            foreach ($path as $n => $xref) {
327                if ($n % 2 === 1) {
328                    switch ($relationships[$n]) {
329                        case 'hus':
330                        case 'wif':
331                        case 'spo':
332                        case 'bro':
333                        case 'sis':
334                        case 'sib':
335                            $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>';
336                            $x                 += 2;
337                            break;
338                        case 'son':
339                        case 'dau':
340                        case 'chi':
341                            if ($n > 2 && preg_match('/fat|mot|par/', $relationships[$n - 2])) {
342                                $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>';
343                                $x                     += 2;
344                            } else {
345                                $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>';
346                            }
347                            $y -= 2;
348                            break;
349                        case 'fat':
350                        case 'mot':
351                        case 'par':
352                            if ($n > 2 && preg_match('/son|dau|chi/', $relationships[$n - 2])) {
353                                $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>';
354                                $x                     += 2;
355                            } else {
356                                $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>';
357                            }
358                            $y += 2;
359                            break;
360                    }
361                    $max_x = max($max_x, $x);
362                    $min_y = min($min_y, $y);
363                    $max_y = max($max_y, $y);
364                } else {
365                    $individual    = Individual::getInstance($xref, $tree);
366                    $table[$x][$y] = view('chart-box', ['individual' => $individual]);
367                }
368            }
369            echo '<div class="wt-chart wt-chart-relationships">';
370            echo '<table style="border-collapse: collapse; margin: 20px 50px;">';
371            for ($y = $max_y; $y >= $min_y; --$y) {
372                echo '<tr>';
373                for ($x = 0; $x <= $max_x; ++$x) {
374                    echo '<td style="padding: 0;">';
375                    if (isset($table[$x][$y])) {
376                        echo $table[$x][$y];
377                    }
378                    echo '</td>';
379                }
380                echo '</tr>';
381            }
382            echo '</table>';
383            echo '</div>';
384        }
385
386        if (!$num_paths) {
387            echo '<p>', I18N::translate('No link between the two individuals could be found.'), '</p>';
388        }
389
390        $html = ob_get_clean();
391
392        return response($html);
393    }
394
395    /**
396     * @param ServerRequestInterface $request
397     *
398     * @return ResponseInterface
399     */
400    public function getAdminAction(ServerRequestInterface $request): ResponseInterface
401    {
402        $this->layout = 'layouts/administration';
403
404        return $this->viewResponse('modules/relationships-chart/config', [
405            'all_trees'         => $this->tree_service->all(),
406            'ancestors_options' => $this->ancestorsOptions(),
407            'default_ancestors' => self::DEFAULT_ANCESTORS,
408            'default_recursion' => self::DEFAULT_RECURSION,
409            'recursion_options' => $this->recursionConfigOptions(),
410            'title'             => I18N::translate('Chart preferences') . ' — ' . $this->title(),
411        ]);
412    }
413
414    /**
415     * @param ServerRequestInterface $request
416     *
417     * @return ResponseInterface
418     */
419    public function postAdminAction(ServerRequestInterface $request): ResponseInterface
420    {
421        foreach ($this->tree_service->all() as $tree) {
422            $recursion = $request->getParsedBody()['relationship-recursion-' . $tree->id()] ?? '';
423            $ancestors = $request->getParsedBody()['relationship-ancestors-' . $tree->id()] ?? '';
424
425            $tree->setPreference('RELATIONSHIP_RECURSION', $recursion);
426            $tree->setPreference('RELATIONSHIP_ANCESTORS', $ancestors);
427        }
428
429        FlashMessages::addMessage(I18N::translate('The preferences for the module “%s” have been updated.', $this->title()), 'success');
430
431        return redirect($this->getConfigLink());
432    }
433
434    /**
435     * Possible options for the ancestors option
436     *
437     * @return string[]
438     */
439    private function ancestorsOptions(): array
440    {
441        return [
442            0 => I18N::translate('Find any relationship'),
443            1 => I18N::translate('Find relationships via ancestors'),
444        ];
445    }
446
447    /**
448     * Possible options for the recursion option
449     *
450     * @return string[]
451     */
452    private function recursionConfigOptions(): array
453    {
454        return [
455            0                         => I18N::translate('none'),
456            1                         => I18N::number(1),
457            2                         => I18N::number(2),
458            3                         => I18N::number(3),
459            self::UNLIMITED_RECURSION => I18N::translate('unlimited'),
460        ];
461    }
462
463    /**
464     * Calculate the shortest paths - or all paths - between two individuals.
465     *
466     * @param Individual $individual1
467     * @param Individual $individual2
468     * @param int        $recursion How many levels of recursion to use
469     * @param bool       $ancestor  Restrict to relationships via a common ancestor
470     *
471     * @return string[][]
472     */
473    private function calculateRelationships(Individual $individual1, Individual $individual2, $recursion, $ancestor = false): array
474    {
475        $tree = $individual1->tree();
476
477        $rows = DB::table('link')
478            ->where('l_file', '=', $tree->id())
479            ->whereIn('l_type', ['FAMS', 'FAMC'])
480            ->select(['l_from', 'l_to'])
481            ->get();
482
483        // Optionally restrict the graph to the ancestors of the individuals.
484        if ($ancestor) {
485            $ancestors = $this->allAncestors($individual1->xref(), $individual2->xref(), $tree->id());
486            $exclude   = $this->excludeFamilies($individual1->xref(), $individual2->xref(), $tree->id());
487        } else {
488            $ancestors = [];
489            $exclude   = [];
490        }
491
492        $graph = [];
493
494        foreach ($rows as $row) {
495            if (empty($ancestors) || in_array($row->l_from, $ancestors, true) && !in_array($row->l_to, $exclude, true)) {
496                $graph[$row->l_from][$row->l_to] = 1;
497                $graph[$row->l_to][$row->l_from] = 1;
498            }
499        }
500
501        $xref1    = $individual1->xref();
502        $xref2    = $individual2->xref();
503        $dijkstra = new Dijkstra($graph);
504        $paths    = $dijkstra->shortestPaths($xref1, $xref2);
505
506        // Only process each exclusion list once;
507        $excluded = [];
508
509        $queue = [];
510        foreach ($paths as $path) {
511            // Insert the paths into the queue, with an exclusion list.
512            $queue[] = [
513                'path'    => $path,
514                'exclude' => [],
515            ];
516            // While there are un-extended paths
517            for ($next = current($queue); $next !== false; $next = next($queue)) {
518                // For each family on the path
519                for ($n = count($next['path']) - 2; $n >= 1; $n -= 2) {
520                    $exclude = $next['exclude'];
521                    if (count($exclude) >= $recursion) {
522                        continue;
523                    }
524                    $exclude[] = $next['path'][$n];
525                    sort($exclude);
526                    $tmp = implode('-', $exclude);
527                    if (in_array($tmp, $excluded, true)) {
528                        continue;
529                    }
530
531                    $excluded[] = $tmp;
532                    // Add any new path to the queue
533                    foreach ($dijkstra->shortestPaths($xref1, $xref2, $exclude) as $new_path) {
534                        $queue[] = [
535                            'path'    => $new_path,
536                            'exclude' => $exclude,
537                        ];
538                    }
539                }
540            }
541        }
542        // Extract the paths from the queue.
543        $paths = [];
544        foreach ($queue as $next) {
545            // The Dijkstra library does not use strict types, and converts
546            // numeric array keys (XREFs) from strings to integers;
547            $path = array_map($this->stringMapper(), $next['path']);
548
549            // Remove duplicates
550            $paths[implode('-', $next['path'])] = $path;
551        }
552
553        return $paths;
554    }
555
556    /**
557     * Convert numeric values to strings
558     *
559     * @return Closure
560     */
561    private function stringMapper(): Closure
562    {
563        return static function ($xref) {
564            return (string) $xref;
565        };
566    }
567
568    /**
569     * Find all ancestors of a list of individuals
570     *
571     * @param string $xref1
572     * @param string $xref2
573     * @param int    $tree_id
574     *
575     * @return string[]
576     */
577    private function allAncestors($xref1, $xref2, $tree_id): array
578    {
579        $ancestors = [
580            $xref1,
581            $xref2,
582        ];
583
584        $queue = [
585            $xref1,
586            $xref2,
587        ];
588        while (!empty($queue)) {
589            $parents = DB::table('link AS l1')
590                ->join('link AS l2', static function (JoinClause $join): void {
591                    $join
592                        ->on('l1.l_to', '=', 'l2.l_to')
593                        ->on('l1.l_file', '=', 'l2.l_file');
594                })
595                ->where('l1.l_file', '=', $tree_id)
596                ->where('l1.l_type', '=', 'FAMC')
597                ->where('l2.l_type', '=', 'FAMS')
598                ->whereIn('l1.l_from', $queue)
599                ->pluck('l2.l_from');
600
601            $queue = [];
602            foreach ($parents as $parent) {
603                if (!in_array($parent, $ancestors, true)) {
604                    $ancestors[] = $parent;
605                    $queue[]     = $parent;
606                }
607            }
608        }
609
610        return $ancestors;
611    }
612
613    /**
614     * Find all families of two individuals
615     *
616     * @param string $xref1
617     * @param string $xref2
618     * @param int    $tree_id
619     *
620     * @return string[]
621     */
622    private function excludeFamilies($xref1, $xref2, $tree_id): array
623    {
624        return DB::table('link AS l1')
625            ->join('link AS l2', static function (JoinClause $join): void {
626                $join
627                    ->on('l1.l_to', '=', 'l2.l_to')
628                    ->on('l1.l_type', '=', 'l2.l_type')
629                    ->on('l1.l_file', '=', 'l2.l_file');
630            })
631            ->where('l1.l_file', '=', $tree_id)
632            ->where('l1.l_type', '=', 'FAMS')
633            ->where('l1.l_from', '=', $xref1)
634            ->where('l2.l_from', '=', $xref2)
635            ->pluck('l1.l_to')
636            ->all();
637    }
638
639    /**
640     * Convert a path (list of XREFs) to an "old-style" string of relationships.
641     * Return an empty array, if privacy rules prevent us viewing any node.
642     *
643     * @param Tree     $tree
644     * @param string[] $path Alternately Individual / Family
645     *
646     * @return string[]
647     */
648    private function oldStyleRelationshipPath(Tree $tree, array $path): array
649    {
650        $spouse_codes  = [
651            'M' => 'hus',
652            'F' => 'wif',
653            'U' => 'spo',
654        ];
655        $parent_codes  = [
656            'M' => 'fat',
657            'F' => 'mot',
658            'U' => 'par',
659        ];
660        $child_codes   = [
661            'M' => 'son',
662            'F' => 'dau',
663            'U' => 'chi',
664        ];
665        $sibling_codes = [
666            'M' => 'bro',
667            'F' => 'sis',
668            'U' => 'sib',
669        ];
670        $relationships = [];
671
672        for ($i = 1, $count = count($path); $i < $count; $i += 2) {
673            $family = Family::getInstance($path[$i], $tree);
674            $prev   = Individual::getInstance($path[$i - 1], $tree);
675            $next   = Individual::getInstance($path[$i + 1], $tree);
676            if (preg_match('/\n\d (HUSB|WIFE|CHIL) @' . $prev->xref() . '@/', $family->gedcom(), $match)) {
677                $rel1 = $match[1];
678            } else {
679                return [];
680            }
681            if (preg_match('/\n\d (HUSB|WIFE|CHIL) @' . $next->xref() . '@/', $family->gedcom(), $match)) {
682                $rel2 = $match[1];
683            } else {
684                return [];
685            }
686            if (($rel1 === 'HUSB' || $rel1 === 'WIFE') && ($rel2 === 'HUSB' || $rel2 === 'WIFE')) {
687                $relationships[$i] = $spouse_codes[$next->sex()];
688            } elseif (($rel1 === 'HUSB' || $rel1 === 'WIFE') && $rel2 === 'CHIL') {
689                $relationships[$i] = $child_codes[$next->sex()];
690            } elseif ($rel1 === 'CHIL' && ($rel2 === 'HUSB' || $rel2 === 'WIFE')) {
691                $relationships[$i] = $parent_codes[$next->sex()];
692            } elseif ($rel1 === 'CHIL' && $rel2 === 'CHIL') {
693                $relationships[$i] = $sibling_codes[$next->sex()];
694            }
695        }
696
697        return $relationships;
698    }
699
700    /**
701     * Possible options for the recursion option
702     *
703     * @param int $max_recursion
704     *
705     * @return string[]
706     */
707    private function recursionOptions(int $max_recursion): array
708    {
709        if ($max_recursion === static::UNLIMITED_RECURSION) {
710            $text = I18N::translate('Find all possible relationships');
711        } else {
712            $text = I18N::translate('Find other relationships');
713        }
714
715        return [
716            '0'            => I18N::translate('Find the closest relationships'),
717            $max_recursion => $text,
718        ];
719    }
720}
721