xref: /webtrees/app/Module/RelationshipsChartModule.php (revision 7c4add84379afdbaa7c4c272763673edc20fb830)
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 Fisharebest\Webtrees\User;
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, RequestHandlerInterface
53{
54    use ModuleChartTrait;
55    use ModuleConfigTrait;
56
57    private const ROUTE_NAME = 'relationships';
58    private const ROUTE_URL  = '/tree/{tree}/relationships-{ancestors}-{recursion}/{xref}{/xref2}';
59
60    /** It would be more correct to use PHP_INT_MAX, but this isn't friendly in URLs */
61    public const UNLIMITED_RECURSION = 99;
62
63    /** By default new trees allow unlimited recursion */
64    public const DEFAULT_RECURSION = '99';
65
66    /** By default new trees search for all relationships (not via ancestors) */
67    public const DEFAULT_ANCESTORS  = '0';
68    public const DEFAULT_PARAMETERS = [
69        'ancestors' => self::DEFAULT_ANCESTORS,
70        'recursion' => self::DEFAULT_RECURSION,
71    ];
72
73    /** @var TreeService */
74    private $tree_service;
75
76    /**
77     * ModuleController constructor.
78     *
79     * @param TreeService   $tree_service
80     */
81    public function __construct(TreeService $tree_service)
82    {
83        $this->tree_service = $tree_service;
84    }
85
86    /**
87     * Initialization.
88     *
89     * @return void
90     */
91    public function boot(): void
92    {
93        $router_container = app(RouterContainer::class);
94        assert($router_container instanceof RouterContainer);
95
96        $router_container->getMap()
97            ->get(self::ROUTE_NAME, self::ROUTE_URL, $this)
98            ->allows(RequestMethodInterface::METHOD_POST)
99            ->tokens([
100                'ancestors' => '\d+',
101                'recursion' => '\d+',
102            ]);
103    }
104
105    /**
106     * A sentence describing what this module does.
107     *
108     * @return string
109     */
110    public function description(): string
111    {
112        /* I18N: Description of the “RelationshipsChart” module */
113        return I18N::translate('A chart displaying relationships between two individuals.');
114    }
115
116    /**
117     * Return a menu item for this chart - for use in individual boxes.
118     *
119     * @param Individual $individual
120     *
121     * @return Menu|null
122     */
123    public function chartBoxMenu(Individual $individual): ?Menu
124    {
125        return $this->chartMenu($individual);
126    }
127
128    /**
129     * A main menu item for this chart.
130     *
131     * @param Individual $individual
132     *
133     * @return Menu
134     */
135    public function chartMenu(Individual $individual): Menu
136    {
137        $gedcomid = $individual->tree()->getUserPreference(Auth::user(), User::PREF_TREE_ACCOUNT_XREF);
138
139        if ($gedcomid !== '' && $gedcomid !== $individual->xref()) {
140            return new Menu(
141                I18N::translate('Relationship to me'),
142                $this->chartUrl($individual, ['xref2' => $gedcomid]),
143                $this->chartMenuClass(),
144                $this->chartUrlAttributes()
145            );
146        }
147
148        return new Menu(
149            $this->title(),
150            $this->chartUrl($individual),
151            $this->chartMenuClass(),
152            $this->chartUrlAttributes()
153        );
154    }
155
156    /**
157     * CSS class for the URL.
158     *
159     * @return string
160     */
161    public function chartMenuClass(): string
162    {
163        return 'menu-chart-relationship';
164    }
165
166    /**
167     * How should this module be identified in the control panel, etc.?
168     *
169     * @return string
170     */
171    public function title(): string
172    {
173        /* I18N: Name of a module/chart */
174        return I18N::translate('Relationships');
175    }
176
177    /**
178     * The URL for a page showing chart options.
179     *
180     * @param Individual $individual
181     * @param mixed[]    $parameters
182     *
183     * @return string
184     */
185    public function chartUrl(Individual $individual, array $parameters = []): string
186    {
187        return route(self::ROUTE_NAME, [
188                'xref' => $individual->xref(),
189                'tree' => $individual->tree()->name(),
190            ] + $parameters + self::DEFAULT_PARAMETERS);
191    }
192
193    /**
194     * @param ServerRequestInterface $request
195     *
196     * @return ResponseInterface
197     */
198    public function handle(ServerRequestInterface $request): ResponseInterface
199    {
200        $tree = $request->getAttribute('tree');
201        assert($tree instanceof Tree);
202
203        $xref = $request->getAttribute('xref');
204        assert(is_string($xref));
205
206        $xref2 = $request->getAttribute('xref2') ?? '';
207
208        $ajax      = $request->getQueryParams()['ajax'] ?? '';
209        $ancestors = (int) $request->getAttribute('ancestors');
210        $recursion = (int) $request->getAttribute('recursion');
211        $user      = $request->getAttribute('user');
212
213        // Convert POST requests into GET requests for pretty URLs.
214        if ($request->getMethod() === RequestMethodInterface::METHOD_POST) {
215            return redirect(route(self::ROUTE_NAME, [
216                'ancestors' => $request->getParsedBody()['ancestors'],
217                'recursion' => $request->getParsedBody()['recursion'],
218                'tree'      => $tree->name(),
219                'xref'      => $request->getParsedBody()['xref'],
220                'xref2'     => $request->getParsedBody()['xref2'],
221            ]));
222        }
223
224        $individual1 = Individual::getInstance($xref, $tree);
225        $individual2 = Individual::getInstance($xref2, $tree);
226
227        $ancestors_only = (int) $tree->getPreference('RELATIONSHIP_ANCESTORS', static::DEFAULT_ANCESTORS);
228        $max_recursion  = (int) $tree->getPreference('RELATIONSHIP_RECURSION', static::DEFAULT_RECURSION);
229
230        $recursion = min($recursion, $max_recursion);
231
232        if ($tree->getPreference('SHOW_PRIVATE_RELATIONSHIPS') !== '1') {
233            if ($individual1 instanceof Individual) {
234                $individual1 = Auth::checkIndividualAccess($individual1);
235            }
236
237            if ($individual2 instanceof Individual) {
238                $individual2 = Auth::checkIndividualAccess($individual2);
239            }
240        }
241
242        Auth::checkComponentAccess($this, 'chart', $tree, $user);
243
244        if ($individual1 instanceof Individual && $individual2 instanceof Individual) {
245            if ($ajax === '1') {
246                return $this->chart($individual1, $individual2, $recursion, $ancestors);
247            }
248
249            /* I18N: %s are individual’s names */
250            $title    = I18N::translate('Relationships between %1$s and %2$s', $individual1->fullName(), $individual2->fullName());
251            $ajax_url = $this->chartUrl($individual1, [
252                'ajax'      => true,
253                'ancestors' => $ancestors,
254                'recursion' => $recursion,
255                'xref2'     => $individual2->xref(),
256            ]);
257        } else {
258            $title    = I18N::translate('Relationships');
259            $ajax_url = '';
260        }
261
262        return $this->viewResponse('modules/relationships-chart/page', [
263            'ajax_url'          => $ajax_url,
264            'ancestors'         => $ancestors,
265            'ancestors_only'    => $ancestors_only,
266            'ancestors_options' => $this->ancestorsOptions(),
267            'individual1'       => $individual1,
268            'individual2'       => $individual2,
269            'max_recursion'     => $max_recursion,
270            'module'            => $this->name(),
271            'recursion'         => $recursion,
272            'recursion_options' => $this->recursionOptions($max_recursion),
273            'title'             => $title,
274            'tree'              => $tree,
275        ]);
276    }
277
278    /**
279     * @param Individual $individual1
280     * @param Individual $individual2
281     * @param int        $recursion
282     * @param int        $ancestors
283     *
284     * @return ResponseInterface
285     */
286    public function chart(Individual $individual1, Individual $individual2, int $recursion, int $ancestors): ResponseInterface
287    {
288        $tree = $individual1->tree();
289
290        $max_recursion = (int) $tree->getPreference('RELATIONSHIP_RECURSION', static::DEFAULT_RECURSION);
291
292        $recursion = min($recursion, $max_recursion);
293
294        $paths = $this->calculateRelationships($individual1, $individual2, $recursion, (bool) $ancestors);
295
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