3 * @copyright Copyright (C) 2020, Friendica
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\Session;
32 use Friendica\Database\DBA;
34 use Friendica\Model\Contact;
35 use Friendica\Model\Item;
36 use Friendica\Model\Term;
37 use Friendica\Module\BaseSearch;
38 use Friendica\Network\HTTPException;
39 use Friendica\Util\Strings;
41 class Index extends BaseSearch
43 public static function content(array $parameters = [])
45 $search = (!empty($_GET['q']) ? Strings::escapeTags(trim(rawurldecode($_GET['q']))) : '');
47 if (DI::config()->get('system', 'block_public') && !Session::isAuthenticated()) {
48 throw new HTTPException\ForbiddenException(DI::l10n()->t('Public access denied.'));
51 if (DI::config()->get('system', 'local_search') && !Session::isAuthenticated()) {
52 $e = new HTTPException\ForbiddenException(DI::l10n()->t('Only logged in users are permitted to perform a search.'));
53 $e->httpdesc = DI::l10n()->t('Public access denied.');
57 if (DI::config()->get('system', 'permit_crawling') && !Session::isAuthenticated()) {
59 // 10 requests are "free", after the 11th only a call per minute is allowed
61 $free_crawls = intval(DI::config()->get('system', 'free_crawls'));
62 if ($free_crawls == 0)
65 $crawl_permit_period = intval(DI::config()->get('system', 'crawl_permit_period'));
66 if ($crawl_permit_period == 0)
67 $crawl_permit_period = 10;
69 $remote = $_SERVER['REMOTE_ADDR'];
70 $result = DI::cache()->get('remote_search:' . $remote);
71 if (!is_null($result)) {
72 $resultdata = json_decode($result);
73 if (($resultdata->time > (time() - $crawl_permit_period)) && ($resultdata->accesses > $free_crawls)) {
74 throw new HTTPException\TooManyRequestsException(DI::l10n()->t('Only one search per minute is permitted for not logged in users.'));
76 DI::cache()->set('remote_search:' . $remote, json_encode(['time' => time(), 'accesses' => $resultdata->accesses + 1]), Duration::HOUR);
78 DI::cache()->set('remote_search:' . $remote, json_encode(['time' => time(), 'accesses' => 1]), Duration::HOUR);
83 DI::page()['aside'] .= Widget\SavedSearches::getHTML('search?q=' . urlencode($search), $search);
86 Nav::setSelected('search');
89 if (!empty($_GET['tag'])) {
91 $search = '#' . Strings::escapeTags(trim(rawurldecode($_GET['tag'])));
94 // contruct a wrapper for the search header
95 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('content_wrapper.tpl'), [
96 'name' => 'search-header',
97 '$title' => DI::l10n()->t('Search'),
99 '$content' => HTML::search($search, 'search-box', false)
106 if (strpos($search, '#') === 0) {
108 $search = substr($search, 1);
111 self::tryRedirectToProfile($search);
113 if (strpos($search, '@') === 0 || strpos($search, '!') === 0) {
114 return self::performContactSearch($search);
117 self::tryRedirectToPost($search);
119 if (!empty($_GET['search-option'])) {
120 switch ($_GET['search-option']) {
127 return self::performContactSearch($search, '@');
129 return self::performContactSearch($search, '!');
133 $tag = $tag || DI::config()->get('system', 'only_tag_search');
135 // Here is the way permissions work in the search module...
136 // Only public posts can be shown
137 // OR your own posts if you are a logged in member
138 // No items will be shown if the member has a blocked profile wall.
140 $pager = new Pager(DI::args()->getQueryString());
143 Logger::info('Start tag search.', ['q' => $search]);
146 "(`uid` = 0 OR (`uid` = ? AND NOT `global`))
147 AND `otype` = ? AND `type` = ? AND `term` = ?",
148 local_user(), Term::OBJECT_TYPE_POST, Term::HASHTAG, $search
151 'order' => ['received' => true],
152 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]
154 $terms = DBA::select('term', ['oid'], $condition, $params);
157 while ($term = DBA::fetch($terms)) {
158 $itemids[] = $term['oid'];
163 if (!empty($itemids)) {
164 $params = ['order' => ['id' => true]];
165 $items = Item::selectForUser(local_user(), [], ['id' => $itemids], $params);
166 $r = Item::inArray($items);
171 Logger::info('Start fulltext search.', ['q' => $search]);
174 "(`uid` = 0 OR (`uid` = ? AND NOT `global`))
175 AND `body` LIKE CONCAT('%',?,'%')",
176 local_user(), $search
179 'order' => ['id' => true],
180 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]
182 $items = Item::selectForUser(local_user(), [], $condition, $params);
183 $r = Item::inArray($items);
186 if (!DBA::isResult($r)) {
187 info(DI::l10n()->t('No results.'));
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(), $r, 'search', false, false, 'commented', local_user());
205 $o .= $pager->renderMinimal(count($r));
211 * Tries to redirect to a local profile page based on the input.
213 * This method separates logged in and anonymous users. Logged in users can trigger contact probes to import
214 * non-existing contacts while anonymous users can only trigger a local lookup.
219 * - Any fully-formed URL
221 * @param string $search
222 * @throws HTTPException\InternalServerErrorException
223 * @throws \ImagickException
225 private static function tryRedirectToProfile(string $search)
227 $isUrl = !empty(parse_url($search, PHP_URL_SCHEME));
228 $isAddr = (bool)preg_match('/^@?([a-z0-9.-_]+@[a-z0-9.-_:]+)$/i', trim($search), $matches);
230 if (!$isUrl && !$isAddr) {
235 $search = $matches[1];
239 // User-specific contact URL/address search
240 $contact_id = Contact::getIdForURL($search, local_user());
242 // User-specific contact URL/address search and probe
243 $contact_id = Contact::getIdForURL($search);
246 // Cheaper local lookup for anonymous users, no probe
248 $contact = Contact::selectFirst(['id' => 'cid'], ['addr' => $search, 'uid' => 0]);
250 $contact = Contact::getDetailsByURL($search, 0, ['cid' => 0]);
253 if (DBA::isResult($contact)) {
254 $contact_id = $contact['cid'];
258 if (!empty($contact_id)) {
259 DI::baseUrl()->redirect('contact/' . $contact_id);
264 * Fetch/search a post by URL and redirects to its local representation if it was found.
266 * @param string $search
267 * @throws HTTPException\InternalServerErrorException
269 private static function tryRedirectToPost(string $search)
271 if (parse_url($search, PHP_URL_SCHEME) == '') {
277 $item_id = Item::fetchByLink($search, local_user());
279 // If the user-specific search failed, we search and probe a public post
280 $item_id = Item::fetchByLink($search);
283 // Cheaper local lookup for anonymous users, no probe
284 $item_id = Item::searchByLink($search);
287 if (!empty($item_id)) {
288 $item = Item::selectFirst(['guid'], ['id' => $item_id]);
289 if (DBA::isResult($item)) {
290 DI::baseUrl()->redirect('display/' . $item['guid']);