xref: /webtrees/app/Module/IndividualListModule.php (revision 7dcc0dd1f98a779ae8ed3c9c0b53d14ead31a778)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2023 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 Fig\Http\Message\StatusCodeInterface;
23use Fisharebest\Webtrees\Auth;
24use Fisharebest\Webtrees\DB;
25use Fisharebest\Webtrees\Family;
26use Fisharebest\Webtrees\I18N;
27use Fisharebest\Webtrees\Individual;
28use Fisharebest\Webtrees\Registry;
29use Fisharebest\Webtrees\Session;
30use Fisharebest\Webtrees\Tree;
31use Fisharebest\Webtrees\Validator;
32use Illuminate\Database\Query\Builder;
33use Illuminate\Database\Query\Expression;
34use Illuminate\Database\Query\JoinClause;
35use Illuminate\Support\Collection;
36use Psr\Http\Message\ResponseInterface;
37use Psr\Http\Message\ServerRequestInterface;
38use Psr\Http\Server\RequestHandlerInterface;
39
40use function array_filter;
41use function array_keys;
42use function array_map;
43use function array_merge;
44use function array_sum;
45use function array_values;
46use function assert;
47use function e;
48use function implode;
49use function ob_get_clean;
50use function ob_start;
51use function route;
52use function uksort;
53use function usort;
54use function view;
55
56use const ARRAY_FILTER_USE_KEY;
57
58/**
59 * Class IndividualListModule
60 */
61class IndividualListModule extends AbstractModule implements ModuleListInterface, RequestHandlerInterface
62{
63    use ModuleListTrait;
64
65    protected const ROUTE_URL = '/tree/{tree}/individual-list';
66
67    // The individual list and family list use the same code/logic.
68    // They just display different lists.
69    protected bool $families = false;
70
71    /**
72     * Initialization.
73     *
74     * @return void
75     */
76    public function boot(): void
77    {
78        Registry::routeFactory()->routeMap()
79            ->get(static::class, static::ROUTE_URL, $this);
80    }
81
82    /**
83     * How should this module be identified in the control panel, etc.?
84     *
85     * @return string
86     */
87    public function title(): string
88    {
89        /* I18N: Name of a module/list */
90        return I18N::translate('Individuals');
91    }
92
93    /**
94     * A sentence describing what this module does.
95     *
96     * @return string
97     */
98    public function description(): string
99    {
100        /* I18N: Description of the “Individuals” module */
101        return I18N::translate('A list of individuals.');
102    }
103
104    /**
105     * CSS class for the URL.
106     *
107     * @return string
108     */
109    public function listMenuClass(): string
110    {
111        return 'menu-list-indi';
112    }
113
114    /**
115     * @param Tree                                      $tree
116     * @param array<bool|int|string|array<string>|null> $parameters
117     *
118     * @return string
119     */
120    public function listUrl(Tree $tree, array $parameters = []): string
121    {
122        $request = Registry::container()->get(ServerRequestInterface::class);
123        $xref    = Validator::attributes($request)->isXref()->string('xref', '');
124
125        if ($xref !== '') {
126            $individual = Registry::individualFactory()->make($xref, $tree);
127
128            if ($individual instanceof Individual && $individual->canShow()) {
129                $primary_name = $individual->getPrimaryName();
130
131                $parameters['surname'] ??= $individual->getAllNames()[$primary_name]['surn'] ?? null;
132            }
133        }
134
135        $parameters['tree'] = $tree->name();
136
137        return route(static::class, $parameters);
138    }
139
140    /**
141     * @return array<string>
142     */
143    public function listUrlAttributes(): array
144    {
145        return [];
146    }
147
148    /**
149     * @param ServerRequestInterface $request
150     *
151     * @return ResponseInterface
152     */
153    public function handle(ServerRequestInterface $request): ResponseInterface
154    {
155        $tree = Validator::attributes($request)->tree();
156        $user = Validator::attributes($request)->user();
157
158        Auth::checkComponentAccess($this, ModuleListInterface::class, $tree, $user);
159
160        // All individuals with this surname
161        $surname_param = Validator::queryParams($request)->string('surname', '');
162        $surname       = I18N::strtoupper(I18N::language()->normalize($surname_param));
163
164        // All surnames beginning with this letter, where "@" is unknown and "," is none
165        $alpha = Validator::queryParams($request)->string('alpha', '');
166
167        // All first names beginning with this letter where "@" is unknown
168        $falpha = Validator::queryParams($request)->string('falpha', '');
169
170        // What type of list to display, if any
171        $show = Validator::queryParams($request)->string('show', 'surn');
172
173        // All individuals
174        $show_all = Validator::queryParams($request)->string('show_all', '');
175
176        // Include/exclude married names
177        $show_marnm = Validator::queryParams($request)->string('show_marnm', '');
178
179        // Break long lists down by given name
180        $show_all_firstnames = Validator::queryParams($request)->string('show_all_firstnames', '');
181
182        $params = [
183            'alpha'               => $alpha,
184            'falpha'              => $falpha,
185            'show'                => $show,
186            'show_all'            => $show_all,
187            'show_all_firstnames' => $show_all_firstnames,
188            'show_marnm'          => $show_marnm,
189            'surname'             => $surname,
190        ];
191
192        if ($surname_param !== $surname) {
193            return Registry::responseFactory()
194                ->redirectUrl($this->listUrl($tree, $params), StatusCodeInterface::STATUS_MOVED_PERMANENTLY);
195        }
196
197
198        // Make sure parameters are consistent with each other.
199        if ($show_all_firstnames === 'yes') {
200            $falpha = '';
201        }
202
203        if ($show_all === 'yes') {
204            $alpha   = '';
205            $surname = '';
206        }
207
208        if ($surname !== '') {
209            $alpha = I18N::language()->initialLetter($surname);
210        }
211
212        $surname_data     = $this->surnameData($tree, $show_marnm === 'yes', $this->families);
213        $all_surns        = $this->allSurns($surname_data);
214        $all_surnames     = $this->allSurnames($surname_data);
215        $surname_initials = $this->surnameInitials($surname_data);
216
217        // Make sure selections are consistent.
218        // i.e. can’t specify show_all and surname at the same time.
219        if ($show_all === 'yes') {
220            if ($show_all_firstnames === 'yes') {
221                $legend = I18N::translate('All');
222                $params = ['tree' => $tree->name(), 'show_all' => 'yes', 'show_marnm' => $show_marnm];
223                $show   = 'indi';
224            } elseif ($falpha !== '') {
225                $legend = I18N::translate('All') . ', ' . e($falpha) . '…';
226                $params = ['tree' => $tree->name(), 'show_all' => 'yes', 'show_marnm' => $show_marnm];
227                $show   = 'indi';
228            } else {
229                $legend = I18N::translate('All');
230                $params = ['tree' => $tree->name(), 'show_all' => 'yes', 'show_marnm' => $show_marnm];
231            }
232        } elseif ($surname !== '') {
233            $show_all = 'no';
234            if ($surname === Individual::NOMEN_NESCIO) {
235                $legend = I18N::translateContext('Unknown surname', '…');
236                $show   = 'indi'; // The surname list makes no sense with only one surname.
237            } else {
238                // The surname parameter is a root/canonical form. Display the actual surnames found.
239                $variants = array_keys($all_surnames[$surname] ?? [$surname => $surname]);
240                usort($variants, I18N::comparator());
241                $variants = array_map(static fn (string $x): string => $x === '' ? I18N::translate('No surname') : $x, $variants);
242                $legend   = implode('/', $variants);
243                $show     = 'indi'; // The surname list makes no sense with only one surname.
244            }
245            $params = ['tree' => $tree->name(), 'surname' => $surname, 'falpha' => $falpha, 'show_marnm' => $show_marnm];
246            switch ($falpha) {
247                case '':
248                    break;
249                case '@':
250                    $legend .= ', ' . I18N::translateContext('Unknown given name', '…');
251                    break;
252                default:
253                    $legend .= ', ' . e($falpha) . '…';
254                    break;
255            }
256        } elseif ($alpha === '@') {
257            $show_all = 'no';
258            $legend   = I18N::translateContext('Unknown surname', '…');
259            $params   = ['alpha' => $alpha, 'tree' => $tree->name(), 'show_marnm' => $show_marnm];
260            $surname  = Individual::NOMEN_NESCIO;
261            $show     = 'indi'; // SURN list makes no sense here
262        } elseif ($alpha === ',') {
263            $show_all = 'no';
264            $legend   = I18N::translate('No surname');
265            $params   = ['alpha' => $alpha, 'tree' => $tree->name(), 'show_marnm' => $show_marnm];
266            $show     = 'indi'; // SURN list makes no sense here
267        } elseif ($alpha !== '') {
268            $show_all = 'no';
269            $legend   = e($alpha) . '…';
270            $params   = ['alpha' => $alpha, 'tree' => $tree->name(), 'show_marnm' => $show_marnm];
271        } else {
272            $show_all = 'no';
273            $legend   = '…';
274            $params   = ['tree' => $tree->name(), 'show_marnm' => $show_marnm];
275            $show     = 'none'; // Don't show lists until something is chosen
276        }
277        $legend = '<bdi>' . $legend . '</bdi>';
278
279        if ($this->families) {
280            $title = I18N::translate('Families') . ' — ' . $legend;
281        } else {
282            $title = I18N::translate('Individuals') . ' — ' . $legend;
283        }
284
285        ob_start(); ?>
286        <div class="d-flex flex-column wt-page-options wt-page-options-individual-list d-print-none">
287            <ul class="d-flex flex-wrap list-unstyled justify-content-center wt-initials-list wt-initials-list-surname">
288
289                <?php foreach ($surname_initials as $letter => $count) : ?>
290                    <li class="wt-initials-list-item d-flex">
291                        <?php if ($count > 0) : ?>
292                            <a href="<?= e($this->listUrl($tree, ['alpha' => $letter, 'show_marnm' => $show_marnm, 'tree' => $tree->name()])) ?>" class="wt-initial px-1<?= $letter === $alpha ? ' active' : '' ?> '" title="<?= I18N::number($count) ?>"><?= $this->displaySurnameInitial((string) $letter) ?></a>
293                        <?php else : ?>
294                            <span class="wt-initial px-1 text-muted"><?= $this->displaySurnameInitial((string) $letter) ?></span>
295
296                        <?php endif ?>
297                    </li>
298                <?php endforeach ?>
299
300                <?php if (Session::has('initiated')) : ?>
301                    <!-- Search spiders don't get the "show all" option as the other links give them everything. -->
302                    <li class="wt-initials-list-item d-flex">
303                        <a class="wt-initial px-1<?= $show_all === 'yes' ? ' active' : '' ?>" href="<?= e($this->listUrl($tree, ['show_all' => 'yes'] + $params)) ?>"><?= I18N::translate('All') ?></a>
304                    </li>
305                <?php endif ?>
306            </ul>
307
308            <!-- Search spiders don't get an option to show/hide the surname sublists, nor does it make sense on the all/unknown/surname views -->
309            <?php if ($show !== 'none' && Session::has('initiated')) : ?>
310                <?php if ($show_marnm === 'yes') : ?>
311                    <p>
312                        <a href="<?= e($this->listUrl($tree, ['show' => $show, 'show_marnm' => 'no'] + $params)) ?>">
313                            <?= I18N::translate('Exclude individuals with “%s” as a married name', $legend) ?>
314                        </a>
315                    </p>
316                <?php else : ?>
317                    <p>
318                        <a href="<?= e($this->listUrl($tree, ['show' => $show, 'show_marnm' => 'yes'] + $params)) ?>">
319                            <?= I18N::translate('Include individuals with “%s” as a married name', $legend) ?>
320                        </a>
321                    </p>
322                <?php endif ?>
323
324                <?php if ($alpha !== '@' && $alpha !== ',' && $surname === '') : ?>
325                    <?php if ($show === 'surn') : ?>
326                        <p>
327                            <a href="<?= e($this->listUrl($tree, ['show' => 'indi'] + $params)) ?>">
328                                <?= I18N::translate('Show the list of individuals') ?>
329                            </a>
330                        </p>
331                    <?php else : ?>
332                        <p>
333                            <a href="<?= e($this->listUrl($tree, ['show' => 'surn'] + $params)) ?>">
334                                <?= I18N::translate('Show the list of surnames') ?>
335                            </a>
336                        </p>
337                    <?php endif ?>
338                <?php endif ?>
339            <?php endif ?>
340        </div>
341
342        <div class="wt-page-content">
343            <?php
344            if ($show === 'indi' || $show === 'surn') {
345                switch ($alpha) {
346                    case '@':
347                        $filter = static fn(string $x): bool => $x === Individual::NOMEN_NESCIO;
348                        break;
349                    case ',':
350                        $filter = static fn(string $x): bool => $x === '';
351                        break;
352                    case '':
353                        if ($show_all === 'yes') {
354                            $filter = static fn(string $x): bool => $x !== '' && $x !== Individual::NOMEN_NESCIO;
355                        } else {
356                            $filter = static fn(string $x): bool => $x === $surname;
357                        }
358                        break;
359                    default:
360                        if ($surname === '') {
361                            $filter = static fn(string $x): bool => I18N::language()->initialLetter($x) === $alpha;
362                        } else {
363                            $filter = static fn(string $x): bool => $x === $surname;
364                        }
365                        break;
366                }
367
368                $all_surnames = array_filter($all_surnames, $filter, ARRAY_FILTER_USE_KEY);
369
370                if ($show === 'surn') {
371                    // Show the surname list
372                    switch ($tree->getPreference('SURNAME_LIST_STYLE')) {
373                        case 'style1':
374                            echo view('lists/surnames-column-list', [
375                                'module'   => $this,
376                                'params'   => ['show' => 'indi', 'show_all' => null] + $params,
377                                'surnames' => $all_surnames,
378                                'totals'   => true,
379                                'tree'     => $tree,
380                            ]);
381                            break;
382                        case 'style3':
383                            echo view('lists/surnames-tag-cloud', [
384                                'module'   => $this,
385                                'params'   => ['show' => 'indi', 'show_all' => null] + $params,
386                                'surnames' => $all_surnames,
387                                'totals'   => true,
388                                'tree'     => $tree,
389                            ]);
390                            break;
391                        case 'style2':
392                        default:
393                            echo view('lists/surnames-table', [
394                                'families' => $this->families,
395                                'module'   => $this,
396                                'order'    => [[0, 'asc']],
397                                'params'   => ['show' => 'indi', 'show_all' => null] + $params,
398                                'surnames' => $all_surnames,
399                                'tree'     => $tree,
400                            ]);
401                            break;
402                    }
403                } else {
404                    // Show the list
405                    $count = array_sum(array_map(static fn(array $x): int => array_sum($x), $all_surnames));
406
407                    // Don't sublist short lists.
408                    if ($count < $tree->getPreference('SUBLIST_TRIGGER_I')) {
409                        $falpha = '';
410                    } else {
411                        // Break long lists by initial letter of given name
412                        $all_surnames  = array_values(array_map(static fn($x): array => array_keys($x), $all_surnames));
413                        $all_surnames  = array_merge(...$all_surnames);
414                        $givn_initials = $this->givenNameInitials($tree, $all_surnames, $show_marnm === 'yes', $this->families);
415
416                        if ($surname !== '' || $show_all === 'yes') {
417                            if ($show_all !== 'yes') {
418                                echo '<h2 class="wt-page-title">', I18N::translate('Individuals with surname %s', $legend), '</h2>';
419                            }
420                            // Don't show the list until we have some filter criteria
421                            $show = $falpha !== '' || $show_all_firstnames === 'yes' ? 'indi' : 'none';
422                            echo '<ul class="d-flex flex-wrap list-unstyled justify-content-center wt-initials-list wt-initials-list-given-names">';
423                            foreach ($givn_initials as $givn_initial => $given_count) {
424                                echo '<li class="wt-initials-list-item d-flex">';
425                                if ($given_count > 0) {
426                                    if ($show === 'indi' && $givn_initial === $falpha && $show_all_firstnames !== 'yes') {
427                                        echo '<a class="wt-initial px-1 active" href="' . e($this->listUrl($tree, ['falpha' => $givn_initial] + $params)) . '" title="' . I18N::number($given_count) . '">' . $this->displayGivenNameInitial((string) $givn_initial) . '</a>';
428                                    } else {
429                                        echo '<a class="wt-initial px-1" href="' . e($this->listUrl($tree, ['falpha' => $givn_initial] + $params)) . '" title="' . I18N::number($given_count) . '">' . $this->displayGivenNameInitial((string) $givn_initial) . '</a>';
430                                    }
431                                } else {
432                                    echo '<span class="wt-initial px-1 text-muted">' . $this->displayGivenNameInitial((string) $givn_initial) . '</span>';
433                                }
434                                echo '</li>';
435                            }
436                            // Search spiders don't get the "show all" option as the other links give them everything.
437                            if (Session::has('initiated')) {
438                                echo '<li class="wt-initials-list-item d-flex">';
439                                if ($show_all_firstnames === 'yes') {
440                                    echo '<span class="wt-initial px-1 active">' . I18N::translate('All') . '</span>';
441                                } else {
442                                    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>';
443                                }
444                                echo '</li>';
445                            }
446                            echo '</ul>';
447                        }
448                    }
449                    if ($show === 'indi') {
450                        if ($alpha === '@') {
451                            $surns_to_show = ['@N.N.'];
452                        } elseif ($alpha === ',') {
453                            $surns_to_show = [''];
454                        } elseif ($surname !== '') {
455                            $surns_to_show = $all_surns[$surname];
456                        } elseif ($alpha !== '') {
457                            $tmp = array_filter(
458                                $all_surns,
459                                static fn (string $x): bool => I18N::language()->initialLetter($x) === $alpha,
460                                ARRAY_FILTER_USE_KEY
461                            );
462
463                            $surns_to_show = array_merge(...array_values($tmp));
464                        } else {
465                            $surns_to_show = [];
466                        }
467
468                        if ($this->families) {
469                            echo view('lists/families-table', [
470                                'families' => $this->families($tree, $surns_to_show, $falpha, $show_marnm === 'yes'),
471                                'tree'     => $tree,
472                            ]);
473                        } else {
474                            echo view('lists/individuals-table', [
475                                'individuals' => $this->individuals($tree, $surns_to_show, $falpha, $show_marnm === 'yes', false),
476                                'sosa'        => false,
477                                'tree'        => $tree,
478                            ]);
479                        }
480                    }
481                }
482            } ?>
483        </div>
484        <?php
485
486        $html = ob_get_clean();
487
488        return $this->viewResponse('modules/individual-list/page', [
489            'content' => $html,
490            'title'   => $title,
491            'tree'    => $tree,
492        ]);
493    }
494
495    /**
496     * Some initial letters have a special meaning
497     *
498     * @param string $initial
499     *
500     * @return string
501     */
502    protected function displayGivenNameInitial(string $initial): string
503    {
504        if ($initial === '@') {
505            return I18N::translateContext('Unknown given name', '…');
506        }
507
508        return e($initial);
509    }
510
511    /**
512     * Some initial letters have a special meaning
513     *
514     * @param string $initial
515     *
516     * @return string
517     */
518    protected function displaySurnameInitial(string $initial): string
519    {
520        if ($initial === '@') {
521            return I18N::translateContext('Unknown surname', '…');
522        }
523
524        if ($initial === ',') {
525            return I18N::translate('No surname');
526        }
527
528        return e($initial);
529    }
530
531    /**
532     * Restrict a query to individuals that are a spouse in a family record.
533     *
534     * @param bool    $fams
535     * @param Builder $query
536     */
537    protected function whereFamily(bool $fams, Builder $query): void
538    {
539        if ($fams) {
540            $query->join('link', static function (JoinClause $join): void {
541                $join
542                    ->on('l_from', '=', 'n_id')
543                    ->on('l_file', '=', 'n_file')
544                    ->where('l_type', '=', 'FAMS');
545            });
546        }
547    }
548
549    /**
550     * Restrict a query to include/exclude married names.
551     *
552     * @param bool    $marnm
553     * @param Builder $query
554     */
555    protected function whereMarriedName(bool $marnm, Builder $query): void
556    {
557        if (!$marnm) {
558            $query->where('n_type', '<>', '_MARNM');
559        }
560    }
561
562    /**
563     * Get a count of individuals with each initial letter
564     *
565     * @param Tree          $tree
566     * @param array<string> $surns if set, only consider people with this surname
567     * @param bool          $marnm if set, include married names
568     * @param bool          $fams  if set, only consider individuals with FAMS records
569     *
570     * @return array<int>
571     */
572    public function givenNameInitials(Tree $tree, array $surns, bool $marnm, bool $fams): array
573    {
574        $initials = [];
575
576        // Ensure our own language comes before others.
577        foreach (I18N::language()->alphabet() as $initial) {
578            $initials[$initial] = 0;
579        }
580
581        $query = DB::table('name')
582            ->where('n_file', '=', $tree->id());
583
584        $this->whereFamily($fams, $query);
585        $this->whereMarriedName($marnm, $query);
586
587        if ($surns !== []) {
588            $query->whereIn('n_surn', $surns);
589        }
590
591        $query
592            ->select([$this->binaryColumn('n_givn', 'n_givn'), new Expression('COUNT(*) AS count')])
593            ->groupBy([$this->binaryColumn('n_givn')]);
594
595        foreach ($query->get() as $row) {
596            $initial            = I18N::strtoupper(I18N::language()->initialLetter($row->n_givn));
597            $initials[$initial] ??= 0;
598            $initials[$initial] += (int) $row->count;
599        }
600
601        $count_unknown = $initials['@'] ?? 0;
602
603        if ($count_unknown > 0) {
604            unset($initials['@']);
605            $initials['@'] = $count_unknown;
606        }
607
608        return $initials;
609    }
610
611    /**
612     * @param Tree $tree
613     * @param bool $marnm
614     * @param bool $fams
615     *
616     * @return array<object{n_surn:string,n_surname:string,total:int}>
617     */
618    private function surnameData(Tree $tree, bool $marnm, bool $fams): array
619    {
620        $query = DB::table('name')
621            ->where('n_file', '=', $tree->id())
622            ->whereNotNull('n_surn') // Filters old records for sources, repositories, etc.
623            ->whereNotNull('n_surname')
624            ->select([
625                $this->binaryColumn('n_surn', 'n_surn'),
626                $this->binaryColumn('n_surname', 'n_surname'),
627                new Expression('COUNT(*) AS total'),
628            ]);
629
630        $this->whereFamily($fams, $query);
631        $this->whereMarriedName($marnm, $query);
632
633        $query->groupBy([
634            $this->binaryColumn('n_surn'),
635            $this->binaryColumn('n_surname'),
636        ]);
637
638        return $query
639            ->get()
640            ->map(static fn(object $x): object => (object) ['n_surn' => $x->n_surn, 'n_surname' => $x->n_surname, 'total' => (int) $x->total])
641            ->all();
642    }
643
644    /**
645     * Group n_surn values, based on collation rules for the current language.
646     * We need them to find the individuals with this n_surn.
647     *
648     * @param array<object{n_surn:string,n_surname:string,total:int}> $surname_data
649     *
650     * @return array<array<int,string>>
651     */
652    protected function allSurns(array $surname_data): array
653    {
654        $list = [];
655
656        foreach ($surname_data as $row) {
657            $normalized = I18N::strtoupper(I18N::language()->normalize($row->n_surn));
658            $list[$normalized][] = $row->n_surn;
659        }
660
661        uksort($list, I18N::comparator());
662
663        return $list;
664    }
665
666    /**
667     * Group n_surname values, based on collation rules for each n_surn.
668     * We need them to show counts of individuals with each surname.
669     *
670     * @param array<object{n_surn:string,n_surname:string,total:int}> $surname_data
671     *
672     * @return array<array<int>>
673     */
674    protected function allSurnames(array $surname_data): array
675    {
676        $list = [];
677
678        foreach ($surname_data as $row) {
679            $n_surn = $row->n_surn === '' ? $row->n_surname : $row->n_surn;
680            $n_surn = I18N::strtoupper(I18N::language()->normalize($n_surn));
681
682            $list[$n_surn][$row->n_surname] ??= 0;
683            $list[$n_surn][$row->n_surname] += $row->total;
684        }
685
686        uksort($list, I18N::comparator());
687
688        return $list;
689    }
690
691    /**
692     * Extract initial letters and counts for all surnames.
693     *
694     * @param array<object{n_surn:string,n_surname:string,total:int}> $surname_data
695     *
696     * @return array<int>
697     */
698    protected function surnameInitials(array $surname_data): array
699    {
700        $initials = [];
701
702        // Ensure our own language comes before others.
703        foreach (I18N::language()->alphabet() as $initial) {
704            $initials[$initial] = 0;
705        }
706
707        foreach ($surname_data as $row) {
708            $initial = I18N::language()->initialLetter(I18N::strtoupper($row->n_surn));
709            $initial = I18N::language()->normalize($initial);
710
711            $initials[$initial] ??= 0;
712            $initials[$initial] += $row->total;
713        }
714
715        // Move specials to the end
716        $count_none = $initials[''] ?? 0;
717
718        if ($count_none > 0) {
719            unset($initials['']);
720            $initials[','] = $count_none;
721        }
722
723        $count_unknown = $initials['@'] ?? 0;
724
725        if ($count_unknown > 0) {
726            unset($initials['@']);
727            $initials['@'] = $count_unknown;
728        }
729
730        return $initials;
731    }
732
733    /**
734     * Fetch a list of individuals with specified names
735     * To search for unknown names, use $surn="@N.N.", $salpha="@" or $galpha="@"
736     * To search for names with no surnames, use $salpha=","
737     *
738     * @param Tree          $tree
739     * @param array<string> $surns_to_show if set, only fetch people with this n_surn
740     * @param string        $galpha        if set, only fetch given names starting with this letter
741     * @param bool          $marnm         if set, include married names
742     * @param bool          $fams          if set, only fetch individuals with FAMS records
743     *
744     * @return Collection<int,Individual>
745     */
746    protected function individuals(Tree $tree, array $surns_to_show, string $galpha, bool $marnm, bool $fams): Collection
747    {
748        $query = DB::table('individuals')
749            ->join('name', static function (JoinClause $join): void {
750                $join
751                    ->on('n_id', '=', 'i_id')
752                    ->on('n_file', '=', 'i_file');
753            })
754            ->where('i_file', '=', $tree->id())
755            ->select(['i_id AS xref', 'i_gedcom AS gedcom', 'n_givn', 'n_surn']);
756
757        $this->whereFamily($fams, $query);
758        $this->whereMarriedName($marnm, $query);
759
760        if ($surns_to_show === []) {
761            $query->whereNotIn('n_surn', ['', '@N.N.']);
762        } else {
763            $query->whereIn($this->binaryColumn('n_surn'), $surns_to_show);
764        }
765
766        $individuals = new Collection();
767
768        foreach ($query->get() as $row) {
769            $individual = Registry::individualFactory()->make($row->xref, $tree, $row->gedcom);
770            assert($individual instanceof Individual);
771
772            // The name from the database may be private - check the filtered list...
773            foreach ($individual->getAllNames() as $n => $name) {
774                if ($name['givn'] === $row->n_givn && $name['surn'] === $row->n_surn) {
775                    if ($galpha === '' || I18N::strtoupper(I18N::language()->initialLetter($row->n_givn)) === $galpha) {
776                        $individual->setPrimaryName($n);
777                        // We need to clone $individual, as we may have multiple references to the
778                        // same individual in this list, and the "primary name" would otherwise
779                        // be shared amongst all of them.
780                        $individuals->push(clone $individual);
781                        break;
782                    }
783                }
784            }
785        }
786
787        return $individuals;
788    }
789
790    /**
791     * Fetch a list of families with specified names
792     * To search for unknown names, use $surn="@N.N.", $salpha="@" or $galpha="@"
793     * To search for names with no surnames, use $salpha=","
794     *
795     * @param Tree          $tree
796     * @param array<string> $surnames if set, only fetch people with this n_surname
797     * @param string        $galpha   if set, only fetch given names starting with this letter
798     * @param bool          $marnm    if set, include married names
799     *
800     * @return Collection<int,Family>
801     */
802    protected function families(Tree $tree, array $surnames, string $galpha, bool $marnm): Collection
803    {
804        $families = new Collection();
805
806        foreach ($this->individuals($tree, $surnames, $galpha, $marnm, true) as $indi) {
807            foreach ($indi->spouseFamilies() as $family) {
808                $families->push($family);
809            }
810        }
811
812        return $families->unique();
813    }
814
815    /**
816     * This module assumes the database will use binary collation on the name columns.
817     * Until we convert MySQL databases to use utf8_bin, we need to do this at run-time.
818     *
819     * @param string      $column
820     * @param string|null $alias
821     *
822     * @return Expression
823     */
824    private function binaryColumn(string $column, string $alias = null): Expression
825    {
826        if (DB::connection()->getDriverName() === 'mysql') {
827            $sql = 'CAST(' . $column . ' AS binary)';
828        } else {
829            $sql = $column;
830        }
831
832        if ($alias !== null) {
833            $sql .= ' AS ' . $alias;
834        }
835
836        return new Expression($sql);
837    }
838}
839