3 namespace Friendica\Module\Search;
5 use Friendica\App\Arguments;
6 use Friendica\App\BaseURL;
7 use Friendica\Content\Nav;
8 use Friendica\Content\Pager;
9 use Friendica\Content\Text\HTML;
10 use Friendica\Content\Widget;
11 use Friendica\Core\Cache;
12 use Friendica\Core\Cache\Cache as CacheClass;
13 use Friendica\Core\Config;
14 use Friendica\Core\L10n;
15 use Friendica\Core\Logger;
16 use Friendica\Core\Renderer;
17 use Friendica\Core\Session;
18 use Friendica\Database\DBA;
19 use Friendica\Model\Contact;
20 use Friendica\Model\Item;
21 use Friendica\Model\Term;
22 use Friendica\Module\BaseSearchModule;
23 use Friendica\Network\HTTPException;
24 use Friendica\Util\Strings;
26 class Index extends BaseSearchModule
28 public static function content(array $parameters = [])
30 $search = (!empty($_GET['q']) ? Strings::escapeTags(trim(rawurldecode($_GET['q']))) : '');
32 if (Config::get('system', 'block_public') && !Session::isAuthenticated()) {
33 throw new HTTPException\ForbiddenException(L10n::t('Public access denied.'));
36 if (Config::get('system', 'local_search') && !Session::isAuthenticated()) {
37 $e = new HTTPException\ForbiddenException(L10n::t('Only logged in users are permitted to perform a search.'));
38 $e->httpdesc = L10n::t('Public access denied.');
42 /** @var BaseURL $baseURL */
43 $baseURL = self::getClass(BaseURL::class);
45 if (Config::get('system', 'permit_crawling') && !Session::isAuthenticated()) {
47 // 10 requests are "free", after the 11th only a call per minute is allowed
49 $free_crawls = intval(Config::get('system', 'free_crawls'));
50 if ($free_crawls == 0)
53 $crawl_permit_period = intval(Config::get('system', 'crawl_permit_period'));
54 if ($crawl_permit_period == 0)
55 $crawl_permit_period = 10;
57 $remote = $_SERVER['REMOTE_ADDR'];
58 $result = Cache::get('remote_search:' . $remote);
59 if (!is_null($result)) {
60 $resultdata = json_decode($result);
61 if (($resultdata->time > (time() - $crawl_permit_period)) && ($resultdata->accesses > $free_crawls)) {
62 throw new HTTPException\TooManyRequestsException(L10n::t('Only one search per minute is permitted for not logged in users.'));
64 Cache::set('remote_search:' . $remote, json_encode(['time' => time(), 'accesses' => $resultdata->accesses + 1]), CacheClass::HOUR);
66 Cache::set('remote_search:' . $remote, json_encode(['time' => time(), 'accesses' => 1]), CacheClass::HOUR);
71 self::getApp()->page['aside'] .= Widget\SavedSearches::getHTML('search?q=' . urlencode($search), $search);
74 Nav::setSelected('search');
77 if (!empty($_GET['tag'])) {
79 $search = '#' . Strings::escapeTags(trim(rawurldecode($_GET['tag'])));
82 // contruct a wrapper for the search header
83 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('content_wrapper.tpl'), [
84 'name' => 'search-header',
85 '$title' => L10n::t('Search'),
87 '$content' => HTML::search($search, 'search-box', false)
94 if (strpos($search, '#') === 0) {
96 $search = substr($search, 1);
99 self::tryRedirectToProfile($baseURL, $search);
101 if (strpos($search, '@') === 0 || strpos($search, '!') === 0) {
102 return self::performContactSearch($search);
105 self::tryRedirectToPost($baseURL, $search);
107 if (!empty($_GET['search-option'])) {
108 switch ($_GET['search-option']) {
115 return self::performContactSearch($search, '@');
117 return self::performContactSearch($search, '!');
121 $tag = $tag || Config::get('system', 'only_tag_search');
123 // Here is the way permissions work in the search module...
124 // Only public posts can be shown
125 // OR your own posts if you are a logged in member
126 // No items will be shown if the member has a blocked profile wall.
128 /** @var Arguments $args */
129 $args = self::getClass(Arguments::class);
130 $pager = new Pager($args->getQueryString());
133 Logger::info('Start tag search.', ['q' => $search]);
136 "(`uid` = 0 OR (`uid` = ? AND NOT `global`))
137 AND `otype` = ? AND `type` = ? AND `term` = ?",
138 local_user(), Term::OBJECT_TYPE_POST, Term::HASHTAG, $search
141 'order' => ['received' => true],
142 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]
144 $terms = DBA::select('term', ['oid'], $condition, $params);
147 while ($term = DBA::fetch($terms)) {
148 $itemids[] = $term['oid'];
153 if (!empty($itemids)) {
154 $params = ['order' => ['id' => true]];
155 $items = Item::selectForUser(local_user(), [], ['id' => $itemids], $params);
156 $r = Item::inArray($items);
161 Logger::info('Start fulltext search.', ['q' => $search]);
164 "(`uid` = 0 OR (`uid` = ? AND NOT `global`))
165 AND `body` LIKE CONCAT('%',?,'%')",
166 local_user(), $search
169 'order' => ['id' => true],
170 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]
172 $items = Item::selectForUser(local_user(), [], $condition, $params);
173 $r = Item::inArray($items);
176 if (!DBA::isResult($r)) {
177 info(L10n::t('No results.'));
182 $title = L10n::t('Items tagged with: %s', $search);
184 $title = L10n::t('Results for: %s', $search);
187 $o .= Renderer::replaceMacros(Renderer::getMarkupTemplate('section_title.tpl'), [
191 Logger::info('Start Conversation.', ['q' => $search]);
193 $o .= conversation(self::getApp(), $r, $pager, 'search', false, false, 'commented', local_user());
195 $o .= $pager->renderMinimal(count($r));
201 * Tries to redirect to a local profile page based on the input.
203 * This method separates logged in and anonymous users. Logged in users can trigger contact probes to import
204 * non-existing contacts while anonymous users can only trigger a local lookup.
209 * - Any fully-formed URL
211 * @param BaseURL $baseURL
212 * @param string $search
213 * @throws HTTPException\InternalServerErrorException
214 * @throws \ImagickException
216 private static function tryRedirectToProfile(BaseURL $baseURL, string $search)
218 $isUrl = !empty(parse_url($search, PHP_URL_SCHEME));
219 $isAddr = (bool)preg_match('/^@?([a-z0-9.-_]+@[a-z0-9.-_:]+)$/i', trim($search), $matches);
221 if (!$isUrl && !$isAddr) {
226 $search = $matches[1];
230 // User-specific contact URL/address search
231 $contact_id = Contact::getIdForURL($search, local_user());
233 // User-specific contact URL/address search and probe
234 $contact_id = Contact::getIdForURL($search);
237 // Cheaper local lookup for anonymous users, no probe
239 $contact = Contact::selectFirst(['id' => 'cid'], ['addr' => $search, 'uid' => 0]);
241 $contact = Contact::getDetailsByURL($search, 0, ['cid' => 0]);
244 if (DBA::isResult($contact)) {
245 $contact_id = $contact['cid'];
249 if (!empty($contact_id)) {
250 $baseURL->redirect('contact/' . $contact_id);
255 * Fetch/search a post by URL and redirects to its local representation if it was found.
257 * @param BaseURL $baseURL
258 * @param string $search
259 * @throws HTTPException\InternalServerErrorException
261 private static function tryRedirectToPost(BaseURL $baseURL, string $search)
263 if (parse_url($search, PHP_URL_SCHEME) == '') {
269 $item_id = Item::fetchByLink($search, local_user());
271 // If the user-specific search failed, we search and probe a public post
272 $item_id = Item::fetchByLink($search);
275 // Cheaper local lookup for anonymous users, no probe
276 $item_id = Item::searchByLink($search);
279 if (!empty($item_id)) {
280 $item = Item::selectFirst(['guid'], ['id' => $item_id]);
281 if (DBA::isResult($item)) {
282 $baseURL->redirect('display/' . $item['guid']);