xref: /webtrees/app/Http/RequestHandlers/SearchGeneralPage.php (revision 0d047a8c74753c7558a60f4789c838996d6fae8b)
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 array_filter;
35use function assert;
36use function in_array;
37use function preg_replace;
38use function redirect;
39use function trim;
40
41use const PREG_SET_ORDER;
42
43/**
44 * Search for genealogy data
45 */
46class SearchGeneralPage implements RequestHandlerInterface
47{
48    use ViewResponseTrait;
49
50    /** @var SearchService */
51    private $search_service;
52
53    /** @var TreeService */
54    private $tree_service;
55
56    /**
57     * SearchController constructor.
58     *
59     * @param SearchService $search_service
60     * @param TreeService   $tree_service
61     */
62    public function __construct(SearchService $search_service, TreeService $tree_service)
63    {
64        $this->search_service = $search_service;
65        $this->tree_service   = $tree_service;
66    }
67
68    /**
69     * The standard search.
70     *
71     * @param ServerRequestInterface $request
72     *
73     * @return ResponseInterface
74     */
75    public function handle(ServerRequestInterface $request): ResponseInterface
76    {
77        $tree = $request->getAttribute('tree');
78        assert($tree instanceof Tree);
79
80        $params = $request->getQueryParams();
81        $query  = $params['query'] ?? '';
82
83        // What type of records to search?
84        $search_individuals  = (bool) ($params['search_individuals'] ?? false);
85        $search_families     = (bool) ($params['search_families'] ?? false);
86        $search_repositories = (bool) ($params['search_repositories'] ?? false);
87        $search_sources      = (bool) ($params['search_sources'] ?? false);
88        $search_notes        = (bool) ($params['search_notes'] ?? false);
89
90        // Default to families and individuals only
91        if (!$search_individuals && !$search_families && !$search_repositories && !$search_sources && !$search_notes) {
92            $search_families    = true;
93            $search_individuals = true;
94        }
95
96        // What to search for?
97        $search_terms = $this->extractSearchTerms($query);
98
99        // What trees to search?
100        if (Site::getPreference('ALLOW_CHANGE_GEDCOM') === '1') {
101            $all_trees = $this->tree_service->all();
102        } else {
103            $all_trees = new Collection([$tree]);
104        }
105
106        $search_tree_names = new Collection($params['search_trees'] ?? []);
107
108        $search_trees = $all_trees
109            ->filter(static function (Tree $tree) use ($search_tree_names): bool {
110                return $search_tree_names->containsStrict($tree->name());
111            });
112
113        if ($search_trees->isEmpty()) {
114            $search_trees->add($tree);
115        }
116
117        // Do the search
118        $individuals  = new Collection();
119        $families     = new Collection();
120        $repositories = new Collection();
121        $sources      = new Collection();
122        $notes        = new Collection();
123
124        if ($search_terms !== []) {
125            if ($search_individuals) {
126                $individuals = $this->search_service->searchIndividuals($search_trees->all(), $search_terms);
127            }
128
129            if ($search_families) {
130                $tmp1 = $this->search_service->searchFamilies($search_trees->all(), $search_terms);
131                $tmp2 = $this->search_service->searchFamilyNames($search_trees->all(), $search_terms);
132
133                $families = $tmp1->merge($tmp2)->unique(static function (Family $family): string {
134                    return $family->xref() . '@' . $family->tree()->id();
135                });
136            }
137
138            if ($search_repositories) {
139                $repositories = $this->search_service->searchRepositories($search_trees->all(), $search_terms);
140            }
141
142            if ($search_sources) {
143                $sources = $this->search_service->searchSources($search_trees->all(), $search_terms);
144            }
145
146            if ($search_notes) {
147                $notes = $this->search_service->searchNotes($search_trees->all(), $search_terms);
148            }
149        }
150
151        // If only 1 item is returned, automatically forward to that item
152        if ($individuals->count() === 1 && $families->isEmpty() && $sources->isEmpty() && $notes->isEmpty()) {
153            return redirect($individuals->first()->url());
154        }
155
156        if ($individuals->isEmpty() && $families->count() === 1 && $sources->isEmpty() && $notes->isEmpty()) {
157            return redirect($families->first()->url());
158        }
159
160        if ($individuals->isEmpty() && $families->isEmpty() && $sources->count() === 1 && $notes->isEmpty()) {
161            return redirect($sources->first()->url());
162        }
163
164        if ($individuals->isEmpty() && $families->isEmpty() && $sources->isEmpty() && $notes->count() === 1) {
165            return redirect($notes->first()->url());
166        }
167
168        $title = I18N::translate('General search');
169
170        return $this->viewResponse('search-general-page', [
171            'all_trees'           => $all_trees,
172            'families'            => $families,
173            'individuals'         => $individuals,
174            'notes'               => $notes,
175            'query'               => $query,
176            'repositories'        => $repositories,
177            'search_families'     => $search_families,
178            'search_individuals'  => $search_individuals,
179            'search_notes'        => $search_notes,
180            'search_repositories' => $search_repositories,
181            'search_sources'      => $search_sources,
182            'search_trees'        => $search_trees,
183            'sources'             => $sources,
184            'title'               => $title,
185            'tree'                => $tree,
186        ]);
187    }
188
189    /**
190     * Convert the query into an array of search terms
191     *
192     * @param string $query
193     *
194     * @return array<string>
195     */
196    private function extractSearchTerms(string $query): array
197    {
198        $search_terms = [];
199
200        // Words in double quotes stay together
201        preg_match_all('/"([^"]+)"/', $query, $matches, PREG_SET_ORDER);
202        foreach ($matches as $match) {
203            $search_terms[] = trim($match[1]);
204            // Remove this string from the search query
205            $query = strtr($query, [$match[0] => '']);
206        }
207
208        // Treat CJK characters as separate words, not as characters.
209        $query = preg_replace('/\p{Han}/u', '$0 ', $query);
210
211        // Other words get treated separately
212        preg_match_all('/[\S]+/', $query, $matches, PREG_SET_ORDER);
213        foreach ($matches as $match) {
214            $search_terms[] = $match[0];
215        }
216
217        return $search_terms;
218    }
219}
220