Passed
Push — develop ( 8b59ed...6cf45e )
by Greg
07:13
created

IndividualListModule::individuals()   B

Complexity

Conditions 8
Paths 10

Size

Total Lines 49
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

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