xref: /webtrees/app/Http/RequestHandlers/SearchGeneralPage.php (revision c4943cff72f95a28fbb9404e3c20b169ff098e5c)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2021 webtrees development team
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <https://www.gnu.org/licenses/>.
16 */
17
18declare(strict_types=1);
19
20namespace Fisharebest\Webtrees\Http\RequestHandlers;
21
22use Fisharebest\Webtrees\Family;
23use Fisharebest\Webtrees\Http\ViewResponseTrait;
24use Fisharebest\Webtrees\I18N;
25use Fisharebest\Webtrees\Services\SearchService;
26use Fisharebest\Webtrees\Services\TreeService;
27use Fisharebest\Webtrees\Site;
28use Fisharebest\Webtrees\Tree;
29use Illuminate\Support\Collection;
30use Psr\Http\Message\ResponseInterface;
31use Psr\Http\Message\ServerRequestInterface;
32use Psr\Http\Server\RequestHandlerInterface;
33
34use function assert;
35use function preg_replace;
36use function redirect;
37use function trim;
38
39use const PREG_SET_ORDER;
40
41/**
42 * Search for genealogy data
43 */
44class SearchGeneralPage implements RequestHandlerInterface
45{
46    use ViewResponseTrait;
47
48    private SearchService $search_service;
49
50    private TreeService $tree_service;
51
52    /**
53     * SearchController constructor.
54     *
55     * @param SearchService $search_service
56     * @param TreeService   $tree_service
57     */
58    public function __construct(SearchService $search_service, TreeService $tree_service)
59    {
60        $this->search_service = $search_service;
61        $this->tree_service   = $tree_service;
62    }
63
64    /**
65     * The standard search.
66     *
67     * @param ServerRequestInterface $request
68     *
69     * @return ResponseInterface
70     */
71    public function handle(ServerRequestInterface $request): ResponseInterface
72    {
73        $tree = $request->getAttribute('tree');
74        assert($tree instanceof Tree);
75
76        $params = $request->getQueryParams();
77        $query  = $params['query'] ?? '';
78
79        // What type of records to search?
80        $search_individuals  = (bool) ($params['search_individuals'] ?? false);
81        $search_families     = (bool) ($params['search_families'] ?? false);
82        $search_repositories = (bool) ($params['search_repositories'] ?? false);
83        $search_sources      = (bool) ($params['search_sources'] ?? false);
84        $search_notes        = (bool) ($params['search_notes'] ?? false);
85
86        // Default to families and individuals only
87        if (!$search_individuals && !$search_families && !$search_repositories && !$search_sources && !$search_notes) {
88            $search_families    = true;
89            $search_individuals = true;
90        }
91
92        // What to search for?
93        $search_terms = $this->extractSearchTerms($query);
94
95        // What trees to search?
96        if (Site::getPreference('ALLOW_CHANGE_GEDCOM') === '1') {
97            $all_trees = $this->tree_service->all();
98        } else {
99            $all_trees = new Collection([$tree]);
100        }
101
102        $search_tree_names = new Collection($params['search_trees'] ?? []);
103
104        $search_trees = $all_trees
105            ->filter(static function (Tree $tree) use ($search_tree_names): bool {
106                return $search_tree_names->containsStrict($tree->name());
107            });
108
109        if ($search_trees->isEmpty()) {
110            $search_trees->add($tree);
111        }
112
113        // Do the search
114        $individuals  = new Collection();
115        $families     = new Collection();
116        $repositories = new Collection();
117        $sources      = new Collection();
118        $notes        = new Collection();
119
120        if ($search_terms !== []) {
121            if ($search_individuals) {
122                $individuals = $this->search_service->searchIndividuals($search_trees->all(), $search_terms);
123            }
124
125            if ($search_families) {
126                $tmp1 = $this->search_service->searchFamilies($search_trees->all(), $search_terms);
127                $tmp2 = $this->search_service->searchFamilyNames($search_trees->all(), $search_terms);
128
129                $families = $tmp1->merge($tmp2)->unique(static function (Family $family): string {
130                    return $family->xref() . '@' . $family->tree()->id();
131                });
132            }
133
134            if ($search_repositories) {
135                $repositories = $this->search_service->searchRepositories($search_trees->all(), $search_terms);
136            }
137
138            if ($search_sources) {
139                $sources = $this->search_service->searchSources($search_trees->all(), $search_terms);
140            }
141
142            if ($search_notes) {
143                $notes = $this->search_service->searchNotes($search_trees->all(), $search_terms);
144            }
145        }
146
147        // If only 1 item is returned, automatically forward to that item
148        if ($individuals->count() === 1 && $families->isEmpty() && $sources->isEmpty() && $notes->isEmpty()) {
149            return redirect($individuals->first()->url());
150        }
151
152        if ($individuals->isEmpty() && $families->count() === 1 && $sources->isEmpty() && $notes->isEmpty()) {
153            return redirect($families->first()->url());
154        }
155
156        if ($individuals->isEmpty() && $families->isEmpty() && $sources->count() === 1 && $notes->isEmpty()) {
157            return redirect($sources->first()->url());
158        }
159
160        if ($individuals->isEmpty() && $families->isEmpty() && $sources->isEmpty() && $notes->count() === 1) {
161            return redirect($notes->first()->url());
162        }
163
164        $title = I18N::translate('General search');
165
166        return $this->viewResponse('search-general-page', [
167            'all_trees'           => $all_trees,
168            'families'            => $families,
169            'individuals'         => $individuals,
170            'notes'               => $notes,
171            'query'               => $query,
172            'repositories'        => $repositories,
173            'search_families'     => $search_families,
174            'search_individuals'  => $search_individuals,
175            'search_notes'        => $search_notes,
176            'search_repositories' => $search_repositories,
177            'search_sources'      => $search_sources,
178            'search_trees'        => $search_trees,
179            'sources'             => $sources,
180            'title'               => $title,
181            'tree'                => $tree,
182        ]);
183    }
184
185    /**
186     * Convert the query into an array of search terms
187     *
188     * @param string $query
189     *
190     * @return array<string>
191     */
192    private function extractSearchTerms(string $query): array
193    {
194        $search_terms = [];
195
196        // Words in double quotes stay together
197        preg_match_all('/"([^"]+)"/', $query, $matches, PREG_SET_ORDER);
198        foreach ($matches as $match) {
199            $search_terms[] = trim($match[1]);
200            // Remove this string from the search query
201            $query = strtr($query, [$match[0] => '']);
202        }
203
204        // Treat CJK characters as separate words, not as characters.
205        $query = preg_replace('/\p{Han}/u', '$0 ', $query);
206
207        // Other words get treated separately
208        preg_match_all('/[\S]+/', $query, $matches, PREG_SET_ORDER);
209        foreach ($matches as $match) {
210            $search_terms[] = $match[0];
211        }
212
213        return $search_terms;
214    }
215}
216