3 * @copyright Copyright (C) 2010-2021, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Module\Search;
24 use Friendica\Content\Nav;
25 use Friendica\Content\Pager;
26 use Friendica\Content\Text\HTML;
27 use Friendica\Content\Widget;
28 use Friendica\Core\Cache\Duration;
29 use Friendica\Core\Logger;
30 use Friendica\Core\Renderer;
31 use Friendica\Core\Search;
32 use Friendica\Core\Session;
33 use Friendica\Database\DBA;
35 use Friendica\Model\Contact;
36 use Friendica\Model\Item;
37 use Friendica\Model\Post;
38 use Friendica\Model\Tag;
39 use Friendica\Module\BaseSearch;
40 use Friendica\Network\HTTPException;
41 use Friendica\Util\Strings;
43 class Index extends BaseSearch
45 public static function content(array $parameters = [])
47 $search = (!empty($_GET['q']) ? Strings::escapeTags(trim(rawurldecode($_GET['q']))) : '');
49 if (DI::config()->get('system', 'block_public') && !Session::isAuthenticated()) {
50 throw new HTTPException\ForbiddenException(DI::l10n()->t('Public access denied.'));
53 if (DI::config()->get('system', 'local_search') && !Session::isAuthenticated()) {
54 $e = new HTTPException\ForbiddenException(DI::l10n()->t('Only logged in users are permitted to perform a search.'));
55 $e->httpdesc = DI::l10n()->t('Public access denied.');
59 if (DI::config()->get('system', 'permit_crawling') && !Session::isAuthenticated()) {
61 // 10 requests are "free", after the 11th only a call per minute is allowed
63 $free_crawls = intval(DI::config()->get('system', 'free_crawls'));
64 if ($free_crawls == 0)
67 $crawl_permit_period = intval(DI::config()->get('system', 'crawl_permit_period'));
68 if ($crawl_permit_period == 0)
69 $crawl_permit_period = 10;
71 $remote = $_SERVER['REMOTE_ADDR'];
72 $result = DI::cache()->get('remote_search:' . $remote);
73 if (!is_null($result)) {
74 $resultdata = json_decode($result);
75 if (($resultdata->time > (time() - $crawl_permit_period)) && ($resultdata->accesses > $free_crawls)) {
76 throw new HTTPException\TooManyRequestsException(DI::l10n()->t('Only one search per minute is permitted for not logged in users.'));
78 DI::cache()->set('remote_search:' . $remote, json_encode(['time' => time(), 'accesses' => $resultdata->accesses + 1]), Duration::HOUR);
80 DI::cache()->set('remote_search:' . $remote, json_encode(['time' => time(), 'accesses' => 1]), Duration::HOUR);
85 DI::page()['aside'] .= Widget\SavedSearches::getHTML(Search::getSearchPath($search), $search);
88 Nav::setSelected('search');
91 if (!empty($_GET['tag'])) {
93 $search = '#' . Strings::escapeTags(trim(rawurldecode($_GET['tag'])));
96 // contruct a wrapper for the search header
97 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('content_wrapper.tpl'), [
98 'name' => 'search-header',
99 '$title' => DI::l10n()->t('Search'),
101 '$content' => HTML::search($search, 'search-box', false)
108 if (strpos($search, '#') === 0) {
110 $search = substr($search, 1);
113 self::tryRedirectToProfile($search);
115 if (strpos($search, '@') === 0 || strpos($search, '!') === 0) {
116 return self::performContactSearch($search);
119 self::tryRedirectToPost($search);
121 if (!empty($_GET['search-option'])) {
122 switch ($_GET['search-option']) {
129 return self::performContactSearch($search, '@');
131 return self::performContactSearch($search, '!');
135 // Don't perform a fulltext or tag search on search results that look like an URL
136 // Tags don't look like an URL and the fulltext search does only work with natural words
137 if (parse_url($search, PHP_URL_SCHEME) && parse_url($search, PHP_URL_HOST)) {
138 Logger::info('Skipping tag and fulltext search since the search looks like a URL.', ['q' => $search]);
139 notice(DI::l10n()->t('No results.'));
143 $tag = $tag || DI::config()->get('system', 'only_tag_search');
145 // Here is the way permissions work in the search module...
146 // Only public posts can be shown
147 // OR your own posts if you are a logged in member
148 // No items will be shown if the member has a blocked profile wall.
150 if (DI::mode()->isMobile()) {
151 $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_mobile_network',
152 DI::config()->get('system', 'itemspage_network_mobile'));
154 $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_network',
155 DI::config()->get('system', 'itemspage_network'));
158 $last_uriid = isset($_GET['last_uriid']) ? intval($_GET['last_uriid']) : 0;
160 $pager = new Pager(DI::l10n(), DI::args()->getQueryString(), $itemsPerPage);
163 Logger::info('Start tag search.', ['q' => $search]);
164 $uriids = Tag::getURIIdListByTag($search, local_user(), $pager->getStart(), $pager->getItemsPerPage(), $last_uriid);
165 $count = Tag::countByTag($search, local_user());
167 Logger::info('Start fulltext search.', ['q' => $search]);
168 $uriids = Post\Content::getURIIdListBySearch($search, local_user(), $pager->getStart(), $pager->getItemsPerPage(), $last_uriid);
169 $count = Post\Content::countBySearch($search, local_user());
172 if (!empty($uriids)) {
173 $condition = ["(`uid` = ? OR (`uid` = ? AND NOT `global`))", 0, local_user()];
174 $condition = DBA::mergeConditions($condition, ['uri-id' => $uriids]);
175 $params = ['order' => ['id' => true]];
176 $items = Post::toArray(Post::selectForUser(local_user(), Item::DISPLAY_FIELDLIST, $condition, $params));
180 if (empty($last_uriid)) {
181 notice(DI::l10n()->t('No results.'));
186 if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll')) {
187 $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
188 $o .= Renderer::replaceMacros($tpl, ['$reload_uri' => DI::args()->getQueryString()]);
192 $title = DI::l10n()->t('Items tagged with: %s', $search);
194 $title = DI::l10n()->t('Results for: %s', $search);
197 $o .= Renderer::replaceMacros(Renderer::getMarkupTemplate('section_title.tpl'), [
201 Logger::info('Start Conversation.', ['q' => $search]);
203 $o .= conversation(DI::app(), $items, 'search', false, false, 'commented', local_user());
205 if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll')) {
206 $o .= HTML::scrollLoader();
208 $o .= $pager->renderMinimal($count);
216 * Tries to redirect to a local profile page based on the input.
218 * This method separates logged in and anonymous users. Logged in users can trigger contact probes to import
219 * non-existing contacts while anonymous users can only trigger a local lookup.
224 * - Any fully-formed URL
226 * @param string $search
227 * @throws HTTPException\InternalServerErrorException
228 * @throws \ImagickException
230 private static function tryRedirectToProfile(string $search)
232 $isUrl = !empty(parse_url($search, PHP_URL_SCHEME));
233 $isAddr = (bool)preg_match('/^@?([a-z0-9.-_]+@[a-z0-9.-_:]+)$/i', trim($search), $matches);
235 if (!$isUrl && !$isAddr) {
240 $search = $matches[1];
244 // User-specific contact URL/address search
245 $contact_id = Contact::getIdForURL($search, local_user());
247 // User-specific contact URL/address search and probe
248 $contact_id = Contact::getIdForURL($search);
251 // Cheaper local lookup for anonymous users, no probe
253 $contact = Contact::selectFirst(['id'], ['addr' => $search, 'uid' => 0]);
255 $contact = Contact::getByURL($search, null, ['id']) ?: ['id' => 0];
258 if (DBA::isResult($contact)) {
259 $contact_id = $contact['id'];
263 if (!empty($contact_id)) {
264 DI::baseUrl()->redirect('contact/' . $contact_id);
269 * Fetch/search a post by URL and redirects to its local representation if it was found.
271 * @param string $search
272 * @throws HTTPException\InternalServerErrorException
274 private static function tryRedirectToPost(string $search)
276 if (parse_url($search, PHP_URL_SCHEME) == '') {
282 $item_id = Item::fetchByLink($search, local_user());
284 // If the user-specific search failed, we search and probe a public post
285 $item_id = Item::fetchByLink($search);
288 // Cheaper local lookup for anonymous users, no probe
289 $item_id = Item::searchByLink($search);
292 if (!empty($item_id)) {
293 $item = Post::selectFirst(['guid'], ['id' => $item_id]);
294 if (DBA::isResult($item)) {
295 DI::baseUrl()->redirect('display/' . $item['guid']);