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;
20 use Friendica\Model\Contact;
21 use Friendica\Model\Item;
22 use Friendica\Model\Term;
23 use Friendica\Module\BaseSearchModule;
24 use Friendica\Network\HTTPException;
25 use Friendica\Util\Strings;
27 class Index extends BaseSearchModule
29 public static function content(array $parameters = [])
31 $search = (!empty($_GET['q']) ? Strings::escapeTags(trim(rawurldecode($_GET['q']))) : '');
33 if (Config::get('system', 'block_public') && !Session::isAuthenticated()) {
34 throw new HTTPException\ForbiddenException(L10n::t('Public access denied.'));
37 if (Config::get('system', 'local_search') && !Session::isAuthenticated()) {
38 $e = new HTTPException\ForbiddenException(L10n::t('Only logged in users are permitted to perform a search.'));
39 $e->httpdesc = L10n::t('Public access denied.');
43 if (Config::get('system', 'permit_crawling') && !Session::isAuthenticated()) {
45 // 10 requests are "free", after the 11th only a call per minute is allowed
47 $free_crawls = intval(Config::get('system', 'free_crawls'));
48 if ($free_crawls == 0)
51 $crawl_permit_period = intval(Config::get('system', 'crawl_permit_period'));
52 if ($crawl_permit_period == 0)
53 $crawl_permit_period = 10;
55 $remote = $_SERVER['REMOTE_ADDR'];
56 $result = Cache::get('remote_search:' . $remote);
57 if (!is_null($result)) {
58 $resultdata = json_decode($result);
59 if (($resultdata->time > (time() - $crawl_permit_period)) && ($resultdata->accesses > $free_crawls)) {
60 throw new HTTPException\TooManyRequestsException(L10n::t('Only one search per minute is permitted for not logged in users.'));
62 Cache::set('remote_search:' . $remote, json_encode(['time' => time(), 'accesses' => $resultdata->accesses + 1]), CacheClass::HOUR);
64 Cache::set('remote_search:' . $remote, json_encode(['time' => time(), 'accesses' => 1]), CacheClass::HOUR);
69 DI::app()->page['aside'] .= Widget\SavedSearches::getHTML('search?q=' . urlencode($search), $search);
72 Nav::setSelected('search');
75 if (!empty($_GET['tag'])) {
77 $search = '#' . Strings::escapeTags(trim(rawurldecode($_GET['tag'])));
80 // contruct a wrapper for the search header
81 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('content_wrapper.tpl'), [
82 'name' => 'search-header',
83 '$title' => L10n::t('Search'),
85 '$content' => HTML::search($search, 'search-box', false)
92 if (strpos($search, '#') === 0) {
94 $search = substr($search, 1);
97 self::tryRedirectToProfile($search);
99 if (strpos($search, '@') === 0 || strpos($search, '!') === 0) {
100 return self::performContactSearch($search);
103 self::tryRedirectToPost($search);
105 if (!empty($_GET['search-option'])) {
106 switch ($_GET['search-option']) {
113 return self::performContactSearch($search, '@');
115 return self::performContactSearch($search, '!');
119 $tag = $tag || Config::get('system', 'only_tag_search');
121 // Here is the way permissions work in the search module...
122 // Only public posts can be shown
123 // OR your own posts if you are a logged in member
124 // No items will be shown if the member has a blocked profile wall.
126 $pager = new Pager(DI::args()->getQueryString());
129 Logger::info('Start tag search.', ['q' => $search]);
132 "(`uid` = 0 OR (`uid` = ? AND NOT `global`))
133 AND `otype` = ? AND `type` = ? AND `term` = ?",
134 local_user(), Term::OBJECT_TYPE_POST, Term::HASHTAG, $search
137 'order' => ['received' => true],
138 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]
140 $terms = DBA::select('term', ['oid'], $condition, $params);
143 while ($term = DBA::fetch($terms)) {
144 $itemids[] = $term['oid'];
149 if (!empty($itemids)) {
150 $params = ['order' => ['id' => true]];
151 $items = Item::selectForUser(local_user(), [], ['id' => $itemids], $params);
152 $r = Item::inArray($items);
157 Logger::info('Start fulltext search.', ['q' => $search]);
160 "(`uid` = 0 OR (`uid` = ? AND NOT `global`))
161 AND `body` LIKE CONCAT('%',?,'%')",
162 local_user(), $search
165 'order' => ['id' => true],
166 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]
168 $items = Item::selectForUser(local_user(), [], $condition, $params);
169 $r = Item::inArray($items);
172 if (!DBA::isResult($r)) {
173 info(L10n::t('No results.'));
178 $title = L10n::t('Items tagged with: %s', $search);
180 $title = L10n::t('Results for: %s', $search);
183 $o .= Renderer::replaceMacros(Renderer::getMarkupTemplate('section_title.tpl'), [
187 Logger::info('Start Conversation.', ['q' => $search]);
189 $o .= conversation(DI::app(), $r, $pager, 'search', false, false, 'commented', local_user());
191 $o .= $pager->renderMinimal(count($r));
197 * Tries to redirect to a local profile page based on the input.
199 * This method separates logged in and anonymous users. Logged in users can trigger contact probes to import
200 * non-existing contacts while anonymous users can only trigger a local lookup.
205 * - Any fully-formed URL
207 * @param string $search
208 * @throws HTTPException\InternalServerErrorException
209 * @throws \ImagickException
211 private static function tryRedirectToProfile(string $search)
213 $isUrl = !empty(parse_url($search, PHP_URL_SCHEME));
214 $isAddr = (bool)preg_match('/^@?([a-z0-9.-_]+@[a-z0-9.-_:]+)$/i', trim($search), $matches);
216 if (!$isUrl && !$isAddr) {
221 $search = $matches[1];
225 // User-specific contact URL/address search
226 $contact_id = Contact::getIdForURL($search, local_user());
228 // User-specific contact URL/address search and probe
229 $contact_id = Contact::getIdForURL($search);
232 // Cheaper local lookup for anonymous users, no probe
234 $contact = Contact::selectFirst(['id' => 'cid'], ['addr' => $search, 'uid' => 0]);
236 $contact = Contact::getDetailsByURL($search, 0, ['cid' => 0]);
239 if (DBA::isResult($contact)) {
240 $contact_id = $contact['cid'];
244 if (!empty($contact_id)) {
245 DI::baseUrl()->redirect('contact/' . $contact_id);
250 * Fetch/search a post by URL and redirects to its local representation if it was found.
252 * @param string $search
253 * @throws HTTPException\InternalServerErrorException
255 private static function tryRedirectToPost(string $search)
257 if (parse_url($search, PHP_URL_SCHEME) == '') {
263 $item_id = Item::fetchByLink($search, local_user());
265 // If the user-specific search failed, we search and probe a public post
266 $item_id = Item::fetchByLink($search);
269 // Cheaper local lookup for anonymous users, no probe
270 $item_id = Item::searchByLink($search);
273 if (!empty($item_id)) {
274 $item = Item::selectFirst(['guid'], ['id' => $item_id]);
275 if (DBA::isResult($item)) {
276 DI::baseUrl()->redirect('display/' . $item['guid']);