3 namespace Friendica\Module\Search;
5 use Friendica\Content\Nav;
6 use Friendica\Content\Pager;
7 use Friendica\Content\Text\HTML;
8 use Friendica\Content\Widget;
9 use Friendica\Core\Cache\Cache as CacheClass;
10 use Friendica\Core\Config;
11 use Friendica\Core\L10n;
12 use Friendica\Core\Logger;
13 use Friendica\Core\Renderer;
14 use Friendica\Core\Session;
15 use Friendica\Database\DBA;
17 use Friendica\Model\Contact;
18 use Friendica\Model\Item;
19 use Friendica\Model\Term;
20 use Friendica\Module\BaseSearchModule;
21 use Friendica\Network\HTTPException;
22 use Friendica\Util\Strings;
24 class Index extends BaseSearchModule
26 public static function content(array $parameters = [])
28 $search = (!empty($_GET['q']) ? Strings::escapeTags(trim(rawurldecode($_GET['q']))) : '');
30 if (Config::get('system', 'block_public') && !Session::isAuthenticated()) {
31 throw new HTTPException\ForbiddenException(L10n::t('Public access denied.'));
34 if (Config::get('system', 'local_search') && !Session::isAuthenticated()) {
35 $e = new HTTPException\ForbiddenException(L10n::t('Only logged in users are permitted to perform a search.'));
36 $e->httpdesc = L10n::t('Public access denied.');
40 if (Config::get('system', 'permit_crawling') && !Session::isAuthenticated()) {
42 // 10 requests are "free", after the 11th only a call per minute is allowed
44 $free_crawls = intval(Config::get('system', 'free_crawls'));
45 if ($free_crawls == 0)
48 $crawl_permit_period = intval(Config::get('system', 'crawl_permit_period'));
49 if ($crawl_permit_period == 0)
50 $crawl_permit_period = 10;
52 $remote = $_SERVER['REMOTE_ADDR'];
53 $result = DI::cache()->get('remote_search:' . $remote);
54 if (!is_null($result)) {
55 $resultdata = json_decode($result);
56 if (($resultdata->time > (time() - $crawl_permit_period)) && ($resultdata->accesses > $free_crawls)) {
57 throw new HTTPException\TooManyRequestsException(L10n::t('Only one search per minute is permitted for not logged in users.'));
59 DI::cache()->set('remote_search:' . $remote, json_encode(['time' => time(), 'accesses' => $resultdata->accesses + 1]), CacheClass::HOUR);
61 DI::cache()->set('remote_search:' . $remote, json_encode(['time' => time(), 'accesses' => 1]), CacheClass::HOUR);
66 DI::page()['aside'] .= Widget\SavedSearches::getHTML('search?q=' . urlencode($search), $search);
69 Nav::setSelected('search');
72 if (!empty($_GET['tag'])) {
74 $search = '#' . Strings::escapeTags(trim(rawurldecode($_GET['tag'])));
77 // contruct a wrapper for the search header
78 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('content_wrapper.tpl'), [
79 'name' => 'search-header',
80 '$title' => L10n::t('Search'),
82 '$content' => HTML::search($search, 'search-box', false)
89 if (strpos($search, '#') === 0) {
91 $search = substr($search, 1);
94 self::tryRedirectToProfile($search);
96 if (strpos($search, '@') === 0 || strpos($search, '!') === 0) {
97 return self::performContactSearch($search);
100 self::tryRedirectToPost($search);
102 if (!empty($_GET['search-option'])) {
103 switch ($_GET['search-option']) {
110 return self::performContactSearch($search, '@');
112 return self::performContactSearch($search, '!');
116 $tag = $tag || Config::get('system', 'only_tag_search');
118 // Here is the way permissions work in the search module...
119 // Only public posts can be shown
120 // OR your own posts if you are a logged in member
121 // No items will be shown if the member has a blocked profile wall.
123 $pager = new Pager(DI::args()->getQueryString());
126 Logger::info('Start tag search.', ['q' => $search]);
129 "(`uid` = 0 OR (`uid` = ? AND NOT `global`))
130 AND `otype` = ? AND `type` = ? AND `term` = ?",
131 local_user(), Term::OBJECT_TYPE_POST, Term::HASHTAG, $search
134 'order' => ['received' => true],
135 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]
137 $terms = DBA::select('term', ['oid'], $condition, $params);
140 while ($term = DBA::fetch($terms)) {
141 $itemids[] = $term['oid'];
146 if (!empty($itemids)) {
147 $params = ['order' => ['id' => true]];
148 $items = Item::selectForUser(local_user(), [], ['id' => $itemids], $params);
149 $r = Item::inArray($items);
154 Logger::info('Start fulltext search.', ['q' => $search]);
157 "(`uid` = 0 OR (`uid` = ? AND NOT `global`))
158 AND `body` LIKE CONCAT('%',?,'%')",
159 local_user(), $search
162 'order' => ['id' => true],
163 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]
165 $items = Item::selectForUser(local_user(), [], $condition, $params);
166 $r = Item::inArray($items);
169 if (!DBA::isResult($r)) {
170 info(L10n::t('No results.'));
175 $title = L10n::t('Items tagged with: %s', $search);
177 $title = L10n::t('Results for: %s', $search);
180 $o .= Renderer::replaceMacros(Renderer::getMarkupTemplate('section_title.tpl'), [
184 Logger::info('Start Conversation.', ['q' => $search]);
186 $o .= conversation(DI::app(), $r, $pager, 'search', false, false, 'commented', local_user());
188 $o .= $pager->renderMinimal(count($r));
194 * Tries to redirect to a local profile page based on the input.
196 * This method separates logged in and anonymous users. Logged in users can trigger contact probes to import
197 * non-existing contacts while anonymous users can only trigger a local lookup.
202 * - Any fully-formed URL
204 * @param string $search
205 * @throws HTTPException\InternalServerErrorException
206 * @throws \ImagickException
208 private static function tryRedirectToProfile(string $search)
210 $isUrl = !empty(parse_url($search, PHP_URL_SCHEME));
211 $isAddr = (bool)preg_match('/^@?([a-z0-9.-_]+@[a-z0-9.-_:]+)$/i', trim($search), $matches);
213 if (!$isUrl && !$isAddr) {
218 $search = $matches[1];
222 // User-specific contact URL/address search
223 $contact_id = Contact::getIdForURL($search, local_user());
225 // User-specific contact URL/address search and probe
226 $contact_id = Contact::getIdForURL($search);
229 // Cheaper local lookup for anonymous users, no probe
231 $contact = Contact::selectFirst(['id' => 'cid'], ['addr' => $search, 'uid' => 0]);
233 $contact = Contact::getDetailsByURL($search, 0, ['cid' => 0]);
236 if (DBA::isResult($contact)) {
237 $contact_id = $contact['cid'];
241 if (!empty($contact_id)) {
242 DI::baseUrl()->redirect('contact/' . $contact_id);
247 * Fetch/search a post by URL and redirects to its local representation if it was found.
249 * @param string $search
250 * @throws HTTPException\InternalServerErrorException
252 private static function tryRedirectToPost(string $search)
254 if (parse_url($search, PHP_URL_SCHEME) == '') {
260 $item_id = Item::fetchByLink($search, local_user());
262 // If the user-specific search failed, we search and probe a public post
263 $item_id = Item::fetchByLink($search);
266 // Cheaper local lookup for anonymous users, no probe
267 $item_id = Item::searchByLink($search);
270 if (!empty($item_id)) {
271 $item = Item::selectFirst(['guid'], ['id' => $item_id]);
272 if (DBA::isResult($item)) {
273 DI::baseUrl()->redirect('display/' . $item['guid']);