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