3 * @copyright Copyright (C) 2010-2023, 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;
25 use Friendica\Content\Conversation;
26 use Friendica\Content\Nav;
27 use Friendica\Content\Pager;
28 use Friendica\Content\Text\HTML;
29 use Friendica\Content\Widget;
30 use Friendica\Core\Cache\Enum\Duration;
31 use Friendica\Core\L10n;
32 use Friendica\Core\Logger;
33 use Friendica\Core\Renderer;
34 use Friendica\Core\Search;
35 use Friendica\Database\DBA;
37 use Friendica\Model\Contact;
38 use Friendica\Model\Item;
39 use Friendica\Model\Post;
40 use Friendica\Model\Tag;
41 use Friendica\Module\BaseSearch;
42 use Friendica\Module\Response;
43 use Friendica\Network\HTTPException;
44 use Friendica\Util\Network;
45 use Friendica\Util\Profiler;
46 use Psr\Log\LoggerInterface;
48 class Index extends BaseSearch
51 private $remoteAddress;
53 public function __construct(L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, Response $response, App\Request $request, array $server, array $parameters = [])
55 parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
57 $this->remoteAddress = $request->getRemoteAddress();
60 protected function content(array $request = []): string
62 $search = (!empty($_GET['q']) ? trim(rawurldecode($_GET['q'])) : '');
64 if (DI::config()->get('system', 'block_public') && !DI::userSession()->isAuthenticated()) {
65 throw new HTTPException\ForbiddenException(DI::l10n()->t('Public access denied.'));
68 if (DI::config()->get('system', 'local_search') && !DI::userSession()->isAuthenticated()) {
69 throw new HTTPException\ForbiddenException(DI::l10n()->t('Only logged in users are permitted to perform a search.'));
72 if (DI::config()->get('system', 'permit_crawling') && !DI::userSession()->isAuthenticated()) {
74 // 10 requests are "free", after the 11th only a call per minute is allowed
76 $free_crawls = intval(DI::config()->get('system', 'free_crawls'));
77 if ($free_crawls == 0)
80 $crawl_permit_period = intval(DI::config()->get('system', 'crawl_permit_period'));
81 if ($crawl_permit_period == 0)
82 $crawl_permit_period = 10;
84 $remote = $this->remoteAddress;
85 $result = DI::cache()->get('remote_search:' . $remote);
86 if (!is_null($result)) {
87 $resultdata = json_decode($result);
88 if (($resultdata->time > (time() - $crawl_permit_period)) && ($resultdata->accesses > $free_crawls)) {
89 throw new HTTPException\TooManyRequestsException(DI::l10n()->t('Only one search per minute is permitted for not logged in users.'));
91 DI::cache()->set('remote_search:' . $remote, json_encode(['time' => time(), 'accesses' => $resultdata->accesses + 1]), Duration::HOUR);
93 DI::cache()->set('remote_search:' . $remote, json_encode(['time' => time(), 'accesses' => 1]), Duration::HOUR);
97 if (DI::userSession()->getLocalUserId()) {
98 DI::page()['aside'] .= Widget\SavedSearches::getHTML(Search::getSearchPath($search), $search);
101 Nav::setSelected('search');
104 if (!empty($_GET['tag'])) {
106 $search = '#' . trim(rawurldecode($_GET['tag']));
109 // contruct a wrapper for the search header
110 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('content_wrapper.tpl'), [
111 'name' => 'search-header',
112 '$title' => DI::l10n()->t('Search'),
114 '$content' => HTML::search($search, 'search-box', false)
121 if (strpos($search, '#') === 0) {
123 $search = substr($search, 1);
125 if (strpos($search, '@') === 0 || strpos($search, '!') === 0) {
126 return self::performContactSearch($search);
129 self::tryRedirectToPost($search);
131 self::tryRedirectToProfile($search);
133 if (!empty($_GET['search-option'])) {
134 switch ($_GET['search-option']) {
141 return self::performContactSearch($search, '@');
143 return self::performContactSearch($search, '!');
148 // Don't perform a fulltext or tag search on search results that look like an URL
149 // Tags don't look like an URL and the fulltext search does only work with natural words
150 if (parse_url($search, PHP_URL_SCHEME) && parse_url($search, PHP_URL_HOST)) {
151 Logger::info('Skipping tag and fulltext search since the search looks like a URL.', ['q' => $search]);
152 DI::sysmsg()->addNotice(DI::l10n()->t('No results.'));
156 $tag = $tag || DI::config()->get('system', 'only_tag_search');
158 // Here is the way permissions work in the search module...
159 // Only public posts can be shown
160 // OR your own posts if you are a logged in member
161 // No items will be shown if the member has a blocked profile wall.
163 if (DI::mode()->isMobile()) {
164 $itemsPerPage = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'itemspage_mobile_network',
165 DI::config()->get('system', 'itemspage_network_mobile'));
167 $itemsPerPage = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'itemspage_network',
168 DI::config()->get('system', 'itemspage_network'));
171 $last_uriid = isset($_GET['last_uriid']) ? intval($_GET['last_uriid']) : 0;
173 $pager = new Pager(DI::l10n(), DI::args()->getQueryString(), $itemsPerPage);
176 Logger::info('Start tag search.', ['q' => $search]);
177 $uriids = Tag::getURIIdListByTag($search, DI::userSession()->getLocalUserId(), $pager->getStart(), $pager->getItemsPerPage(), $last_uriid);
178 $count = Tag::countByTag($search, DI::userSession()->getLocalUserId());
180 Logger::info('Start fulltext search.', ['q' => $search]);
181 $uriids = Post\Content::getURIIdListBySearch($search, DI::userSession()->getLocalUserId(), $pager->getStart(), $pager->getItemsPerPage(), $last_uriid);
182 $count = Post\Content::countBySearch($search, DI::userSession()->getLocalUserId());
185 if (!empty($uriids)) {
186 $condition = ["(`uid` = ? OR (`uid` = ? AND NOT `global`))", 0, DI::userSession()->getLocalUserId()];
187 $condition = DBA::mergeConditions($condition, ['uri-id' => $uriids]);
188 $params = ['order' => ['id' => true]];
189 $items = Post::toArray(Post::selectForUser(DI::userSession()->getLocalUserId(), Item::DISPLAY_FIELDLIST, $condition, $params));
193 if (empty($last_uriid)) {
194 DI::sysmsg()->addNotice(DI::l10n()->t('No results.'));
199 if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'infinite_scroll')) {
200 $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
201 $o .= Renderer::replaceMacros($tpl, ['$reload_uri' => DI::args()->getQueryString()]);
205 $title = DI::l10n()->t('Items tagged with: %s', $search);
207 $title = DI::l10n()->t('Results for: %s', $search);
210 $o .= Renderer::replaceMacros(Renderer::getMarkupTemplate('section_title.tpl'), [
214 Logger::info('Start Conversation.', ['q' => $search]);
216 $o .= DI::conversation()->create($items, Conversation::MODE_SEARCH, false, false, 'commented', DI::userSession()->getLocalUserId());
218 if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'infinite_scroll')) {
219 $o .= HTML::scrollLoader();
221 $o .= $pager->renderMinimal($count);
229 * Tries to redirect to a local profile page based on the input.
231 * This method separates logged in and anonymous users. Logged in users can trigger contact probes to import
232 * non-existing contacts while anonymous users can only trigger a local lookup.
237 * - Any fully-formed URL
239 * @param string $search
240 * @throws HTTPException\InternalServerErrorException
241 * @throws \ImagickException
243 private static function tryRedirectToProfile(string $search)
245 $search = Network::convertToIdn($search);
246 $isUrl = !empty(parse_url($search, PHP_URL_SCHEME));
247 $isAddr = (bool)preg_match('/^@?([a-z0-9.-_]+@[a-z0-9.-_:]+)$/i', trim($search), $matches);
249 if (!$isUrl && !$isAddr) {
254 $search = $matches[1];
257 if (DI::userSession()->getLocalUserId()) {
258 // User-specific contact URL/address search
259 $contact_id = Contact::getIdForURL($search, DI::userSession()->getLocalUserId());
261 // User-specific contact URL/address search and probe
262 $contact_id = Contact::getIdForURL($search);
265 // Cheaper local lookup for anonymous users, no probe
267 $contact = Contact::selectFirst(['id'], ['addr' => $search, 'uid' => 0]);
269 $contact = Contact::getByURL($search, null, ['id']) ?: ['id' => 0];
272 if (DBA::isResult($contact)) {
273 $contact_id = $contact['id'];
277 if (!empty($contact_id)) {
278 DI::baseUrl()->redirect('contact/' . $contact_id);
283 * Fetch/search a post by URL and redirects to its local representation if it was found.
285 * @param string $search
286 * @throws HTTPException\InternalServerErrorException
288 private static function tryRedirectToPost(string $search)
290 if (parse_url($search, PHP_URL_SCHEME) == '') {
294 $search = Network::convertToIdn($search);
296 if (DI::userSession()->getLocalUserId()) {
298 $item_id = Item::fetchByLink($search, DI::userSession()->getLocalUserId());
300 // If the user-specific search failed, we search and probe a public post
301 $item_id = Item::fetchByLink($search);
304 // Cheaper local lookup for anonymous users, no probe
305 $item_id = Item::searchByLink($search);
308 if (!empty($item_id)) {
309 $item = Post::selectFirst(['guid'], ['id' => $item_id]);
310 if (DBA::isResult($item)) {
311 DI::baseUrl()->redirect('display/' . $item['guid']);