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