xref: /webtrees/app/Module/IndividualListModule.php (revision 1082dae98fac1db8249bca55d2b3fdce9ae0fac3)
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 Fisharebest\Localization\Locale\LocaleInterface;
24use Fisharebest\Webtrees\Auth;
25use Fisharebest\Webtrees\Contracts\UserInterface;
26use Fisharebest\Webtrees\Family;
27use Fisharebest\Webtrees\GedcomRecord;
28use Fisharebest\Webtrees\I18N;
29use Fisharebest\Webtrees\Individual;
30use Fisharebest\Webtrees\Registry;
31use Fisharebest\Webtrees\Services\LocalizationService;
32use Fisharebest\Webtrees\Session;
33use Fisharebest\Webtrees\Tree;
34use Illuminate\Database\Capsule\Manager as DB;
35use Illuminate\Database\Query\Builder;
36use Illuminate\Database\Query\Expression;
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 array_keys;
44use function assert;
45use function e;
46use function implode;
47use function in_array;
48use function ob_get_clean;
49use function ob_start;
50use function redirect;
51use function route;
52use function usort;
53use function view;
54
55/**
56 * Class IndividualListModule
57 */
58class IndividualListModule extends AbstractModule implements ModuleListInterface, RequestHandlerInterface
59{
60    use ModuleListTrait;
61
62    protected const ROUTE_URL = '/tree/{tree}/individual-list';
63
64    private LocalizationService $localization_service;
65
66    /**
67     * IndividualListModule constructor.
68     *
69     * @param LocalizationService $localization_service
70     */
71    public function __construct(LocalizationService $localization_service)
72    {
73        $this->localization_service = $localization_service;
74    }
75
76    /**
77     * Initialization.
78     *
79     * @return void
80     */
81    public function boot(): void
82    {
83        $router_container = app(RouterContainer::class);
84        assert($router_container instanceof RouterContainer);
85
86        $router_container->getMap()
87            ->get(static::class, static::ROUTE_URL, $this);
88    }
89
90    /**
91     * How should this module be identified in the control panel, etc.?
92     *
93     * @return string
94     */
95    public function title(): string
96    {
97        /* I18N: Name of a module/list */
98        return I18N::translate('Individuals');
99    }
100
101    /**
102     * A sentence describing what this module does.
103     *
104     * @return string
105     */
106    public function description(): string
107    {
108        /* I18N: Description of the “Individuals” module */
109        return I18N::translate('A list of individuals.');
110    }
111
112    /**
113     * CSS class for the URL.
114     *
115     * @return string
116     */
117    public function listMenuClass(): string
118    {
119        return 'menu-list-indi';
120    }
121
122    /**
123     * @param Tree                              $tree
124     * @param array<bool|int|string|array|null> $parameters
125     *
126     * @return string
127     */
128    public function listUrl(Tree $tree, array $parameters = []): string
129    {
130        $xref = app(ServerRequestInterface::class)->getAttribute('xref', '');
131
132        if ($xref !== '') {
133            $individual = Registry::individualFactory()->make($xref, $tree);
134
135            if ($individual instanceof Individual && $individual->canShow()) {
136                $primary_name = $individual->getPrimaryName();
137
138                $parameters['surname'] = $parameters['surname'] ?? $individual->getAllNames()[$primary_name]['surn'] ?? null;
139            }
140        }
141
142        $parameters['tree'] = $tree->name();
143
144        return route(static::class, $parameters);
145    }
146
147    /**
148     * @return array<string>
149     */
150    public function listUrlAttributes(): array
151    {
152        return [];
153    }
154
155    /**
156     * Handle URLs generated by older versions of webtrees
157     *
158     * @param ServerRequestInterface $request
159     *
160     * @return ResponseInterface
161     */
162    public function getListAction(ServerRequestInterface $request): ResponseInterface
163    {
164        return redirect($this->listUrl($request->getAttribute('tree'), $request->getQueryParams()));
165    }
166
167    /**
168     * @param ServerRequestInterface $request
169     *
170     * @return ResponseInterface
171     */
172    public function handle(ServerRequestInterface $request): ResponseInterface
173    {
174        $tree = $request->getAttribute('tree');
175        assert($tree instanceof Tree);
176
177        $user = $request->getAttribute('user');
178        assert($user instanceof UserInterface);
179
180        Auth::checkComponentAccess($this, ModuleListInterface::class, $tree, $user);
181
182        return $this->createResponse($tree, $user, $request->getQueryParams(), false);
183    }
184
185    /**
186     * @param Tree          $tree
187     * @param UserInterface $user
188     * @param array<string> $params
189     * @param bool          $families
190     *
191     * @return ResponseInterface
192     */
193    protected function createResponse(Tree $tree, UserInterface $user, array $params, bool $families): ResponseInterface
194    {
195        ob_start();
196
197        // We show three different lists: initials, surnames and individuals
198
199        // All surnames beginning with this letter where "@"=unknown and ","=none
200        $alpha = $params['alpha'] ?? '';
201
202        // All individuals with this surname
203        $surname = $params['surname'] ?? '';
204
205        // All individuals
206        $show_all = $params['show_all'] ?? 'no';
207
208        // Long lists can be broken down by given name
209        $show_all_firstnames = $params['show_all_firstnames'] ?? 'no';
210        if ($show_all_firstnames === 'yes') {
211            $falpha = '';
212        } else {
213            // All first names beginning with this letter
214            $falpha = $params['falpha'] ?? '';
215        }
216
217        $show_marnm = $params['show_marnm'] ?? '';
218        switch ($show_marnm) {
219            case 'no':
220            case 'yes':
221                $user->setPreference($families ? 'family-list-marnm' : 'individual-list-marnm', $show_marnm);
222                break;
223            default:
224                $show_marnm = $user->getPreference($families ? 'family-list-marnm' : 'individual-list-marnm');
225        }
226
227        // Make sure selections are consistent.
228        // i.e. can’t specify show_all and surname at the same time.
229        if ($show_all === 'yes') {
230            if ($show_all_firstnames === 'yes') {
231                $alpha   = '';
232                $surname = '';
233                $legend  = I18N::translate('All');
234                $params  = [
235                    'tree'     => $tree->name(),
236                    'show_all' => 'yes',
237                ];
238                $show    = 'indi';
239            } elseif ($falpha !== '') {
240                $alpha   = '';
241                $surname = '';
242                $legend  = I18N::translate('All') . ', ' . e($falpha) . '…';
243                $params  = [
244                    'tree'     => $tree->name(),
245                    'show_all' => 'yes',
246                ];
247                $show    = 'indi';
248            } else {
249                $alpha   = '';
250                $surname = '';
251                $legend  = I18N::translate('All');
252                $show    = $params['show'] ?? 'surn';
253                $params  = [
254                    'tree'     => $tree->name(),
255                    'show_all' => 'yes',
256                ];
257            }
258        } elseif ($surname !== '') {
259            $alpha    = $this->localization_service->initialLetter($surname, I18N::locale()); // so we can highlight the initial letter
260            $show_all = 'no';
261            if ($surname === Individual::NOMEN_NESCIO) {
262                $legend = I18N::translateContext('Unknown surname', '…');
263            } else {
264                // The surname parameter is a root/canonical form.
265                // Display it as the actual surname
266                $legend = implode('/', array_keys($this->surnames($tree, $surname, $alpha, $show_marnm === 'yes', $families, I18N::locale())));
267            }
268            $params = [
269                'tree'    => $tree->name(),
270                'surname' => $surname,
271                'falpha'  => $falpha,
272            ];
273            switch ($falpha) {
274                case '':
275                    break;
276                case '@':
277                    $legend .= ', ' . I18N::translateContext('Unknown given name', '…');
278                    break;
279                default:
280                    $legend .= ', ' . e($falpha) . '…';
281                    break;
282            }
283            $show = 'indi'; // SURN list makes no sense here
284        } elseif ($alpha === '@') {
285            $show_all = 'no';
286            $legend   = I18N::translateContext('Unknown surname', '…');
287            $params   = [
288                'alpha' => $alpha,
289                'tree'  => $tree->name(),
290            ];
291            $show     = 'indi'; // SURN list makes no sense here
292        } elseif ($alpha === ',') {
293            $show_all = 'no';
294            $legend   = I18N::translate('None');
295            $params   = [
296                'alpha' => $alpha,
297                'tree'  => $tree->name(),
298            ];
299            $show     = 'indi'; // SURN list makes no sense here
300        } elseif ($alpha !== '') {
301            $show_all = 'no';
302            $legend   = e($alpha) . '…';
303            $show     = $params['show'] ?? 'surn';
304            $params   = [
305                'alpha' => $alpha,
306                'tree'  => $tree->name(),
307            ];
308        } else {
309            $show_all = 'no';
310            $legend   = '…';
311            $params   = [
312                'tree' => $tree->name(),
313            ];
314            $show     = 'none'; // Don't show lists until something is chosen
315        }
316        $legend = '<bdi>' . $legend . '</bdi>';
317
318        if ($families) {
319            $title = I18N::translate('Families') . ' — ' . $legend;
320        } else {
321            $title = I18N::translate('Individuals') . ' — ' . $legend;
322        } ?>
323        <div class="d-flex flex-column wt-page-options wt-page-options-individual-list d-print-none">
324            <ul class="d-flex flex-wrap list-unstyled justify-content-center wt-initials-list wt-initials-list-surname">
325
326                <?php foreach ($this->surnameAlpha($tree, $show_marnm === 'yes', $families, I18N::locale()) as $letter => $count) : ?>
327                    <li class="wt-initials-list-item d-flex">
328                        <?php if ($count > 0) : ?>
329                            <a href="<?= e($this->listUrl($tree, ['alpha' => $letter, 'tree' => $tree->name()])) ?>" class="wt-initial px-1<?= $letter === $alpha ? ' active' : '' ?> '" title="<?= I18N::number($count) ?>"><?= $this->surnameInitial((string) $letter) ?></a>
330                        <?php else : ?>
331                            <span class="wt-initial px-1 text-muted"><?= $this->surnameInitial((string) $letter) ?></span>
332
333                        <?php endif ?>
334                    </li>
335                <?php endforeach ?>
336
337                <?php if (Session::has('initiated')) : ?>
338                    <!-- Search spiders don't get the "show all" option as the other links give them everything. -->
339                    <li class="wt-initials-list-item d-flex">
340                        <a class="wt-initial px-1<?= $show_all === 'yes' ? ' active' : '' ?>" href="<?= e($this->listUrl($tree, ['show_all' => 'yes'] + $params)) ?>"><?= I18N::translate('All') ?></a>
341                    </li>
342                <?php endif ?>
343            </ul>
344
345            <!-- Search spiders don't get an option to show/hide the surname sublists, nor does it make sense on the all/unknown/surname views -->
346            <?php if ($show !== 'none' && Session::has('initiated')) : ?>
347                <?php if ($show_marnm === 'yes') : ?>
348                    <p>
349                        <a href="<?= e($this->listUrl($tree, ['show' => $show, 'show_marnm' => 'no'] + $params)) ?>">
350                            <?= I18N::translate('Exclude individuals with “%s” as a married name', $legend) ?>
351                        </a>
352                    </p>
353                <?php else : ?>
354                    <p>
355                        <a href="<?= e($this->listUrl($tree, ['show' => $show, 'show_marnm' => 'yes'] + $params)) ?>">
356                            <?= I18N::translate('Include individuals with “%s” as a married name', $legend) ?>
357                        </a>
358                    </p>
359                <?php endif ?>
360
361                <?php if ($alpha !== '@' && $alpha !== ',' && $surname === '') : ?>
362                    <?php if ($show === 'surn') : ?>
363                        <p>
364                            <a href="<?= e($this->listUrl($tree, ['show' => 'indi', 'show_marnm' => 'no'] + $params)) ?>">
365                                <?= I18N::translate('Show the list of individuals') ?>
366                            </a>
367                        </p>
368                    <?php else : ?>
369                        <p>
370                            <a href="<?= e($this->listUrl($tree, ['show' => 'surn', 'show_marnm' => 'no'] + $params)) ?>">
371                                <?= I18N::translate('Show the list of surnames') ?>
372                            </a>
373                        </p>
374                    <?php endif ?>
375                <?php endif ?>
376            <?php endif ?>
377        </div>
378
379        <div class="wt-page-content">
380            <?php
381
382            if ($show === 'indi' || $show === 'surn') {
383                $surns = $this->surnames($tree, $surname, $alpha, $show_marnm === 'yes', $families, I18N::locale());
384                if ($show === 'surn') {
385                    // Show the surname list
386                    switch ($tree->getPreference('SURNAME_LIST_STYLE')) {
387                        case 'style1':
388                            echo view('lists/surnames-column-list', [
389                                'module'   => $this,
390                                'surnames' => $surns,
391                                'totals'   => true,
392                                'tree'     => $tree,
393                            ]);
394                            break;
395                        case 'style3':
396                            echo view('lists/surnames-tag-cloud', [
397                                'module'   => $this,
398                                'surnames' => $surns,
399                                'totals'   => true,
400                                'tree'     => $tree,
401                            ]);
402                            break;
403                        case 'style2':
404                        default:
405                            echo view('lists/surnames-table', [
406                                'families' => $families,
407                                'module'   => $this,
408                                'surnames' => $surns,
409                                'tree'     => $tree,
410                            ]);
411                            break;
412                    }
413                } else {
414                    // Show the list
415                    $count = 0;
416                    foreach ($surns as $surnames) {
417                        foreach ($surnames as $total) {
418                            $count += $total;
419                        }
420                    }
421                    // Don't sublist short lists.
422                    if ($count < $tree->getPreference('SUBLIST_TRIGGER_I')) {
423                        $falpha = '';
424                    } else {
425                        $givn_initials = $this->givenAlpha($tree, $surname, $alpha, $show_marnm === 'yes', $families, I18N::locale());
426                        // Break long lists by initial letter of given name
427                        if ($surname !== '' || $show_all === 'yes') {
428                            if ($show_all === 'no') {
429                                echo '<h2 class="wt-page-title">', I18N::translate('Individuals with surname %s', $legend), '</h2>';
430                            }
431                            // Don't show the list until we have some filter criteria
432                            $show = $falpha !== '' || $show_all_firstnames === 'yes' ? 'indi' : 'none';
433                            $list = [];
434                            echo '<ul class="d-flex flex-wrap list-unstyled justify-content-center wt-initials-list wt-initials-list-given-names">';
435                            foreach ($givn_initials as $givn_initial => $given_count) {
436                                echo '<li class="wt-initials-list-item d-flex">';
437                                if ($given_count > 0) {
438                                    if ($show === 'indi' && $givn_initial === $falpha && $show_all_firstnames === 'no') {
439                                        echo '<a class="wt-initial px-1 active" href="' . e($this->listUrl($tree, ['falpha' => $givn_initial] + $params)) . '" title="' . I18N::number($given_count) . '">' . $this->givenNameInitial((string) $givn_initial) . '</a>';
440                                    } else {
441                                        echo '<a class="wt-initial px-1" href="' . e($this->listUrl($tree, ['falpha' => $givn_initial] + $params)) . '" title="' . I18N::number($given_count) . '">' . $this->givenNameInitial((string) $givn_initial) . '</a>';
442                                    }
443                                } else {
444                                    echo '<span class="wt-initial px-1 text-muted">' . $this->givenNameInitial((string) $givn_initial) . '</span>';
445                                }
446                                echo '</li>';
447                            }
448                            // Search spiders don't get the "show all" option as the other links give them everything.
449                            if (Session::has('initiated')) {
450                                echo '<li class="wt-initials-list-item d-flex">';
451                                if ($show_all_firstnames === 'yes') {
452                                    echo '<span class="wt-initial px-1 active">' . I18N::translate('All') . '</span>';
453                                } else {
454                                    echo '<a class="wt-initial px-1" href="' . e($this->listUrl($tree, ['show_all_firstnames' => 'yes'] + $params)) . '" title="' . I18N::number($count) . '">' . I18N::translate('All') . '</a>';
455                                }
456                                echo '</li>';
457                            }
458                            echo '</ul>';
459                            echo '<p class="text-center alpha_index">', implode(' | ', $list), '</p>';
460                        }
461                    }
462                    if ($show === 'indi') {
463                        if (!$families) {
464                            echo view('lists/individuals-table', [
465                                'individuals' => $this->individuals($tree, $surname, $alpha, $falpha, $show_marnm === 'yes', false, I18N::locale()),
466                                'sosa'        => false,
467                                'tree'        => $tree,
468                            ]);
469                        } else {
470                            echo view('lists/families-table', [
471                                'families' => $this->families($tree, $surname, $alpha, $falpha, $show_marnm === 'yes', I18N::locale()),
472                                'tree'     => $tree,
473                            ]);
474                        }
475                    }
476                }
477            } ?>
478        </div>
479        <?php
480
481        $html = ob_get_clean();
482
483        return $this->viewResponse('modules/individual-list/page', [
484            'content' => $html,
485            'title'   => $title,
486            'tree'    => $tree,
487        ]);
488    }
489
490    /**
491     * Some initial letters have a special meaning
492     *
493     * @param string $initial
494     *
495     * @return string
496     */
497    protected function givenNameInitial(string $initial): string
498    {
499        if ($initial === '@') {
500            return I18N::translateContext('Unknown given name', '…');
501        }
502
503        return e($initial);
504    }
505
506    /**
507     * Some initial letters have a special meaning
508     *
509     * @param string $initial
510     *
511     * @return string
512     */
513    protected function surnameInitial(string $initial): string
514    {
515        if ($initial === '@') {
516            return I18N::translateContext('Unknown surname', '…');
517        }
518
519        if ($initial === ',') {
520            return I18N::translate('None');
521        }
522
523        return e($initial);
524    }
525
526    /**
527     * Restrict a query to individuals that are a spouse in a family record.
528     *
529     * @param bool    $fams
530     * @param Builder $query
531     */
532    protected function whereFamily(bool $fams, Builder $query): void
533    {
534        if ($fams) {
535            $query->join('link', static function (JoinClause $join): void {
536                $join
537                    ->on('l_from', '=', 'n_id')
538                    ->on('l_file', '=', 'n_file')
539                    ->where('l_type', '=', 'FAMS');
540            });
541        }
542    }
543
544    /**
545     * Restrict a query to include/exclude married names.
546     *
547     * @param bool    $marnm
548     * @param Builder $query
549     */
550    protected function whereMarriedName(bool $marnm, Builder $query): void
551    {
552        if (!$marnm) {
553            $query->where('n_type', '<>', '_MARNM');
554        }
555    }
556
557    /**
558     * Get a list of initial surname letters.
559     *
560     * @param Tree            $tree
561     * @param bool            $marnm if set, include married names
562     * @param bool            $fams  if set, only consider individuals with FAMS records
563     * @param LocaleInterface $locale
564     *
565     * @return array<int>
566     */
567    public function surnameAlpha(Tree $tree, bool $marnm, bool $fams, LocaleInterface $locale): array
568    {
569        $collation = $this->localization_service->collation($locale);
570
571        $n_surn = $this->fieldWithCollation('n_surn', $collation);
572        $alphas = [];
573
574        $query = DB::table('name')->where('n_file', '=', $tree->id());
575
576        $this->whereFamily($fams, $query);
577        $this->whereMarriedName($marnm, $query);
578
579        // Fetch all the letters in our alphabet, whether or not there
580        // are any names beginning with that letter. It looks better to
581        // show the full alphabet, rather than omitting rare letters such as X.
582        foreach ($this->localization_service->alphabet($locale) as $letter) {
583            $query2 = clone $query;
584
585            $this->whereInitial($query2, 'n_surn', $letter, $locale);
586
587            $alphas[$letter] = $query2->count();
588        }
589
590        // Now fetch initial letters that are not in our alphabet,
591        // including "@" (for "@N.N.") and "" for no surname.
592        foreach ($this->localization_service->alphabet($locale) as $letter) {
593            $query->where($n_surn, 'NOT LIKE', $letter . '%');
594        }
595
596        $rows = $query
597            ->groupBy(['initial'])
598            ->orderBy('initial')
599            ->pluck(new Expression('COUNT(*) AS aggregate'), new Expression('SUBSTR(n_surn, 1, 1) AS initial'));
600
601        $specials = ['@', ''];
602
603        foreach ($rows as $alpha => $count) {
604            if (!in_array($alpha, $specials, true)) {
605                $alphas[$alpha] = (int) $count;
606            }
607        }
608
609        // Empty surnames have a special code ',' - as we search for SURN.GIVN
610        foreach ($specials as $special) {
611            if ($rows->has($special)) {
612                $alphas[$special ?: ','] = (int) $rows[$special];
613            }
614        }
615
616        return $alphas;
617    }
618
619    /**
620     * Get a list of initial given name letters for indilist.php and famlist.php
621     *
622     * @param Tree            $tree
623     * @param string          $surn   if set, only consider people with this surname
624     * @param string          $salpha if set, only consider surnames starting with this letter
625     * @param bool            $marnm  if set, include married names
626     * @param bool            $fams   if set, only consider individuals with FAMS records
627     * @param LocaleInterface $locale
628     *
629     * @return array<int>
630     */
631    public function givenAlpha(Tree $tree, string $surn, string $salpha, bool $marnm, bool $fams, LocaleInterface $locale): array
632    {
633        $collation = $this->localization_service->collation($locale);
634
635        $alphas = [];
636
637        $query = DB::table('name')
638            ->where('n_file', '=', $tree->id());
639
640        $this->whereFamily($fams, $query);
641        $this->whereMarriedName($marnm, $query);
642
643        if ($surn !== '') {
644            $n_surn = $this->fieldWithCollation('n_surn', $collation);
645            $query->where($n_surn, '=', $surn);
646        } elseif ($salpha === ',') {
647            $query->where('n_surn', '=', '');
648        } elseif ($salpha === '@') {
649            $query->where('n_surn', '=', Individual::NOMEN_NESCIO);
650        } elseif ($salpha !== '') {
651            $this->whereInitial($query, 'n_surn', $salpha, $locale);
652        } else {
653            // All surnames
654            $query->whereNotIn('n_surn', ['', Individual::NOMEN_NESCIO]);
655        }
656
657        // Fetch all the letters in our alphabet, whether or not there
658        // are any names beginning with that letter. It looks better to
659        // show the full alphabet, rather than omitting rare letters such as X
660        foreach ($this->localization_service->alphabet($locale) as $letter) {
661            $query2 = clone $query;
662
663            $this->whereInitial($query2, 'n_givn', $letter, $locale);
664
665            $alphas[$letter] = $query2->distinct()->count('n_id');
666        }
667
668        $rows = $query
669            ->groupBy(['initial'])
670            ->orderBy('initial')
671            ->pluck(new Expression('COUNT(*) AS aggregate'), new Expression('UPPER(SUBSTR(n_givn, 1, 1)) AS initial'));
672
673        foreach ($rows as $alpha => $count) {
674            if ($alpha !== '@') {
675                $alphas[$alpha] = (int) $count;
676            }
677        }
678
679        if ($rows->has('@')) {
680            $alphas['@'] = (int) $rows['@'];
681        }
682
683        return $alphas;
684    }
685
686    /**
687     * Get a count of actual surnames and variants, based on a "root" surname.
688     *
689     * @param Tree            $tree
690     * @param string          $surn   if set, only count people with this surname
691     * @param string          $salpha if set, only consider surnames starting with this letter
692     * @param bool            $marnm  if set, include married names
693     * @param bool            $fams   if set, only consider individuals with FAMS records
694     * @param LocaleInterface $locale
695     *
696     * @return array<array<int>>
697     */
698    public function surnames(
699        Tree $tree,
700        string $surn,
701        string $salpha,
702        bool $marnm,
703        bool $fams,
704        LocaleInterface $locale
705    ): array {
706        $collation = $this->localization_service->collation($locale);
707
708        $query = DB::table('name')
709            ->where('n_file', '=', $tree->id())
710            ->select([
711                new Expression('UPPER(n_surn /*! COLLATE ' . $collation . ' */) AS n_surn'),
712                new Expression('n_surname /*! COLLATE utf8_bin */ AS n_surname'),
713                new Expression('COUNT(*) AS total'),
714            ]);
715
716        $this->whereFamily($fams, $query);
717        $this->whereMarriedName($marnm, $query);
718
719        if ($surn !== '') {
720            $query->where('n_surn', '=', $surn);
721        } elseif ($salpha === ',') {
722            $query->where('n_surn', '=', '');
723        } elseif ($salpha === '@') {
724            $query->where('n_surn', '=', Individual::NOMEN_NESCIO);
725        } elseif ($salpha !== '') {
726            $this->whereInitial($query, 'n_surn', $salpha, $locale);
727        } else {
728            // All surnames
729            $query->whereNotIn('n_surn', ['', Individual::NOMEN_NESCIO]);
730        }
731        $query
732            ->groupBy(['n_surn'])
733            ->groupBy(['n_surname'])
734            ->orderBy('n_surname');
735
736        $list = [];
737
738        foreach ($query->get() as $row) {
739            $list[$row->n_surn][$row->n_surname] = (int) $row->total;
740        }
741
742        return $list;
743    }
744
745    /**
746     * Fetch a list of individuals with specified names
747     * To search for unknown names, use $surn="@N.N.", $salpha="@" or $galpha="@"
748     * To search for names with no surnames, use $salpha=","
749     *
750     * @param Tree            $tree
751     * @param string          $surn   if set, only fetch people with this surname
752     * @param string          $salpha if set, only fetch surnames starting with this letter
753     * @param string          $galpha if set, only fetch given names starting with this letter
754     * @param bool            $marnm  if set, include married names
755     * @param bool            $fams   if set, only fetch individuals with FAMS records
756     * @param LocaleInterface $locale
757     *
758     * @return array<Individual>
759     */
760    public function individuals(
761        Tree $tree,
762        string $surn,
763        string $salpha,
764        string $galpha,
765        bool $marnm,
766        bool $fams,
767        LocaleInterface $locale
768    ): array {
769        $collation = $this->localization_service->collation($locale);
770
771        // Use specific collation for name fields.
772        $n_givn = $this->fieldWithCollation('n_givn', $collation);
773        $n_surn = $this->fieldWithCollation('n_surn', $collation);
774
775        $query = DB::table('individuals')
776            ->join('name', static function (JoinClause $join): void {
777                $join
778                    ->on('n_id', '=', 'i_id')
779                    ->on('n_file', '=', 'i_file');
780            })
781            ->where('i_file', '=', $tree->id())
782            ->select(['i_id AS xref', 'i_gedcom AS gedcom', 'n_givn', 'n_surn']);
783
784        $this->whereFamily($fams, $query);
785        $this->whereMarriedName($marnm, $query);
786
787        if ($surn) {
788            $query->where($n_surn, '=', $surn);
789        } elseif ($salpha === ',') {
790            $query->where($n_surn, '=', '');
791        } elseif ($salpha === '@') {
792            $query->where($n_surn, '=', Individual::NOMEN_NESCIO);
793        } elseif ($salpha) {
794            $this->whereInitial($query, 'n_surn', $salpha, $locale);
795        } else {
796            // All surnames
797            $query->whereNotIn($n_surn, ['', Individual::NOMEN_NESCIO]);
798        }
799        if ($galpha) {
800            $this->whereInitial($query, 'n_givn', $galpha, $locale);
801        }
802
803        $query
804            ->orderBy(new Expression("CASE n_surn WHEN '" . Individual::NOMEN_NESCIO . "' THEN 1 ELSE 0 END"))
805            ->orderBy($n_surn)
806            ->orderBy(new Expression("CASE n_givn WHEN '" . Individual::NOMEN_NESCIO . "' THEN 1 ELSE 0 END"))
807            ->orderBy($n_givn);
808
809        $list = [];
810        $rows = $query->get();
811
812        foreach ($rows as $row) {
813            $individual = Registry::individualFactory()->make($row->xref, $tree, $row->gedcom);
814            assert($individual instanceof Individual);
815
816            // The name from the database may be private - check the filtered list...
817            foreach ($individual->getAllNames() as $n => $name) {
818                if ($name['givn'] === $row->n_givn && $name['surn'] === $row->n_surn) {
819                    $individual->setPrimaryName($n);
820                    // We need to clone $individual, as we may have multiple references to the
821                    // same individual in this list, and the "primary name" would otherwise
822                    // be shared amongst all of them.
823                    $list[] = clone $individual;
824                    break;
825                }
826            }
827        }
828
829        return $list;
830    }
831
832    /**
833     * Fetch a list of families with specified names
834     * To search for unknown names, use $surn="@N.N.", $salpha="@" or $galpha="@"
835     * To search for names with no surnames, use $salpha=","
836     *
837     * @param Tree            $tree
838     * @param string          $surn   if set, only fetch people with this surname
839     * @param string          $salpha if set, only fetch surnames starting with this letter
840     * @param string          $galpha if set, only fetch given names starting with this letter
841     * @param bool            $marnm  if set, include married names
842     * @param LocaleInterface $locale
843     *
844     * @return array<Family>
845     */
846    public function families(Tree $tree, string $surn, string $salpha, string $galpha, bool $marnm, LocaleInterface $locale): array
847    {
848        $list = [];
849        foreach ($this->individuals($tree, $surn, $salpha, $galpha, $marnm, true, $locale) as $indi) {
850            foreach ($indi->spouseFamilies() as $family) {
851                $list[$family->xref()] = $family;
852            }
853        }
854        usort($list, GedcomRecord::nameComparator());
855
856        return $list;
857    }
858
859    /**
860     * Use MySQL-specific comments so we can run these queries on other RDBMS.
861     *
862     * @param string $field
863     * @param string $collation
864     *
865     * @return Expression
866     */
867    protected function fieldWithCollation(string $field, string $collation): Expression
868    {
869        return new Expression($field . ' /*! COLLATE ' . $collation . ' */');
870    }
871
872    /**
873     * Modify a query to restrict a field to a given initial letter.
874     * Take account of digraphs, equialent letters, etc.
875     *
876     * @param Builder         $query
877     * @param string          $field
878     * @param string          $letter
879     * @param LocaleInterface $locale
880     *
881     * @return void
882     */
883    protected function whereInitial(
884        Builder $query,
885        string $field,
886        string $letter,
887        LocaleInterface $locale
888    ): void {
889        $collation = $this->localization_service->collation($locale);
890
891        // Use MySQL-specific comments so we can run these queries on other RDBMS.
892        $field_with_collation = $this->fieldWithCollation($field, $collation);
893
894        switch ($locale->languageTag()) {
895            case 'cs':
896                $this->whereInitialCzech($query, $field_with_collation, $letter);
897                break;
898
899            case 'da':
900            case 'nb':
901            case 'nn':
902                $this->whereInitialNorwegian($query, $field_with_collation, $letter);
903                break;
904
905            case 'sv':
906            case 'fi':
907                $this->whereInitialSwedish($query, $field_with_collation, $letter);
908                break;
909
910            case 'hu':
911                $this->whereInitialHungarian($query, $field_with_collation, $letter);
912                break;
913
914            case 'nl':
915                $this->whereInitialDutch($query, $field_with_collation, $letter);
916                break;
917
918            default:
919                $query->where($field_with_collation, 'LIKE', '\\' . $letter . '%');
920        }
921    }
922
923    /**
924     * @param Builder    $query
925     * @param Expression $field
926     * @param string     $letter
927     */
928    protected function whereInitialCzech(Builder $query, Expression $field, string $letter): void
929    {
930        if ($letter === 'C') {
931            $query->where($field, 'LIKE', 'C%')->where($field, 'NOT LIKE', 'CH%');
932        } else {
933            $query->where($field, 'LIKE', '\\' . $letter . '%');
934        }
935    }
936
937    /**
938     * @param Builder    $query
939     * @param Expression $field
940     * @param string     $letter
941     */
942    protected function whereInitialDutch(Builder $query, Expression $field, string $letter): void
943    {
944        if ($letter === 'I') {
945            $query->where($field, 'LIKE', 'I%')->where($field, 'NOT LIKE', 'IJ%');
946        } else {
947            $query->where($field, 'LIKE', '\\' . $letter . '%');
948        }
949    }
950
951    /**
952     * Hungarian has many digraphs and trigraphs, so exclude these from prefixes.
953     *
954     * @param Builder    $query
955     * @param Expression $field
956     * @param string     $letter
957     */
958    protected function whereInitialHungarian(Builder $query, Expression $field, string $letter): void
959    {
960        switch ($letter) {
961            case 'C':
962                $query->where($field, 'LIKE', 'C%')->where($field, 'NOT LIKE', 'CS%');
963                break;
964
965            case 'D':
966                $query->where($field, 'LIKE', 'D%')->where($field, 'NOT LIKE', 'DZ%');
967                break;
968
969            case 'DZ':
970                $query->where($field, 'LIKE', 'DZ%')->where($field, 'NOT LIKE', 'DZS%');
971                break;
972
973            case 'G':
974                $query->where($field, 'LIKE', 'G%')->where($field, 'NOT LIKE', 'GY%');
975                break;
976
977            case 'L':
978                $query->where($field, 'LIKE', 'L%')->where($field, 'NOT LIKE', 'LY%');
979                break;
980
981            case 'N':
982                $query->where($field, 'LIKE', 'N%')->where($field, 'NOT LIKE', 'NY%');
983                break;
984
985            case 'S':
986                $query->where($field, 'LIKE', 'S%')->where($field, 'NOT LIKE', 'SZ%');
987                break;
988
989            case 'T':
990                $query->where($field, 'LIKE', 'T%')->where($field, 'NOT LIKE', 'TY%');
991                break;
992
993            case 'Z':
994                $query->where($field, 'LIKE', 'Z%')->where($field, 'NOT LIKE', 'ZS%');
995                break;
996
997            default:
998                $query->where($field, 'LIKE', '\\' . $letter . '%');
999                break;
1000        }
1001    }
1002
1003    /**
1004     * In Norwegian and Danish, AA gets listed under Å, NOT A
1005     *
1006     * @param Builder    $query
1007     * @param Expression $field
1008     * @param string     $letter
1009     */
1010    protected function whereInitialNorwegian(Builder $query, Expression $field, string $letter): void
1011    {
1012        switch ($letter) {
1013            case 'A':
1014                $query->where($field, 'LIKE', 'A%')->where($field, 'NOT LIKE', 'AA%');
1015                break;
1016
1017            case 'Å':
1018                $query->where(static function (Builder $query) use ($field): void {
1019                    $query
1020                        ->where($field, 'LIKE', 'Å%')
1021                        ->orWhere($field, 'LIKE', 'AA%');
1022                });
1023                break;
1024
1025            default:
1026                $query->where($field, 'LIKE', '\\' . $letter . '%');
1027                break;
1028        }
1029    }
1030
1031    /**
1032     * In Swedish and Finnish, AA gets listed under A, NOT Å (even though Swedish collation says they should).
1033     *
1034     * @param Builder    $query
1035     * @param Expression $field
1036     * @param string     $letter
1037     */
1038    protected function whereInitialSwedish(Builder $query, Expression $field, string $letter): void
1039    {
1040        if ($letter === 'Å') {
1041            $query->where($field, 'LIKE', 'Å%')->where($field, 'NOT LIKE', 'AA%');
1042        } else {
1043            $query->where($field, 'LIKE', '\\' . $letter . '%');
1044        }
1045    }
1046}
1047