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