3 * @copyright Copyright (C) 2010-2022, 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\Nav;
26 use Friendica\Content\Pager;
27 use Friendica\Content\Text\HTML;
28 use Friendica\Content\Widget;
29 use Friendica\Core\Cache\Enum\Duration;
30 use Friendica\Core\L10n;
31 use Friendica\Core\Logger;
32 use Friendica\Core\Renderer;
33 use Friendica\Core\Search;
34 use Friendica\Database\DBA;
36 use Friendica\Model\Contact;
37 use Friendica\Model\Item;
38 use Friendica\Model\Post;
39 use Friendica\Model\Tag;
40 use Friendica\Module\BaseSearch;
41 use Friendica\Module\Response;
42 use Friendica\Network\HTTPException;
43 use Friendica\Util\Network;
44 use Friendica\Util\Profiler;
45 use Psr\Log\LoggerInterface;
47 class Index extends BaseSearch
50 private $remoteAddress;
52 public function __construct(L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, Response $response, App\Request $request, array $server, array $parameters = [])
54 parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
56 $this->remoteAddress = $request->getRemoteAddress();
59 protected function content(array $request = []): string
61 $search = (!empty($_GET['q']) ? trim(rawurldecode($_GET['q'])) : '');
63 if (DI::config()->get('system', 'block_public') && !DI::userSession()->isAuthenticated()) {
64 throw new HTTPException\ForbiddenException(DI::l10n()->t('Public access denied.'));
67 if (DI::config()->get('system', 'local_search') && !DI::userSession()->isAuthenticated()) {
68 throw new HTTPException\ForbiddenException(DI::l10n()->t('Only logged in users are permitted to perform a search.'));
71 if (DI::config()->get('system', 'permit_crawling') && !DI::userSession()->isAuthenticated()) {
73 // 10 requests are "free", after the 11th only a call per minute is allowed
75 $free_crawls = intval(DI::config()->get('system', 'free_crawls'));
76 if ($free_crawls == 0)
79 $crawl_permit_period = intval(DI::config()->get('system', 'crawl_permit_period'));
80 if ($crawl_permit_period == 0)
81 $crawl_permit_period = 10;
83 $remote = $this->remoteAddress;
84 $result = DI::cache()->get('remote_search:' . $remote);
85 if (!is_null($result)) {
86 $resultdata = json_decode($result);
87 if (($resultdata->time > (time() - $crawl_permit_period)) && ($resultdata->accesses > $free_crawls)) {
88 throw new HTTPException\TooManyRequestsException(DI::l10n()->t('Only one search per minute is permitted for not logged in users.'));
90 DI::cache()->set('remote_search:' . $remote, json_encode(['time' => time(), 'accesses' => $resultdata->accesses + 1]), Duration::HOUR);
92 DI::cache()->set('remote_search:' . $remote, json_encode(['time' => time(), 'accesses' => 1]), Duration::HOUR);
96 if (DI::userSession()->getLocalUserId()) {
97 DI::page()['aside'] .= Widget\SavedSearches::getHTML(Search::getSearchPath($search), $search);
100 Nav::setSelected('search');
103 if (!empty($_GET['tag'])) {
105 $search = '#' . trim(rawurldecode($_GET['tag']));
108 // contruct a wrapper for the search header
109 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('content_wrapper.tpl'), [
110 'name' => 'search-header',
111 '$title' => DI::l10n()->t('Search'),
113 '$content' => HTML::search($search, 'search-box', false)
120 if (strpos($search, '#') === 0) {
122 $search = substr($search, 1);
124 if (strpos($search, '@') === 0 || strpos($search, '!') === 0) {
125 return self::performContactSearch($search);
128 self::tryRedirectToPost($search);
130 self::tryRedirectToProfile($search);
132 if (!empty($_GET['search-option'])) {
133 switch ($_GET['search-option']) {
140 return self::performContactSearch($search, '@');
142 return self::performContactSearch($search, '!');
147 // Don't perform a fulltext or tag search on search results that look like an URL
148 // Tags don't look like an URL and the fulltext search does only work with natural words
149 if (parse_url($search, PHP_URL_SCHEME) && parse_url($search, PHP_URL_HOST)) {
150 Logger::info('Skipping tag and fulltext search since the search looks like a URL.', ['q' => $search]);
151 DI::sysmsg()->addNotice(DI::l10n()->t('No results.'));
155 $tag = $tag || DI::config()->get('system', 'only_tag_search');
157 // Here is the way permissions work in the search module...
158 // Only public posts can be shown
159 // OR your own posts if you are a logged in member
160 // No items will be shown if the member has a blocked profile wall.
162 if (DI::mode()->isMobile()) {
163 $itemsPerPage = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'itemspage_mobile_network',
164 DI::config()->get('system', 'itemspage_network_mobile'));
166 $itemsPerPage = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'itemspage_network',
167 DI::config()->get('system', 'itemspage_network'));
170 $last_uriid = isset($_GET['last_uriid']) ? intval($_GET['last_uriid']) : 0;
172 $pager = new Pager(DI::l10n(), DI::args()->getQueryString(), $itemsPerPage);
175 Logger::info('Start tag search.', ['q' => $search]);
176 $uriids = Tag::getURIIdListByTag($search, DI::userSession()->getLocalUserId(), $pager->getStart(), $pager->getItemsPerPage(), $last_uriid);
177 $count = Tag::countByTag($search, DI::userSession()->getLocalUserId());
179 Logger::info('Start fulltext search.', ['q' => $search]);
180 $uriids = Post\Content::getURIIdListBySearch($search, DI::userSession()->getLocalUserId(), $pager->getStart(), $pager->getItemsPerPage(), $last_uriid);
181 $count = Post\Content::countBySearch($search, DI::userSession()->getLocalUserId());
184 if (!empty($uriids)) {
185 $condition = ["(`uid` = ? OR (`uid` = ? AND NOT `global`))", 0, DI::userSession()->getLocalUserId()];
186 $condition = DBA::mergeConditions($condition, ['uri-id' => $uriids]);
187 $params = ['order' => ['id' => true]];
188 $items = Post::toArray(Post::selectForUser(DI::userSession()->getLocalUserId(), Item::DISPLAY_FIELDLIST, $condition, $params));
192 if (empty($last_uriid)) {
193 DI::sysmsg()->addNotice(DI::l10n()->t('No results.'));
198 if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'infinite_scroll')) {
199 $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
200 $o .= Renderer::replaceMacros($tpl, ['$reload_uri' => DI::args()->getQueryString()]);
204 $title = DI::l10n()->t('Items tagged with: %s', $search);
206 $title = DI::l10n()->t('Results for: %s', $search);
209 $o .= Renderer::replaceMacros(Renderer::getMarkupTemplate('section_title.tpl'), [
213 Logger::info('Start Conversation.', ['q' => $search]);
215 $o .= DI::conversation()->create($items, 'search', false, false, 'commented', DI::userSession()->getLocalUserId());
217 if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'infinite_scroll')) {
218 $o .= HTML::scrollLoader();
220 $o .= $pager->renderMinimal($count);
228 * Tries to redirect to a local profile page based on the input.
230 * This method separates logged in and anonymous users. Logged in users can trigger contact probes to import
231 * non-existing contacts while anonymous users can only trigger a local lookup.
236 * - Any fully-formed URL
238 * @param string $search
239 * @throws HTTPException\InternalServerErrorException
240 * @throws \ImagickException
242 private static function tryRedirectToProfile(string $search)
244 $search = Network::convertToIdn($search);
245 $isUrl = !empty(parse_url($search, PHP_URL_SCHEME));
246 $isAddr = (bool)preg_match('/^@?([a-z0-9.-_]+@[a-z0-9.-_:]+)$/i', trim($search), $matches);
248 if (!$isUrl && !$isAddr) {
253 $search = $matches[1];
256 if (DI::userSession()->getLocalUserId()) {
257 // User-specific contact URL/address search
258 $contact_id = Contact::getIdForURL($search, DI::userSession()->getLocalUserId());
260 // User-specific contact URL/address search and probe
261 $contact_id = Contact::getIdForURL($search);
264 // Cheaper local lookup for anonymous users, no probe
266 $contact = Contact::selectFirst(['id'], ['addr' => $search, 'uid' => 0]);
268 $contact = Contact::getByURL($search, null, ['id']) ?: ['id' => 0];
271 if (DBA::isResult($contact)) {
272 $contact_id = $contact['id'];
276 if (!empty($contact_id)) {
277 DI::baseUrl()->redirect('contact/' . $contact_id);
282 * Fetch/search a post by URL and redirects to its local representation if it was found.
284 * @param string $search
285 * @throws HTTPException\InternalServerErrorException
287 private static function tryRedirectToPost(string $search)
289 if (parse_url($search, PHP_URL_SCHEME) == '') {
293 $search = Network::convertToIdn($search);
295 if (DI::userSession()->getLocalUserId()) {
297 $item_id = Item::fetchByLink($search, DI::userSession()->getLocalUserId());
299 // If the user-specific search failed, we search and probe a public post
300 $item_id = Item::fetchByLink($search);
303 // Cheaper local lookup for anonymous users, no probe
304 $item_id = Item::searchByLink($search);
307 if (!empty($item_id)) {
308 $item = Post::selectFirst(['guid'], ['id' => $item_id]);
309 if (DBA::isResult($item)) {
310 DI::baseUrl()->redirect('display/' . $item['guid']);