xref: /webtrees/app/Services/SearchService.php (revision d78d61f772a114484f08a67ef32ea95ad658d79e)
132cd2800SGreg Roach<?php
23976b470SGreg Roach
332cd2800SGreg Roach/**
432cd2800SGreg Roach * webtrees: online genealogy
532cd2800SGreg Roach * Copyright (C) 2019 webtrees development team
632cd2800SGreg Roach * This program is free software: you can redistribute it and/or modify
732cd2800SGreg Roach * it under the terms of the GNU General Public License as published by
832cd2800SGreg Roach * the Free Software Foundation, either version 3 of the License, or
932cd2800SGreg Roach * (at your option) any later version.
1032cd2800SGreg Roach * This program is distributed in the hope that it will be useful,
1132cd2800SGreg Roach * but WITHOUT ANY WARRANTY; without even the implied warranty of
1232cd2800SGreg Roach * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1332cd2800SGreg Roach * GNU General Public License for more details.
1432cd2800SGreg Roach * You should have received a copy of the GNU General Public License
1532cd2800SGreg Roach * along with this program. If not, see <http://www.gnu.org/licenses/>.
1632cd2800SGreg Roach */
17fcfa147eSGreg Roach
1832cd2800SGreg Roachdeclare(strict_types=1);
1932cd2800SGreg Roach
2032cd2800SGreg Roachnamespace Fisharebest\Webtrees\Services;
2132cd2800SGreg Roach
2232cd2800SGreg Roachuse Closure;
23dfb2cda2SGreg Roachuse Fisharebest\Webtrees\Date;
24d501c45dSGreg Roachuse Fisharebest\Webtrees\Exceptions\HttpServiceUnavailableException;
2532cd2800SGreg Roachuse Fisharebest\Webtrees\Family;
26a7a24840SGreg Roachuse Fisharebest\Webtrees\Gedcom;
2732cd2800SGreg Roachuse Fisharebest\Webtrees\GedcomRecord;
2852a8ef61SGreg Roachuse Fisharebest\Webtrees\I18N;
2932cd2800SGreg Roachuse Fisharebest\Webtrees\Individual;
3032cd2800SGreg Roachuse Fisharebest\Webtrees\Media;
3132cd2800SGreg Roachuse Fisharebest\Webtrees\Note;
32b68caec6SGreg Roachuse Fisharebest\Webtrees\Place;
3332cd2800SGreg Roachuse Fisharebest\Webtrees\Repository;
342d686e68SGreg Roachuse Fisharebest\Webtrees\Soundex;
3532cd2800SGreg Roachuse Fisharebest\Webtrees\Source;
3632cd2800SGreg Roachuse Fisharebest\Webtrees\Tree;
3732cd2800SGreg Roachuse Illuminate\Database\Capsule\Manager as DB;
3832cd2800SGreg Roachuse Illuminate\Database\Query\Builder;
39a7a24840SGreg Roachuse Illuminate\Database\Query\Expression;
4032cd2800SGreg Roachuse Illuminate\Database\Query\JoinClause;
4132cd2800SGreg Roachuse Illuminate\Support\Collection;
4232cd2800SGreg Roachuse stdClass;
433976b470SGreg Roach
44a7a24840SGreg Roachuse function mb_stripos;
4532cd2800SGreg Roach
4632cd2800SGreg Roach/**
4732cd2800SGreg Roach * Search trees for genealogy records.
4832cd2800SGreg Roach */
4932cd2800SGreg Roachclass SearchService
5032cd2800SGreg Roach{
51d5ad3db0SGreg Roach    /** @var TreeService */
52d5ad3db0SGreg Roach    private $tree_service;
53d5ad3db0SGreg Roach
54d5ad3db0SGreg Roach    /**
55d5ad3db0SGreg Roach     * SearchService constructor.
56d5ad3db0SGreg Roach     *
57d5ad3db0SGreg Roach     * @param TreeService $tree_service
58d5ad3db0SGreg Roach     */
59d5ad3db0SGreg Roach    public function __construct(TreeService $tree_service)
60d5ad3db0SGreg Roach    {
61d5ad3db0SGreg Roach        $this->tree_service = $tree_service;
62d5ad3db0SGreg Roach    }
63d5ad3db0SGreg Roach
64a7a24840SGreg Roach    /**
65a7a24840SGreg Roach     * @param Tree[]   $trees
66a7a24840SGreg Roach     * @param string[] $search
67a7a24840SGreg Roach     *
6854c7f8dfSGreg Roach     * @return Collection
69a7a24840SGreg Roach     */
70a7a24840SGreg Roach    public function searchFamilies(array $trees, array $search): Collection
71a7a24840SGreg Roach    {
72a7a24840SGreg Roach        $query = DB::table('families');
73a7a24840SGreg Roach
74a7a24840SGreg Roach        $this->whereTrees($query, 'f_file', $trees);
75a7a24840SGreg Roach        $this->whereSearch($query, 'f_gedcom', $search);
76a7a24840SGreg Roach
77a7a24840SGreg Roach        return $query
78a7a24840SGreg Roach            ->get()
7952a8ef61SGreg Roach            ->each($this->rowLimiter())
80d5ad3db0SGreg Roach            ->map($this->familyRowMapper())
81a7a24840SGreg Roach            ->filter(GedcomRecord::accessFilter())
827f5fa3c2SGreg Roach            ->filter($this->rawGedcomFilter($search));
83a7a24840SGreg Roach    }
84a7a24840SGreg Roach
8532cd2800SGreg Roach    /**
8632cd2800SGreg Roach     * Search for families by name.
8732cd2800SGreg Roach     *
88a7a24840SGreg Roach     * @param Tree[]   $trees
89a7a24840SGreg Roach     * @param string[] $search
9032cd2800SGreg Roach     * @param int      $offset
9132cd2800SGreg Roach     * @param int      $limit
9232cd2800SGreg Roach     *
9354c7f8dfSGreg Roach     * @return Collection
9432cd2800SGreg Roach     */
95a7a24840SGreg Roach    public function searchFamilyNames(array $trees, array $search, int $offset = 0, int $limit = PHP_INT_MAX): Collection
9632cd2800SGreg Roach    {
9732cd2800SGreg Roach        $query = DB::table('families')
98ac499332SGreg Roach            ->leftJoin('name AS husb_name', static function (JoinClause $join): void {
9932cd2800SGreg Roach                $join
10032cd2800SGreg Roach                    ->on('husb_name.n_file', '=', 'families.f_file')
101ac499332SGreg Roach                    ->on('husb_name.n_id', '=', 'families.f_husb')
102ac499332SGreg Roach                    ->where('husb_name.n_type', '<>', '_MARNM');
10332cd2800SGreg Roach            })
104ac499332SGreg Roach            ->leftJoin('name AS wife_name', static function (JoinClause $join): void {
10532cd2800SGreg Roach                $join
10632cd2800SGreg Roach                    ->on('wife_name.n_file', '=', 'families.f_file')
107ac499332SGreg Roach                    ->on('wife_name.n_id', '=', 'families.f_wife')
108ac499332SGreg Roach                    ->where('wife_name.n_type', '<>', '_MARNM');
109ac499332SGreg Roach            });
110a7a24840SGreg Roach
111a7a24840SGreg Roach        $prefix = DB::connection()->getTablePrefix();
112a69f5655SGreg Roach        $field  = new Expression('COALESCE(' . $prefix . "husb_name.n_full, '') || COALESCE(" . $prefix . "wife_name.n_full, '')");
113a7a24840SGreg Roach
114a7a24840SGreg Roach        $this->whereTrees($query, 'f_file', $trees);
115a7a24840SGreg Roach        $this->whereSearch($query, $field, $search);
116a7a24840SGreg Roach
117a7a24840SGreg Roach        $query
11832cd2800SGreg Roach            ->orderBy('husb_name.n_sort')
11932cd2800SGreg Roach            ->orderBy('wife_name.n_sort')
120c0804649SGreg Roach            ->select(['families.*', 'husb_name.n_sort', 'wife_name.n_sort'])
12132cd2800SGreg Roach            ->distinct();
12232cd2800SGreg Roach
123d5ad3db0SGreg Roach        return $this->paginateQuery($query, $this->familyRowMapper(), GedcomRecord::accessFilter(), $offset, $limit);
124a7a24840SGreg Roach    }
125a7a24840SGreg Roach
126a7a24840SGreg Roach    /**
127a7a24840SGreg Roach     * @param Tree[]   $trees
128a7a24840SGreg Roach     * @param string[] $search
129a7a24840SGreg Roach     *
13054c7f8dfSGreg Roach     * @return Collection
131a7a24840SGreg Roach     */
132a7a24840SGreg Roach    public function searchIndividuals(array $trees, array $search): Collection
133a7a24840SGreg Roach    {
134a7a24840SGreg Roach        $query = DB::table('individuals');
135a7a24840SGreg Roach
136a7a24840SGreg Roach        $this->whereTrees($query, 'i_file', $trees);
137a7a24840SGreg Roach        $this->whereSearch($query, 'i_gedcom', $search);
138a7a24840SGreg Roach
139a7a24840SGreg Roach        return $query
140a7a24840SGreg Roach            ->get()
14152a8ef61SGreg Roach            ->each($this->rowLimiter())
142d5ad3db0SGreg Roach            ->map($this->individualRowMapper())
143a7a24840SGreg Roach            ->filter(GedcomRecord::accessFilter())
1447f5fa3c2SGreg Roach            ->filter($this->rawGedcomFilter($search));
14532cd2800SGreg Roach    }
14632cd2800SGreg Roach
14732cd2800SGreg Roach    /**
14832cd2800SGreg Roach     * Search for individuals by name.
14932cd2800SGreg Roach     *
150a7a24840SGreg Roach     * @param Tree[]   $trees
151a7a24840SGreg Roach     * @param string[] $search
15232cd2800SGreg Roach     * @param int      $offset
15332cd2800SGreg Roach     * @param int      $limit
15432cd2800SGreg Roach     *
15554c7f8dfSGreg Roach     * @return Collection
15632cd2800SGreg Roach     */
157a7a24840SGreg Roach    public function searchIndividualNames(array $trees, array $search, int $offset = 0, int $limit = PHP_INT_MAX): Collection
15832cd2800SGreg Roach    {
15932cd2800SGreg Roach        $query = DB::table('individuals')
1600b5fd0a6SGreg Roach            ->join('name', static function (JoinClause $join): void {
16132cd2800SGreg Roach                $join
16232cd2800SGreg Roach                    ->on('name.n_file', '=', 'individuals.i_file')
163a7a24840SGreg Roach                    ->on('name.n_id', '=', 'individuals.i_id');
16432cd2800SGreg Roach            })
165e84cf2deSGreg Roach            ->orderBy('n_sort')
166*d78d61f7SGreg Roach            ->distinct()
167*d78d61f7SGreg Roach            ->select(['individuals.*']);
16832cd2800SGreg Roach
169a7a24840SGreg Roach        $this->whereTrees($query, 'i_file', $trees);
170a7a24840SGreg Roach        $this->whereSearch($query, 'n_full', $search);
171a7a24840SGreg Roach
172d5ad3db0SGreg Roach        return $this->paginateQuery($query, $this->individualRowMapper(), GedcomRecord::accessFilter(), $offset, $limit);
17332cd2800SGreg Roach    }
17432cd2800SGreg Roach
17532cd2800SGreg Roach    /**
17632cd2800SGreg Roach     * Search for media objects.
17732cd2800SGreg Roach     *
178a7a24840SGreg Roach     * @param Tree[]   $trees
179a7a24840SGreg Roach     * @param string[] $search
18032cd2800SGreg Roach     * @param int      $offset
18132cd2800SGreg Roach     * @param int      $limit
18232cd2800SGreg Roach     *
18354c7f8dfSGreg Roach     * @return Collection
18432cd2800SGreg Roach     */
185a7a24840SGreg Roach    public function searchMedia(array $trees, array $search, int $offset = 0, int $limit = PHP_INT_MAX): Collection
18632cd2800SGreg Roach    {
187a7a24840SGreg Roach        $query = DB::table('media');
18832cd2800SGreg Roach
189a7a24840SGreg Roach        $this->whereTrees($query, 'media.m_file', $trees);
190a7a24840SGreg Roach        $this->whereSearch($query, 'm_gedcom', $search);
191a7a24840SGreg Roach
192d5ad3db0SGreg Roach        return $this->paginateQuery($query, $this->mediaRowMapper(), GedcomRecord::accessFilter(), $offset, $limit);
19332cd2800SGreg Roach    }
19432cd2800SGreg Roach
19532cd2800SGreg Roach    /**
19632cd2800SGreg Roach     * Search for notes.
19732cd2800SGreg Roach     *
198a7a24840SGreg Roach     * @param Tree[]   $trees
199a7a24840SGreg Roach     * @param string[] $search
20032cd2800SGreg Roach     * @param int      $offset
20132cd2800SGreg Roach     * @param int      $limit
20232cd2800SGreg Roach     *
20354c7f8dfSGreg Roach     * @return Collection
20432cd2800SGreg Roach     */
205a7a24840SGreg Roach    public function searchNotes(array $trees, array $search, int $offset = 0, int $limit = PHP_INT_MAX): Collection
20632cd2800SGreg Roach    {
20732cd2800SGreg Roach        $query = DB::table('other')
208a7a24840SGreg Roach            ->where('o_type', '=', 'NOTE');
20932cd2800SGreg Roach
210a7a24840SGreg Roach        $this->whereTrees($query, 'o_file', $trees);
211a7a24840SGreg Roach        $this->whereSearch($query, 'o_gedcom', $search);
212a7a24840SGreg Roach
213d5ad3db0SGreg Roach        return $this->paginateQuery($query, $this->noteRowMapper(), GedcomRecord::accessFilter(), $offset, $limit);
21432cd2800SGreg Roach    }
21532cd2800SGreg Roach
21632cd2800SGreg Roach    /**
21732cd2800SGreg Roach     * Search for repositories.
21832cd2800SGreg Roach     *
219a7a24840SGreg Roach     * @param Tree[]   $trees
220a7a24840SGreg Roach     * @param string[] $search
22132cd2800SGreg Roach     * @param int      $offset
22232cd2800SGreg Roach     * @param int      $limit
22332cd2800SGreg Roach     *
22454c7f8dfSGreg Roach     * @return Collection
22532cd2800SGreg Roach     */
226a7a24840SGreg Roach    public function searchRepositories(array $trees, array $search, int $offset = 0, int $limit = PHP_INT_MAX): Collection
22732cd2800SGreg Roach    {
22832cd2800SGreg Roach        $query = DB::table('other')
229a7a24840SGreg Roach            ->where('o_type', '=', 'REPO');
23032cd2800SGreg Roach
231a7a24840SGreg Roach        $this->whereTrees($query, 'o_file', $trees);
232a7a24840SGreg Roach        $this->whereSearch($query, 'o_gedcom', $search);
233a7a24840SGreg Roach
234d5ad3db0SGreg Roach        return $this->paginateQuery($query, $this->repositoryRowMapper(), GedcomRecord::accessFilter(), $offset, $limit);
23532cd2800SGreg Roach    }
23632cd2800SGreg Roach
23732cd2800SGreg Roach    /**
238a7a24840SGreg Roach     * Search for sources.
23932cd2800SGreg Roach     *
240a7a24840SGreg Roach     * @param Tree[]   $trees
241a7a24840SGreg Roach     * @param string[] $search
24232cd2800SGreg Roach     * @param int      $offset
24332cd2800SGreg Roach     * @param int      $limit
24432cd2800SGreg Roach     *
24554c7f8dfSGreg Roach     * @return Collection
24632cd2800SGreg Roach     */
247a7a24840SGreg Roach    public function searchSources(array $trees, array $search, int $offset = 0, int $limit = PHP_INT_MAX): Collection
248a7a24840SGreg Roach    {
249a7a24840SGreg Roach        $query = DB::table('sources');
250a7a24840SGreg Roach
251a7a24840SGreg Roach        $this->whereTrees($query, 's_file', $trees);
252a7a24840SGreg Roach        $this->whereSearch($query, 's_gedcom', $search);
253a7a24840SGreg Roach
254d5ad3db0SGreg Roach        return $this->paginateQuery($query, $this->sourceRowMapper(), GedcomRecord::accessFilter(), $offset, $limit);
255a7a24840SGreg Roach    }
256a7a24840SGreg Roach
257a7a24840SGreg Roach    /**
258a7a24840SGreg Roach     * Search for sources by name.
259a7a24840SGreg Roach     *
260a7a24840SGreg Roach     * @param Tree[]   $trees
261a7a24840SGreg Roach     * @param string[] $search
262a7a24840SGreg Roach     * @param int      $offset
263a7a24840SGreg Roach     * @param int      $limit
264a7a24840SGreg Roach     *
26554c7f8dfSGreg Roach     * @return Collection
266a7a24840SGreg Roach     */
267a7a24840SGreg Roach    public function searchSourcesByName(array $trees, array $search, int $offset = 0, int $limit = PHP_INT_MAX): Collection
26832cd2800SGreg Roach    {
26932cd2800SGreg Roach        $query = DB::table('sources')
270c0804649SGreg Roach            ->orderBy('s_name');
27132cd2800SGreg Roach
272a7a24840SGreg Roach        $this->whereTrees($query, 's_file', $trees);
273a7a24840SGreg Roach        $this->whereSearch($query, 's_name', $search);
274a7a24840SGreg Roach
275d5ad3db0SGreg Roach        return $this->paginateQuery($query, $this->sourceRowMapper(), GedcomRecord::accessFilter(), $offset, $limit);
27632cd2800SGreg Roach    }
27732cd2800SGreg Roach
27832cd2800SGreg Roach    /**
27932cd2800SGreg Roach     * Search for submitters.
28032cd2800SGreg Roach     *
281a7a24840SGreg Roach     * @param Tree[]   $trees
282a7a24840SGreg Roach     * @param string[] $search
28332cd2800SGreg Roach     * @param int      $offset
28432cd2800SGreg Roach     * @param int      $limit
28532cd2800SGreg Roach     *
28654c7f8dfSGreg Roach     * @return Collection
28732cd2800SGreg Roach     */
288a7a24840SGreg Roach    public function searchSubmitters(array $trees, array $search, int $offset = 0, int $limit = PHP_INT_MAX): Collection
28932cd2800SGreg Roach    {
29032cd2800SGreg Roach        $query = DB::table('other')
291a7a24840SGreg Roach            ->where('o_type', '=', 'SUBM');
29232cd2800SGreg Roach
293a7a24840SGreg Roach        $this->whereTrees($query, 'o_file', $trees);
294a7a24840SGreg Roach        $this->whereSearch($query, 'o_gedcom', $search);
295a7a24840SGreg Roach
296d5ad3db0SGreg Roach        return $this->paginateQuery($query, $this->submitterRowMapper(), GedcomRecord::accessFilter(), $offset, $limit);
29732cd2800SGreg Roach    }
29832cd2800SGreg Roach
29932cd2800SGreg Roach    /**
300b68caec6SGreg Roach     * Search for places.
301b68caec6SGreg Roach     *
302b68caec6SGreg Roach     * @param Tree   $tree
303b68caec6SGreg Roach     * @param string $search
304b68caec6SGreg Roach     * @param int    $offset
305b68caec6SGreg Roach     * @param int    $limit
306b68caec6SGreg Roach     *
30754c7f8dfSGreg Roach     * @return Collection
308b68caec6SGreg Roach     */
309b68caec6SGreg Roach    public function searchPlaces(Tree $tree, string $search, int $offset = 0, int $limit = PHP_INT_MAX): Collection
310b68caec6SGreg Roach    {
311b68caec6SGreg Roach        $query = DB::table('places AS p0')
312b68caec6SGreg Roach            ->where('p0.p_file', '=', $tree->id())
313b68caec6SGreg Roach            ->leftJoin('places AS p1', 'p1.p_id', '=', 'p0.p_parent_id')
314b68caec6SGreg Roach            ->leftJoin('places AS p2', 'p2.p_id', '=', 'p1.p_parent_id')
315b68caec6SGreg Roach            ->leftJoin('places AS p3', 'p3.p_id', '=', 'p2.p_parent_id')
316b68caec6SGreg Roach            ->leftJoin('places AS p4', 'p4.p_id', '=', 'p3.p_parent_id')
317b68caec6SGreg Roach            ->leftJoin('places AS p5', 'p5.p_id', '=', 'p4.p_parent_id')
318b68caec6SGreg Roach            ->leftJoin('places AS p6', 'p6.p_id', '=', 'p5.p_parent_id')
319b68caec6SGreg Roach            ->leftJoin('places AS p7', 'p7.p_id', '=', 'p6.p_parent_id')
320b68caec6SGreg Roach            ->leftJoin('places AS p8', 'p8.p_id', '=', 'p7.p_parent_id')
321b68caec6SGreg Roach            ->orderBy('p0.p_place')
322b68caec6SGreg Roach            ->orderBy('p1.p_place')
323b68caec6SGreg Roach            ->orderBy('p2.p_place')
324b68caec6SGreg Roach            ->orderBy('p3.p_place')
325b68caec6SGreg Roach            ->orderBy('p4.p_place')
326b68caec6SGreg Roach            ->orderBy('p5.p_place')
327b68caec6SGreg Roach            ->orderBy('p6.p_place')
328b68caec6SGreg Roach            ->orderBy('p7.p_place')
329b68caec6SGreg Roach            ->orderBy('p8.p_place')
330b68caec6SGreg Roach            ->select([
331b68caec6SGreg Roach                'p0.p_place AS place0',
332b68caec6SGreg Roach                'p1.p_place AS place1',
333b68caec6SGreg Roach                'p2.p_place AS place2',
334b68caec6SGreg Roach                'p3.p_place AS place3',
335b68caec6SGreg Roach                'p4.p_place AS place4',
336b68caec6SGreg Roach                'p5.p_place AS place5',
337b68caec6SGreg Roach                'p6.p_place AS place6',
338b68caec6SGreg Roach                'p7.p_place AS place7',
339b68caec6SGreg Roach                'p8.p_place AS place8',
340b68caec6SGreg Roach            ]);
341b68caec6SGreg Roach
342b68caec6SGreg Roach        // Filter each level of the hierarchy.
343b68caec6SGreg Roach        foreach (explode(',', $search, 9) as $level => $string) {
344b68caec6SGreg Roach            $query->whereContains('p' . $level . '.p_place', $string);
345b68caec6SGreg Roach        }
346b68caec6SGreg Roach
3476c2179e2SGreg Roach        $row_mapper = static function (stdClass $row) use ($tree): Place {
348b68caec6SGreg Roach            $place = implode(', ', array_filter((array) $row));
349b68caec6SGreg Roach
350b68caec6SGreg Roach            return new Place($place, $tree);
351b68caec6SGreg Roach        };
352b68caec6SGreg Roach
3536c2179e2SGreg Roach        $filter = static function (): bool {
354a7a24840SGreg Roach            return true;
355a7a24840SGreg Roach        };
356b68caec6SGreg Roach
357a7a24840SGreg Roach        return $this->paginateQuery($query, $row_mapper, $filter, $offset, $limit);
358a7a24840SGreg Roach    }
359b68caec6SGreg Roach
360b68caec6SGreg Roach    /**
361a5dbc5b2SGreg Roach     * @param Tree[]   $trees
362dfb2cda2SGreg Roach     * @param string[] $fields
363dfb2cda2SGreg Roach     * @param string[] $modifiers
364dfb2cda2SGreg Roach     *
36554c7f8dfSGreg Roach     * @return Collection
366dfb2cda2SGreg Roach     */
367dfb2cda2SGreg Roach    public function searchIndividualsAdvanced(array $trees, array $fields, array $modifiers): Collection
368dfb2cda2SGreg Roach    {
369dfb2cda2SGreg Roach        $fields = array_filter($fields);
370dfb2cda2SGreg Roach
371dfb2cda2SGreg Roach        $query = DB::table('individuals')
372dfb2cda2SGreg Roach            ->select(['individuals.*'])
373dfb2cda2SGreg Roach            ->distinct();
374dfb2cda2SGreg Roach
375dfb2cda2SGreg Roach        $this->whereTrees($query, 'i_file', $trees);
376dfb2cda2SGreg Roach
377dfb2cda2SGreg Roach        // Join the following tables
378dfb2cda2SGreg Roach        $father_name   = false;
379dfb2cda2SGreg Roach        $mother_name   = false;
380dfb2cda2SGreg Roach        $spouse_family = false;
381dfb2cda2SGreg Roach        $indi_name     = false;
382dfb2cda2SGreg Roach        $indi_date     = false;
383dfb2cda2SGreg Roach        $fam_date      = false;
384dfb2cda2SGreg Roach        $indi_plac     = false;
385dfb2cda2SGreg Roach        $fam_plac      = false;
386dfb2cda2SGreg Roach
387dfb2cda2SGreg Roach        foreach ($fields as $field_name => $field_value) {
388dfb2cda2SGreg Roach            if ($field_value !== '') {
389dfb2cda2SGreg Roach                if (substr($field_name, 0, 14) === 'FAMC:HUSB:NAME') {
390dfb2cda2SGreg Roach                    $father_name = true;
391dfb2cda2SGreg Roach                } elseif (substr($field_name, 0, 14) === 'FAMC:WIFE:NAME') {
392dfb2cda2SGreg Roach                    $mother_name = true;
393dfb2cda2SGreg Roach                } elseif (substr($field_name, 0, 4) === 'NAME') {
394dfb2cda2SGreg Roach                    $indi_name = true;
395dfb2cda2SGreg Roach                } elseif (strpos($field_name, ':DATE') !== false) {
396dfb2cda2SGreg Roach                    if (substr($field_name, 0, 4) === 'FAMS') {
397dfb2cda2SGreg Roach                        $fam_date      = true;
398dfb2cda2SGreg Roach                        $spouse_family = true;
399dfb2cda2SGreg Roach                    } else {
400dfb2cda2SGreg Roach                        $indi_date = true;
401dfb2cda2SGreg Roach                    }
402dfb2cda2SGreg Roach                } elseif (strpos($field_name, ':PLAC') !== false) {
403dfb2cda2SGreg Roach                    if (substr($field_name, 0, 4) === 'FAMS') {
404dfb2cda2SGreg Roach                        $fam_plac      = true;
405dfb2cda2SGreg Roach                        $spouse_family = true;
406dfb2cda2SGreg Roach                    } else {
407dfb2cda2SGreg Roach                        $indi_plac = true;
408dfb2cda2SGreg Roach                    }
409dfb2cda2SGreg Roach                } elseif ($field_name === 'FAMS:NOTE') {
410dfb2cda2SGreg Roach                    $spouse_family = true;
411dfb2cda2SGreg Roach                }
412dfb2cda2SGreg Roach            }
413dfb2cda2SGreg Roach        }
414dfb2cda2SGreg Roach
415dfb2cda2SGreg Roach        if ($father_name || $mother_name) {
4160b5fd0a6SGreg Roach            $query->join('link AS l1', static function (JoinClause $join): void {
417dfb2cda2SGreg Roach                $join
418dfb2cda2SGreg Roach                    ->on('l1.l_file', '=', 'individuals.i_file')
419dfb2cda2SGreg Roach                    ->on('l1.l_from', '=', 'individuals.i_id')
420dfb2cda2SGreg Roach                    ->where('l1.l_type', '=', 'FAMC');
421dfb2cda2SGreg Roach            });
422dfb2cda2SGreg Roach
423dfb2cda2SGreg Roach            if ($father_name) {
4240b5fd0a6SGreg Roach                $query->join('link AS l2', static function (JoinClause $join): void {
425dfb2cda2SGreg Roach                    $join
426dfb2cda2SGreg Roach                        ->on('l2.l_file', '=', 'l1.l_file')
427dfb2cda2SGreg Roach                        ->on('l2.l_from', '=', 'l1.l_to')
428dfb2cda2SGreg Roach                        ->where('l2.l_type', '=', 'HUSB');
429dfb2cda2SGreg Roach                });
4300b5fd0a6SGreg Roach                $query->join('name AS father_name', static function (JoinClause $join): void {
431dfb2cda2SGreg Roach                    $join
432dfb2cda2SGreg Roach                        ->on('father_name.n_file', '=', 'l2.l_file')
433dfb2cda2SGreg Roach                        ->on('father_name.n_id', '=', 'l2.l_to');
434dfb2cda2SGreg Roach                });
435dfb2cda2SGreg Roach            }
436dfb2cda2SGreg Roach
437dfb2cda2SGreg Roach            if ($mother_name) {
4380b5fd0a6SGreg Roach                $query->join('link AS l3', static function (JoinClause $join): void {
439dfb2cda2SGreg Roach                    $join
440dfb2cda2SGreg Roach                        ->on('l3.l_file', '=', 'l1.l_file')
441dfb2cda2SGreg Roach                        ->on('l3.l_from', '=', 'l1.l_to')
442dfb2cda2SGreg Roach                        ->where('l3.l_type', '=', 'WIFE');
443dfb2cda2SGreg Roach                });
4440b5fd0a6SGreg Roach                $query->join('name AS mother_name', static function (JoinClause $join): void {
445dfb2cda2SGreg Roach                    $join
446dfb2cda2SGreg Roach                        ->on('mother_name.n_file', '=', 'l3.l_file')
447dfb2cda2SGreg Roach                        ->on('mother_name.n_id', '=', 'l3.l_to');
448dfb2cda2SGreg Roach                });
449dfb2cda2SGreg Roach            }
450dfb2cda2SGreg Roach        }
451dfb2cda2SGreg Roach
452dfb2cda2SGreg Roach        if ($spouse_family) {
4530b5fd0a6SGreg Roach            $query->join('link AS l4', static function (JoinClause $join): void {
454dfb2cda2SGreg Roach                $join
455dfb2cda2SGreg Roach                    ->on('l4.l_file', '=', 'individuals.i_file')
456dfb2cda2SGreg Roach                    ->on('l4.l_from', '=', 'individuals.i_id')
457dfb2cda2SGreg Roach                    ->where('l4.l_type', '=', 'FAMS');
458dfb2cda2SGreg Roach            });
4590b5fd0a6SGreg Roach            $query->join('families AS spouse_families', static function (JoinClause $join): void {
460dfb2cda2SGreg Roach                $join
461dfb2cda2SGreg Roach                    ->on('spouse_families.f_file', '=', 'l4.l_file')
462dfb2cda2SGreg Roach                    ->on('spouse_families.f_id', '=', 'l4.l_to');
463dfb2cda2SGreg Roach            });
464dfb2cda2SGreg Roach        }
465dfb2cda2SGreg Roach
466dfb2cda2SGreg Roach        if ($indi_name) {
4670b5fd0a6SGreg Roach            $query->join('name AS individual_name', static function (JoinClause $join): void {
468dfb2cda2SGreg Roach                $join
469dfb2cda2SGreg Roach                    ->on('individual_name.n_file', '=', 'individuals.i_file')
470dfb2cda2SGreg Roach                    ->on('individual_name.n_id', '=', 'individuals.i_id');
471dfb2cda2SGreg Roach            });
472dfb2cda2SGreg Roach        }
473dfb2cda2SGreg Roach
474dfb2cda2SGreg Roach        if ($indi_date) {
4750b5fd0a6SGreg Roach            $query->join('dates AS individual_dates', static function (JoinClause $join): void {
476dfb2cda2SGreg Roach                $join
477dfb2cda2SGreg Roach                    ->on('individual_dates.d_file', '=', 'individuals.i_file')
478dfb2cda2SGreg Roach                    ->on('individual_dates.d_gid', '=', 'individuals.i_id');
479dfb2cda2SGreg Roach            });
480dfb2cda2SGreg Roach        }
481dfb2cda2SGreg Roach
482dfb2cda2SGreg Roach        if ($fam_date) {
4830b5fd0a6SGreg Roach            $query->join('dates AS family_dates', static function (JoinClause $join): void {
484dfb2cda2SGreg Roach                $join
485dfb2cda2SGreg Roach                    ->on('family_dates.d_file', '=', 'spouse_families.f_file')
486dfb2cda2SGreg Roach                    ->on('family_dates.d_gid', '=', 'spouse_families.f_id');
487dfb2cda2SGreg Roach            });
488dfb2cda2SGreg Roach        }
489dfb2cda2SGreg Roach
490dfb2cda2SGreg Roach        if ($indi_plac) {
4910b5fd0a6SGreg Roach            $query->join('placelinks AS individual_placelinks', static function (JoinClause $join): void {
492dfb2cda2SGreg Roach                $join
493dfb2cda2SGreg Roach                    ->on('individual_placelinks.pl_file', '=', 'individuals.i_file')
494dfb2cda2SGreg Roach                    ->on('individual_placelinks.pl_gid', '=', 'individuals.i_id');
495dfb2cda2SGreg Roach            });
4960b5fd0a6SGreg Roach            $query->join('places AS individual_places', static function (JoinClause $join): void {
497dfb2cda2SGreg Roach                $join
498dfb2cda2SGreg Roach                    ->on('individual_places.p_file', '=', 'individual_placelinks.pl_file')
499dfb2cda2SGreg Roach                    ->on('individual_places.p_id', '=', 'individual_placelinks.pl_p_id');
500dfb2cda2SGreg Roach            });
501dfb2cda2SGreg Roach        }
502dfb2cda2SGreg Roach
503dfb2cda2SGreg Roach        if ($fam_plac) {
5040b5fd0a6SGreg Roach            $query->join('placelinks AS familyl_placelinks', static function (JoinClause $join): void {
505dfb2cda2SGreg Roach                $join
506dfb2cda2SGreg Roach                    ->on('familyl_placelinks.pl_file', '=', 'individuals.i_file')
507dfb2cda2SGreg Roach                    ->on('familyl_placelinks.pl_gid', '=', 'individuals.i_id');
508dfb2cda2SGreg Roach            });
5090b5fd0a6SGreg Roach            $query->join('places AS family_places', static function (JoinClause $join): void {
510dfb2cda2SGreg Roach                $join
511dfb2cda2SGreg Roach                    ->on('family_places.p_file', '=', 'familyl_placelinks.pl_file')
512dfb2cda2SGreg Roach                    ->on('family_places.p_id', '=', 'familyl_placelinks.pl_p_id');
513dfb2cda2SGreg Roach            });
514dfb2cda2SGreg Roach        }
515dfb2cda2SGreg Roach
516dfb2cda2SGreg Roach        foreach ($fields as $field_name => $field_value) {
5173cfcc809SGreg Roach            $parts = explode(':', $field_name . '::::');
518dfb2cda2SGreg Roach            if ($parts[0] === 'NAME') {
519dfb2cda2SGreg Roach                // NAME:*
520dfb2cda2SGreg Roach                switch ($parts[1]) {
521dfb2cda2SGreg Roach                    case 'GIVN':
522dfb2cda2SGreg Roach                        switch ($modifiers[$field_name]) {
523dfb2cda2SGreg Roach                            case 'EXACT':
524dfb2cda2SGreg Roach                                $query->where('individual_name.n_givn', '=', $field_value);
525dfb2cda2SGreg Roach                                break;
526dfb2cda2SGreg Roach                            case 'BEGINS':
527dfb2cda2SGreg Roach                                $query->where('individual_name.n_givn', 'LIKE', $field_value . '%');
528dfb2cda2SGreg Roach                                break;
529dfb2cda2SGreg Roach                            case 'CONTAINS':
530dfb2cda2SGreg Roach                                $query->where('individual_name.n_givn', 'LIKE', '%' . $field_value . '%');
531dfb2cda2SGreg Roach                                break;
532dfb2cda2SGreg Roach                            case 'SDX_STD':
533dfb2cda2SGreg Roach                                $sdx = Soundex::russell($field_value);
534dfb2cda2SGreg Roach                                if ($sdx !== '') {
535dfb2cda2SGreg Roach                                    $this->wherePhonetic($query, 'individual_name.n_soundex_givn_std', $sdx);
536dfb2cda2SGreg Roach                                } else {
537dfb2cda2SGreg Roach                                    // No phonetic content? Use a substring match
538dfb2cda2SGreg Roach                                    $query->where('individual_name.n_givn', 'LIKE', '%' . $field_value . '%');
539dfb2cda2SGreg Roach                                }
540dfb2cda2SGreg Roach                                break;
541dfb2cda2SGreg Roach                            case 'SDX': // SDX uses DM by default.
542dfb2cda2SGreg Roach                            case 'SDX_DM':
543dfb2cda2SGreg Roach                                $sdx = Soundex::daitchMokotoff($field_value);
544dfb2cda2SGreg Roach                                if ($sdx !== '') {
545dfb2cda2SGreg Roach                                    $this->wherePhonetic($query, 'individual_name.n_soundex_givn_dm', $sdx);
546dfb2cda2SGreg Roach                                } else {
547dfb2cda2SGreg Roach                                    // No phonetic content? Use a substring match
548dfb2cda2SGreg Roach                                    $query->where('individual_name.n_givn', 'LIKE', '%' . $field_value . '%');
549dfb2cda2SGreg Roach                                }
550dfb2cda2SGreg Roach                                break;
551dfb2cda2SGreg Roach                        }
552dfb2cda2SGreg Roach                        break;
553dfb2cda2SGreg Roach                    case 'SURN':
554dfb2cda2SGreg Roach                        switch ($modifiers[$field_name]) {
555dfb2cda2SGreg Roach                            case 'EXACT':
556dfb2cda2SGreg Roach                                $query->where('individual_name.n_surn', '=', $field_value);
557dfb2cda2SGreg Roach                                break;
558dfb2cda2SGreg Roach                            case 'BEGINS':
559dfb2cda2SGreg Roach                                $query->where('individual_name.n_surn', 'LIKE', $field_value . '%');
560dfb2cda2SGreg Roach                                break;
561dfb2cda2SGreg Roach                            case 'CONTAINS':
562dfb2cda2SGreg Roach                                $query->where('individual_name.n_surn', 'LIKE', '%' . $field_value . '%');
563dfb2cda2SGreg Roach                                break;
564dfb2cda2SGreg Roach                            case 'SDX_STD':
565dfb2cda2SGreg Roach                                $sdx = Soundex::russell($field_value);
566dfb2cda2SGreg Roach                                if ($sdx !== '') {
567dfb2cda2SGreg Roach                                    $this->wherePhonetic($query, 'individual_name.n_soundex_surn_std', $sdx);
568dfb2cda2SGreg Roach                                } else {
569dfb2cda2SGreg Roach                                    // No phonetic content? Use a substring match
570dfb2cda2SGreg Roach                                    $query->where('individual_name.n_surn', 'LIKE', '%' . $field_value . '%');
571dfb2cda2SGreg Roach                                }
572dfb2cda2SGreg Roach                                break;
573dfb2cda2SGreg Roach                            case 'SDX': // SDX uses DM by default.
574dfb2cda2SGreg Roach                            case 'SDX_DM':
575dfb2cda2SGreg Roach                                $sdx = Soundex::daitchMokotoff($field_value);
576dfb2cda2SGreg Roach                                if ($sdx !== '') {
577dfb2cda2SGreg Roach                                    $this->wherePhonetic($query, 'individual_name.n_soundex_surn_dm', $sdx);
578dfb2cda2SGreg Roach                                } else {
579dfb2cda2SGreg Roach                                    // No phonetic content? Use a substring match
580dfb2cda2SGreg Roach                                    $query->where('individual_name.n_surn', 'LIKE', '%' . $field_value . '%');
581dfb2cda2SGreg Roach                                }
582dfb2cda2SGreg Roach                                break;
583dfb2cda2SGreg Roach                        }
584dfb2cda2SGreg Roach                        break;
585dfb2cda2SGreg Roach                    case 'NICK':
586dfb2cda2SGreg Roach                    case '_MARNM':
587dfb2cda2SGreg Roach                    case '_HEB':
588dfb2cda2SGreg Roach                    case '_AKA':
589dfb2cda2SGreg Roach                        $query
590dfb2cda2SGreg Roach                            ->where('individual_name', '=', $parts[1])
591dfb2cda2SGreg Roach                            ->where('individual_name', 'LIKE', '%' . $field_value . '%');
592dfb2cda2SGreg Roach                        break;
593dfb2cda2SGreg Roach                }
594dfb2cda2SGreg Roach                unset($fields[$field_name]);
595dfb2cda2SGreg Roach            } elseif ($parts[1] === 'DATE') {
596dfb2cda2SGreg Roach                // *:DATE
597dfb2cda2SGreg Roach                $date = new Date($field_value);
598dfb2cda2SGreg Roach                if ($date->isOK()) {
599dfb2cda2SGreg Roach                    $delta = 365 * ($modifiers[$field_name] ?? 0);
600dfb2cda2SGreg Roach                    $query
601dfb2cda2SGreg Roach                        ->where('individual_dates.d_fact', '=', $parts[0])
602dfb2cda2SGreg Roach                        ->where('individual_dates.d_julianday1', '>=', $date->minimumJulianDay() - $delta)
603dfb2cda2SGreg Roach                        ->where('individual_dates.d_julianday2', '<=', $date->minimumJulianDay() + $delta);
604dfb2cda2SGreg Roach                }
605dfb2cda2SGreg Roach                unset($fields[$field_name]);
606dfb2cda2SGreg Roach            } elseif ($parts[0] === 'FAMS' && $parts[2] === 'DATE') {
607dfb2cda2SGreg Roach                // FAMS:*:DATE
608dfb2cda2SGreg Roach                $date = new Date($field_value);
609dfb2cda2SGreg Roach                if ($date->isOK()) {
610dfb2cda2SGreg Roach                    $delta = 365 * $modifiers[$field_name];
611dfb2cda2SGreg Roach                    $query
612dfb2cda2SGreg Roach                        ->where('family_dates.d_fact', '=', $parts[1])
613dfb2cda2SGreg Roach                        ->where('family_dates.d_julianday1', '>=', $date->minimumJulianDay() - $delta)
614dfb2cda2SGreg Roach                        ->where('family_dates.d_julianday2', '<=', $date->minimumJulianDay() + $delta);
615dfb2cda2SGreg Roach                }
616dfb2cda2SGreg Roach                unset($fields[$field_name]);
617dfb2cda2SGreg Roach            } elseif ($parts[1] === 'PLAC') {
618dfb2cda2SGreg Roach                // *:PLAC
619dfb2cda2SGreg Roach                // SQL can only link a place to a person/family, not to an event.
620dfb2cda2SGreg Roach                $query->where('individual_places.p_place', 'LIKE', '%' . $field_value . '%');
621dfb2cda2SGreg Roach            } elseif ($parts[0] === 'FAMS' && $parts[2] === 'PLAC') {
622dfb2cda2SGreg Roach                // FAMS:*:PLAC
623dfb2cda2SGreg Roach                // SQL can only link a place to a person/family, not to an event.
624dfb2cda2SGreg Roach                $query->where('family_places.p_place', 'LIKE', '%' . $field_value . '%');
625dfb2cda2SGreg Roach            } elseif ($parts[0] === 'FAMC' && $parts[2] === 'NAME') {
626dfb2cda2SGreg Roach                $table = $parts[1] === 'HUSB' ? 'father_name' : 'mother_name';
627dfb2cda2SGreg Roach                // NAME:*
628dfb2cda2SGreg Roach                switch ($parts[3]) {
629dfb2cda2SGreg Roach                    case 'GIVN':
630dfb2cda2SGreg Roach                        switch ($modifiers[$field_name]) {
631dfb2cda2SGreg Roach                            case 'EXACT':
632dfb2cda2SGreg Roach                                $query->where($table . '.n_givn', '=', $field_value);
633dfb2cda2SGreg Roach                                break;
634dfb2cda2SGreg Roach                            case 'BEGINS':
635dfb2cda2SGreg Roach                                $query->where($table . '.n_givn', 'LIKE', $field_value . '%');
636dfb2cda2SGreg Roach                                break;
637dfb2cda2SGreg Roach                            case 'CONTAINS':
638dfb2cda2SGreg Roach                                $query->where($table . '.n_givn', 'LIKE', '%' . $field_value . '%');
639dfb2cda2SGreg Roach                                break;
640dfb2cda2SGreg Roach                            case 'SDX_STD':
641dfb2cda2SGreg Roach                                $sdx = Soundex::russell($field_value);
642dfb2cda2SGreg Roach                                if ($sdx !== '') {
643dfb2cda2SGreg Roach                                    $this->wherePhonetic($query, $table . '.n_soundex_givn_std', $sdx);
644dfb2cda2SGreg Roach                                } else {
645dfb2cda2SGreg Roach                                    // No phonetic content? Use a substring match
646dfb2cda2SGreg Roach                                    $query->where($table . '.n_givn', 'LIKE', '%' . $field_value . '%');
647dfb2cda2SGreg Roach                                }
648dfb2cda2SGreg Roach                                break;
649dfb2cda2SGreg Roach                            case 'SDX': // SDX uses DM by default.
650dfb2cda2SGreg Roach                            case 'SDX_DM':
651dfb2cda2SGreg Roach                                $sdx = Soundex::daitchMokotoff($field_value);
652dfb2cda2SGreg Roach                                if ($sdx !== '') {
653dfb2cda2SGreg Roach                                    $this->wherePhonetic($query, $table . '.n_soundex_givn_dm', $sdx);
654dfb2cda2SGreg Roach                                } else {
655dfb2cda2SGreg Roach                                    // No phonetic content? Use a substring match
656dfb2cda2SGreg Roach                                    $query->where($table . '.n_givn', 'LIKE', '%' . $field_value . '%');
657dfb2cda2SGreg Roach                                }
658dfb2cda2SGreg Roach                                break;
659dfb2cda2SGreg Roach                        }
660dfb2cda2SGreg Roach                        break;
661dfb2cda2SGreg Roach                    case 'SURN':
662dfb2cda2SGreg Roach                        switch ($modifiers[$field_name]) {
663dfb2cda2SGreg Roach                            case 'EXACT':
664dfb2cda2SGreg Roach                                $query->where($table . '.n_surn', '=', $field_value);
665dfb2cda2SGreg Roach                                break;
666dfb2cda2SGreg Roach                            case 'BEGINS':
667dfb2cda2SGreg Roach                                $query->where($table . '.n_surn', 'LIKE', $field_value . '%');
668dfb2cda2SGreg Roach                                break;
669dfb2cda2SGreg Roach                            case 'CONTAINS':
670dfb2cda2SGreg Roach                                $query->where($table . '.n_surn', 'LIKE', '%' . $field_value . '%');
671dfb2cda2SGreg Roach                                break;
672dfb2cda2SGreg Roach                            case 'SDX_STD':
673dfb2cda2SGreg Roach                                $sdx = Soundex::russell($field_value);
674dfb2cda2SGreg Roach                                if ($sdx !== '') {
675dfb2cda2SGreg Roach                                    $this->wherePhonetic($query, $table . '.n_soundex_surn_std', $sdx);
676dfb2cda2SGreg Roach                                } else {
677dfb2cda2SGreg Roach                                    // No phonetic content? Use a substring match
678dfb2cda2SGreg Roach                                    $query->where($table . '.n_surn', 'LIKE', '%' . $field_value . '%');
679dfb2cda2SGreg Roach                                }
680dfb2cda2SGreg Roach                                break;
681dfb2cda2SGreg Roach                            case 'SDX': // SDX uses DM by default.
682dfb2cda2SGreg Roach                            case 'SDX_DM':
683dfb2cda2SGreg Roach                                $sdx = Soundex::daitchMokotoff($field_value);
684dfb2cda2SGreg Roach                                if ($sdx !== '') {
685dfb2cda2SGreg Roach                                    $this->wherePhonetic($query, $table . '.n_soundex_surn_dm', $sdx);
686dfb2cda2SGreg Roach                                } else {
687dfb2cda2SGreg Roach                                    // No phonetic content? Use a substring match
688dfb2cda2SGreg Roach                                    $query->where($table . '.n_surn', 'LIKE', '%' . $field_value . '%');
689dfb2cda2SGreg Roach                                }
690dfb2cda2SGreg Roach                                break;
691dfb2cda2SGreg Roach                        }
692dfb2cda2SGreg Roach                        break;
693dfb2cda2SGreg Roach                }
694dfb2cda2SGreg Roach                unset($fields[$field_name]);
695dfb2cda2SGreg Roach            } elseif ($parts[0] === 'FAMS') {
696dfb2cda2SGreg Roach                // e.g. searches for occupation, religion, note, etc.
697dfb2cda2SGreg Roach                // Initial matching only.  Need PHP to apply filter.
698dfb2cda2SGreg Roach                $query->where('families.f_gedcom', 'LIKE', "%\n1 " . $parts[1] . ' %' . $field_value . '%');
699dfb2cda2SGreg Roach            } elseif ($parts[1] === 'TYPE') {
700dfb2cda2SGreg Roach                // e.g. FACT:TYPE or EVEN:TYPE
701dfb2cda2SGreg Roach                // Initial matching only.  Need PHP to apply filter.
702dfb2cda2SGreg Roach                $query->where('individuals.i_gedcom', 'LIKE', "%\n1 " . $parts[0] . '%\n2 TYPE %' . $field_value . '%');
703dfb2cda2SGreg Roach            } else {
704dfb2cda2SGreg Roach                // e.g. searches for occupation, religion, note, etc.
705dfb2cda2SGreg Roach                // Initial matching only.  Need PHP to apply filter.
706c5457947SGreg Roach                $query->where('individuals.i_gedcom', 'LIKE', "%\n1 " . $parts[0] . '%' . $parts[1] . '%' . $field_value . '%');
707dfb2cda2SGreg Roach            }
708dfb2cda2SGreg Roach        }
709dfb2cda2SGreg Roach        return $query
710dfb2cda2SGreg Roach            ->get()
71152a8ef61SGreg Roach            ->each($this->rowLimiter())
712d5ad3db0SGreg Roach            ->map($this->individualRowMapper())
713dfb2cda2SGreg Roach            ->filter(GedcomRecord::accessFilter())
7140b5fd0a6SGreg Roach            ->filter(static function (Individual $individual) use ($fields): bool {
715c5457947SGreg Roach                // Check for searches which were only partially matched by SQL
716dfb2cda2SGreg Roach                foreach ($fields as $field_name => $field_value) {
717a41e65f0SGreg Roach                    $regex = '/' . preg_quote($field_value, '/') . '/i';
718dfb2cda2SGreg Roach
719c5457947SGreg Roach                    $parts = explode(':', $field_name . '::::');
720dfb2cda2SGreg Roach
721dfb2cda2SGreg Roach                    // *:PLAC
722c5457947SGreg Roach                    if ($parts[1] === 'PLAC') {
723a41e65f0SGreg Roach                        foreach ($individual->facts([$parts[0]]) as $fact) {
724392561bbSGreg Roach                            if (preg_match($regex, $fact->place()->gedcomName())) {
725c5457947SGreg Roach                                continue 2;
726dfb2cda2SGreg Roach                            }
727a41e65f0SGreg Roach                        }
728c5457947SGreg Roach                        return false;
729c5457947SGreg Roach                    }
730c5457947SGreg Roach
731dfb2cda2SGreg Roach                    // FAMS:*:PLAC
732c5457947SGreg Roach                    if ($parts[0] === 'FAMS' && $parts[2] === 'PLAC') {
73339ca88baSGreg Roach                        foreach ($individual->spouseFamilies() as $family) {
734a41e65f0SGreg Roach                            foreach ($family->facts([$parts[1]]) as $fact) {
735392561bbSGreg Roach                                if (preg_match($regex, $fact->place()->gedcomName())) {
736c5457947SGreg Roach                                    continue 2;
737a41e65f0SGreg Roach                                }
738dfb2cda2SGreg Roach                            }
739dfb2cda2SGreg Roach                        }
740c5457947SGreg Roach                        return false;
741c5457947SGreg Roach                    }
742c5457947SGreg Roach
743dfb2cda2SGreg Roach                    // e.g. searches for occupation, religion, note, etc.
744c5457947SGreg Roach                    if ($parts[0] === 'FAMS') {
74539ca88baSGreg Roach                        foreach ($individual->spouseFamilies() as $family) {
746a41e65f0SGreg Roach                            foreach ($family->facts([$parts[1]]) as $fact) {
747a41e65f0SGreg Roach                                if (preg_match($regex, $fact->value())) {
748c5457947SGreg Roach                                    continue 3;
749a41e65f0SGreg Roach                                }
750dfb2cda2SGreg Roach                            }
751dfb2cda2SGreg Roach                        }
752c5457947SGreg Roach                        return false;
753c5457947SGreg Roach                    }
754c5457947SGreg Roach
755dfb2cda2SGreg Roach                    // e.g. FACT:TYPE or EVEN:TYPE
756c5457947SGreg Roach                    if ($parts[1] === 'TYPE' || $parts[1] === '_WT_USER') {
757a41e65f0SGreg Roach                        foreach ($individual->facts([$parts[0]]) as $fact) {
758c5457947SGreg Roach                            if (preg_match($regex, $fact->attribute($parts[1]))) {
759c5457947SGreg Roach                                continue 2;
760dfb2cda2SGreg Roach                            }
761dfb2cda2SGreg Roach                        }
762dfb2cda2SGreg Roach
763dfb2cda2SGreg Roach                        return false;
764dfb2cda2SGreg Roach                    }
765c5457947SGreg Roach                }
766dfb2cda2SGreg Roach
767dfb2cda2SGreg Roach                return true;
768dfb2cda2SGreg Roach            });
769dfb2cda2SGreg Roach    }
770dfb2cda2SGreg Roach
771dfb2cda2SGreg Roach    /**
772dfb2cda2SGreg Roach     * @param string $soundex
773dfb2cda2SGreg Roach     * @param string $lastname
774dfb2cda2SGreg Roach     * @param string $firstname
775dfb2cda2SGreg Roach     * @param string $place
776dfb2cda2SGreg Roach     * @param Tree[] $search_trees
777dfb2cda2SGreg Roach     *
77854c7f8dfSGreg Roach     * @return Collection
779dfb2cda2SGreg Roach     */
780dfb2cda2SGreg Roach    public function searchIndividualsPhonetic(string $soundex, string $lastname, string $firstname, string $place, array $search_trees): Collection
781dfb2cda2SGreg Roach    {
782dfb2cda2SGreg Roach        switch ($soundex) {
783dfb2cda2SGreg Roach            default:
784dfb2cda2SGreg Roach            case 'Russell':
785dfb2cda2SGreg Roach                $givn_sdx   = Soundex::russell($firstname);
786dfb2cda2SGreg Roach                $surn_sdx   = Soundex::russell($lastname);
787dfb2cda2SGreg Roach                $plac_sdx   = Soundex::russell($place);
788dfb2cda2SGreg Roach                $givn_field = 'n_soundex_givn_std';
789dfb2cda2SGreg Roach                $surn_field = 'n_soundex_surn_std';
790dfb2cda2SGreg Roach                $plac_field = 'p_std_soundex';
791dfb2cda2SGreg Roach                break;
792dfb2cda2SGreg Roach            case 'DaitchM':
793dfb2cda2SGreg Roach                $givn_sdx   = Soundex::daitchMokotoff($firstname);
794dfb2cda2SGreg Roach                $surn_sdx   = Soundex::daitchMokotoff($lastname);
795dfb2cda2SGreg Roach                $plac_sdx   = Soundex::daitchMokotoff($place);
796dfb2cda2SGreg Roach                $givn_field = 'n_soundex_givn_dm';
797dfb2cda2SGreg Roach                $surn_field = 'n_soundex_surn_dm';
798dfb2cda2SGreg Roach                $plac_field = 'p_dm_soundex';
799dfb2cda2SGreg Roach                break;
800dfb2cda2SGreg Roach        }
801dfb2cda2SGreg Roach
802dfb2cda2SGreg Roach        // Nothing to search for? Return nothing.
803dfb2cda2SGreg Roach        if ($givn_sdx === '' && $surn_sdx === '' && $plac_sdx === '') {
8043fda39a7SGreg Roach            return new Collection();
805dfb2cda2SGreg Roach        }
806dfb2cda2SGreg Roach
807dfb2cda2SGreg Roach        $query = DB::table('individuals')
808dfb2cda2SGreg Roach            ->select(['individuals.*'])
809dfb2cda2SGreg Roach            ->distinct();
810dfb2cda2SGreg Roach
811dfb2cda2SGreg Roach        $this->whereTrees($query, 'i_file', $search_trees);
812dfb2cda2SGreg Roach
813dfb2cda2SGreg Roach        if ($plac_sdx !== '') {
8140b5fd0a6SGreg Roach            $query->join('placelinks', static function (JoinClause $join): void {
815dfb2cda2SGreg Roach                $join
816dfb2cda2SGreg Roach                    ->on('placelinks.pl_file', '=', 'individuals.i_file')
817dfb2cda2SGreg Roach                    ->on('placelinks.pl_gid', '=', 'individuals.i_id');
818dfb2cda2SGreg Roach            });
8190b5fd0a6SGreg Roach            $query->join('places', static function (JoinClause $join): void {
820dfb2cda2SGreg Roach                $join
821dfb2cda2SGreg Roach                    ->on('places.p_file', '=', 'placelinks.pl_file')
822dfb2cda2SGreg Roach                    ->on('places.p_id', '=', 'placelinks.pl_p_id');
823dfb2cda2SGreg Roach            });
824dfb2cda2SGreg Roach
825dfb2cda2SGreg Roach            $this->wherePhonetic($query, $plac_field, $plac_sdx);
826dfb2cda2SGreg Roach        }
827dfb2cda2SGreg Roach
828dfb2cda2SGreg Roach        if ($givn_sdx !== '' || $surn_sdx !== '') {
8290b5fd0a6SGreg Roach            $query->join('name', static function (JoinClause $join): void {
830dfb2cda2SGreg Roach                $join
831dfb2cda2SGreg Roach                    ->on('name.n_file', '=', 'individuals.i_file')
832dfb2cda2SGreg Roach                    ->on('name.n_id', '=', 'individuals.i_id');
833dfb2cda2SGreg Roach            });
834dfb2cda2SGreg Roach
835dfb2cda2SGreg Roach            $this->wherePhonetic($query, $givn_field, $givn_sdx);
836dfb2cda2SGreg Roach            $this->wherePhonetic($query, $surn_field, $surn_sdx);
837dfb2cda2SGreg Roach        }
838dfb2cda2SGreg Roach
839dfb2cda2SGreg Roach        return $query
840dfb2cda2SGreg Roach            ->get()
84152a8ef61SGreg Roach            ->each($this->rowLimiter())
842d5ad3db0SGreg Roach            ->map($this->individualRowMapper())
843dfb2cda2SGreg Roach            ->filter(GedcomRecord::accessFilter());
844dfb2cda2SGreg Roach    }
845dfb2cda2SGreg Roach
846dfb2cda2SGreg Roach    /**
84732cd2800SGreg Roach     * Paginate a search query.
84832cd2800SGreg Roach     *
84932cd2800SGreg Roach     * @param Builder $query      Searches the database for the desired records.
85032cd2800SGreg Roach     * @param Closure $row_mapper Converts a row from the query into a record.
851a7a24840SGreg Roach     * @param Closure $row_filter
85232cd2800SGreg Roach     * @param int     $offset     Skip this many rows.
85332cd2800SGreg Roach     * @param int     $limit      Take this many rows.
85432cd2800SGreg Roach     *
85532cd2800SGreg Roach     * @return Collection
85632cd2800SGreg Roach     */
857a7a24840SGreg Roach    private function paginateQuery(Builder $query, Closure $row_mapper, Closure $row_filter, int $offset, int $limit): Collection
85832cd2800SGreg Roach    {
85932cd2800SGreg Roach        $collection = new Collection();
86032cd2800SGreg Roach
86132cd2800SGreg Roach        foreach ($query->cursor() as $row) {
86232cd2800SGreg Roach            $record = $row_mapper($row);
863b68caec6SGreg Roach            // If the object has a method "canShow()", then use it to filter for privacy.
864a7a24840SGreg Roach            if ($row_filter($record)) {
86532cd2800SGreg Roach                if ($offset > 0) {
86632cd2800SGreg Roach                    $offset--;
86732cd2800SGreg Roach                } else {
86832cd2800SGreg Roach                    if ($limit > 0) {
86932cd2800SGreg Roach                        $collection->push($record);
87032cd2800SGreg Roach                    }
87132cd2800SGreg Roach
87232cd2800SGreg Roach                    $limit--;
87332cd2800SGreg Roach
87432cd2800SGreg Roach                    if ($limit === 0) {
87532cd2800SGreg Roach                        break;
87632cd2800SGreg Roach                    }
87732cd2800SGreg Roach                }
87832cd2800SGreg Roach            }
87932cd2800SGreg Roach        }
88032cd2800SGreg Roach
881e0458bdcSGreg Roach
88232cd2800SGreg Roach        return $collection;
88332cd2800SGreg Roach    }
884a7a24840SGreg Roach
885a7a24840SGreg Roach    /**
886a7a24840SGreg Roach     * Apply search filters to a SQL query column.  Apply collation rules to MySQL.
887a7a24840SGreg Roach     *
888a7a24840SGreg Roach     * @param Builder           $query
889a7a24840SGreg Roach     * @param Expression|string $field
890a7a24840SGreg Roach     * @param string[]          $search_terms
891a7a24840SGreg Roach     */
892a7a24840SGreg Roach    private function whereSearch(Builder $query, $field, array $search_terms): void
893a7a24840SGreg Roach    {
894a7a24840SGreg Roach        if ($field instanceof Expression) {
895a7a24840SGreg Roach            $field = $field->getValue();
896a7a24840SGreg Roach        }
897a7a24840SGreg Roach
898a7a24840SGreg Roach        foreach ($search_terms as $search_term) {
899a69f5655SGreg Roach            $query->whereContains(new Expression($field), $search_term);
900a7a24840SGreg Roach        }
901a7a24840SGreg Roach    }
902a7a24840SGreg Roach
903a7a24840SGreg Roach    /**
9042d686e68SGreg Roach     * Apply soundex search filters to a SQL query column.
9052d686e68SGreg Roach     *
9062d686e68SGreg Roach     * @param Builder           $query
9072d686e68SGreg Roach     * @param Expression|string $field
9082d686e68SGreg Roach     * @param string            $soundex
9092d686e68SGreg Roach     */
9102d686e68SGreg Roach    private function wherePhonetic(Builder $query, $field, string $soundex): void
9112d686e68SGreg Roach    {
9122d686e68SGreg Roach        if ($soundex !== '') {
9130b5fd0a6SGreg Roach            $query->where(static function (Builder $query) use ($soundex, $field): void {
9142d686e68SGreg Roach                foreach (explode(':', $soundex) as $sdx) {
9152d686e68SGreg Roach                    $query->orWhere($field, 'LIKE', '%' . $sdx . '%');
9162d686e68SGreg Roach                }
9172d686e68SGreg Roach            });
9182d686e68SGreg Roach        }
9192d686e68SGreg Roach    }
9202d686e68SGreg Roach
9212d686e68SGreg Roach    /**
922a7a24840SGreg Roach     * @param Builder $query
923a7a24840SGreg Roach     * @param string  $tree_id_field
924a7a24840SGreg Roach     * @param Tree[]  $trees
925a7a24840SGreg Roach     */
926a7a24840SGreg Roach    private function whereTrees(Builder $query, string $tree_id_field, array $trees): void
927a7a24840SGreg Roach    {
9280b5fd0a6SGreg Roach        $tree_ids = array_map(static function (Tree $tree): int {
929a7a24840SGreg Roach            return $tree->id();
930a7a24840SGreg Roach        }, $trees);
931a7a24840SGreg Roach
932a7a24840SGreg Roach        $query->whereIn($tree_id_field, $tree_ids);
933a7a24840SGreg Roach    }
934a7a24840SGreg Roach
935d5ad3db0SGreg Roach
936d5ad3db0SGreg Roach    /**
937d5ad3db0SGreg Roach     * Find the media object that uses a particular media file.
938d5ad3db0SGreg Roach     *
939d5ad3db0SGreg Roach     * @param string $file
940d5ad3db0SGreg Roach     *
941d5ad3db0SGreg Roach     * @return Media[]
942d5ad3db0SGreg Roach     */
943d5ad3db0SGreg Roach    public function findMediaObjectsForMediaFile(string $file): array
944d5ad3db0SGreg Roach    {
945d5ad3db0SGreg Roach        return DB::table('media')
946d5ad3db0SGreg Roach            ->join('media_file', static function (JoinClause $join): void {
947d5ad3db0SGreg Roach                $join
948d5ad3db0SGreg Roach                    ->on('media_file.m_file', '=', 'media.m_file')
949d5ad3db0SGreg Roach                    ->on('media_file.m_id', '=', 'media.m_id');
950d5ad3db0SGreg Roach            })
951d5ad3db0SGreg Roach            ->join('gedcom_setting', 'media.m_file', '=', 'gedcom_setting.gedcom_id')
952d5ad3db0SGreg Roach            ->where(new Expression('setting_value || multimedia_file_refn'), '=', $file)
953d5ad3db0SGreg Roach            ->select(['media.*'])
954d5ad3db0SGreg Roach            ->distinct()
955d5ad3db0SGreg Roach            ->get()
956d5ad3db0SGreg Roach            ->map($this->mediaRowMapper())
957d5ad3db0SGreg Roach            ->all();
958d5ad3db0SGreg Roach    }
959d5ad3db0SGreg Roach
960a7a24840SGreg Roach    /**
961a7a24840SGreg Roach     * A closure to filter records by privacy-filtered GEDCOM data.
962a7a24840SGreg Roach     *
963a7a24840SGreg Roach     * @param array $search_terms
964a7a24840SGreg Roach     *
965a7a24840SGreg Roach     * @return Closure
966a7a24840SGreg Roach     */
967a7a24840SGreg Roach    private function rawGedcomFilter(array $search_terms): Closure
968a7a24840SGreg Roach    {
9696c2179e2SGreg Roach        return static function (GedcomRecord $record) use ($search_terms): bool {
970a7a24840SGreg Roach            // Ignore non-genealogy fields
971a7a24840SGreg Roach            $gedcom = preg_replace('/\n\d (?:_UID) .*/', '', $record->gedcom());
972a7a24840SGreg Roach
973a7a24840SGreg Roach            // Ignore matches in links
974a7a24840SGreg Roach            $gedcom = preg_replace('/\n\d ' . Gedcom::REGEX_TAG . '( @' . Gedcom::REGEX_XREF . '@)?/', '', $gedcom);
975a7a24840SGreg Roach
976a7a24840SGreg Roach            // Re-apply the filtering
977a7a24840SGreg Roach            foreach ($search_terms as $search_term) {
978a7a24840SGreg Roach                if (mb_stripos($gedcom, $search_term) === false) {
979a7a24840SGreg Roach                    return false;
980a7a24840SGreg Roach                }
981a7a24840SGreg Roach            }
982a7a24840SGreg Roach
983a7a24840SGreg Roach            return true;
984a7a24840SGreg Roach        };
985a7a24840SGreg Roach    }
98652a8ef61SGreg Roach
98752a8ef61SGreg Roach    /**
98852a8ef61SGreg Roach     * Searching for short or common text can give more results than the system can process.
98952a8ef61SGreg Roach     *
99052a8ef61SGreg Roach     * @param int $limit
99152a8ef61SGreg Roach     *
99252a8ef61SGreg Roach     * @return Closure
99352a8ef61SGreg Roach     */
99452a8ef61SGreg Roach    private function rowLimiter(int $limit = 1000): Closure
99552a8ef61SGreg Roach    {
9966c2179e2SGreg Roach        return static function () use ($limit): void {
99752a8ef61SGreg Roach            static $n = 0;
99852a8ef61SGreg Roach
99952a8ef61SGreg Roach            if (++$n > $limit) {
100052a8ef61SGreg Roach                $message = I18N::translate('The search returned too many results.');
100152a8ef61SGreg Roach
1002d501c45dSGreg Roach                throw new HttpServiceUnavailableException($message);
100352a8ef61SGreg Roach            }
100452a8ef61SGreg Roach        };
100552a8ef61SGreg Roach    }
1006d5ad3db0SGreg Roach
1007d5ad3db0SGreg Roach    /**
1008d5ad3db0SGreg Roach     * Convert a row from any tree in the families table into a family object.
1009d5ad3db0SGreg Roach     *
1010d5ad3db0SGreg Roach     * @return Closure
1011d5ad3db0SGreg Roach     */
1012d5ad3db0SGreg Roach    private function familyRowMapper(): Closure
1013d5ad3db0SGreg Roach    {
1014d5ad3db0SGreg Roach        return function (stdClass $row): Family {
1015d5ad3db0SGreg Roach            $tree = $this->tree_service->find((int) $row->f_file);
1016d5ad3db0SGreg Roach
1017d5ad3db0SGreg Roach            return Family::getInstance($row->f_id, $tree, $row->f_gedcom);
1018d5ad3db0SGreg Roach        };
1019d5ad3db0SGreg Roach    }
1020d5ad3db0SGreg Roach
1021d5ad3db0SGreg Roach    /**
1022d5ad3db0SGreg Roach     * Convert a row from any tree in the individuals table into an individual object.
1023d5ad3db0SGreg Roach     *
1024d5ad3db0SGreg Roach     * @return Closure
1025d5ad3db0SGreg Roach     */
1026d5ad3db0SGreg Roach    private function individualRowMapper(): Closure
1027d5ad3db0SGreg Roach    {
1028d5ad3db0SGreg Roach        return function (stdClass $row): Individual {
1029d5ad3db0SGreg Roach            $tree = $this->tree_service->find((int) $row->i_file);
1030d5ad3db0SGreg Roach
1031d5ad3db0SGreg Roach            return Individual::getInstance($row->i_id, $tree, $row->i_gedcom);
1032d5ad3db0SGreg Roach        };
1033d5ad3db0SGreg Roach    }
1034d5ad3db0SGreg Roach
1035d5ad3db0SGreg Roach    /**
1036d5ad3db0SGreg Roach     * Convert a row from any tree in the media table into an media object.
1037d5ad3db0SGreg Roach     *
1038d5ad3db0SGreg Roach     * @return Closure
1039d5ad3db0SGreg Roach     */
1040d5ad3db0SGreg Roach    private function mediaRowMapper(): Closure
1041d5ad3db0SGreg Roach    {
1042d5ad3db0SGreg Roach        return function (stdClass $row): Media {
1043d5ad3db0SGreg Roach            $tree = $this->tree_service->find((int) $row->m_file);
1044d5ad3db0SGreg Roach
1045d5ad3db0SGreg Roach            return Media::getInstance($row->m_id, $tree, $row->m_gedcom);
1046d5ad3db0SGreg Roach        };
1047d5ad3db0SGreg Roach    }
1048d5ad3db0SGreg Roach
1049d5ad3db0SGreg Roach    /**
1050d5ad3db0SGreg Roach     * Convert a row from any tree in the other table into a note object.
1051d5ad3db0SGreg Roach     *
1052d5ad3db0SGreg Roach     * @return Closure
1053d5ad3db0SGreg Roach     */
1054d5ad3db0SGreg Roach    private function noteRowMapper(): Closure
1055d5ad3db0SGreg Roach    {
1056d5ad3db0SGreg Roach        return function (stdClass $row): Note {
1057d5ad3db0SGreg Roach            $tree = $this->tree_service->find((int) $row->o_file);
1058d5ad3db0SGreg Roach
1059d5ad3db0SGreg Roach            return Note::getInstance($row->o_id, $tree, $row->o_gedcom);
1060d5ad3db0SGreg Roach        };
1061d5ad3db0SGreg Roach    }
1062d5ad3db0SGreg Roach
1063d5ad3db0SGreg Roach    /**
1064d5ad3db0SGreg Roach     * Convert a row from any tree in the other table into a repository object.
1065d5ad3db0SGreg Roach     *
1066d5ad3db0SGreg Roach     * @return Closure
1067d5ad3db0SGreg Roach     */
1068d5ad3db0SGreg Roach    private function repositoryRowMapper(): Closure
1069d5ad3db0SGreg Roach    {
1070d5ad3db0SGreg Roach        return function (stdClass $row): Repository {
1071d5ad3db0SGreg Roach            $tree = $this->tree_service->find((int) $row->o_file);
1072d5ad3db0SGreg Roach
1073d5ad3db0SGreg Roach            return Repository::getInstance($row->o_id, $tree, $row->o_gedcom);
1074d5ad3db0SGreg Roach        };
1075d5ad3db0SGreg Roach    }
1076d5ad3db0SGreg Roach
1077d5ad3db0SGreg Roach    /**
1078d5ad3db0SGreg Roach     * Convert a row from any tree in the sources table into a source object.
1079d5ad3db0SGreg Roach     *
1080d5ad3db0SGreg Roach     * @return Closure
1081d5ad3db0SGreg Roach     */
1082d5ad3db0SGreg Roach    private function sourceRowMapper(): Closure
1083d5ad3db0SGreg Roach    {
1084d5ad3db0SGreg Roach        return function (stdClass $row): Source {
1085d5ad3db0SGreg Roach            $tree = $this->tree_service->find((int) $row->s_file);
1086d5ad3db0SGreg Roach
1087d5ad3db0SGreg Roach            return Source::getInstance($row->s_id, $tree, $row->s_gedcom);
1088d5ad3db0SGreg Roach        };
1089d5ad3db0SGreg Roach    }
1090d5ad3db0SGreg Roach
1091d5ad3db0SGreg Roach    /**
1092d5ad3db0SGreg Roach     * Convert a row from any tree in the other table into a submitter object.
1093d5ad3db0SGreg Roach     *
1094d5ad3db0SGreg Roach     * @return Closure
1095d5ad3db0SGreg Roach     */
1096d5ad3db0SGreg Roach    private function submitterRowMapper(): Closure
1097d5ad3db0SGreg Roach    {
1098d5ad3db0SGreg Roach        return function (stdClass $row): GedcomRecord {
1099d5ad3db0SGreg Roach            $tree = $this->tree_service->find((int) $row->o_file);
1100d5ad3db0SGreg Roach
1101d5ad3db0SGreg Roach            return GedcomRecord::getInstance($row->o_id, $tree, $row->o_gedcom);
1102d5ad3db0SGreg Roach        };
1103d5ad3db0SGreg Roach    }
110432cd2800SGreg Roach}
1105