]> git.mxchange.org Git - friendica.git/blob - mod/search.php
Improve search box
[friendica.git] / mod / search.php
1 <?php
2 /**
3  * @file mod/search.php
4  */
5
6 use Friendica\App;
7 use Friendica\Content\Nav;
8 use Friendica\Content\Pager;
9 use Friendica\Content\Text\HTML;
10 use Friendica\Core\Cache;
11 use Friendica\Core\Config;
12 use Friendica\Core\L10n;
13 use Friendica\Core\Logger;
14 use Friendica\Core\Session;
15 use Friendica\Core\Renderer;
16 use Friendica\Database\DBA;
17 use Friendica\Model\Item;
18 use Friendica\Module\BaseSearchModule;
19 use Friendica\Util\Strings;
20
21 function search_init(App $a) {
22         $search = (!empty($_GET['q']) ? Strings::escapeTags(trim(rawurldecode($_GET['q']))) : '');
23
24         if (local_user()) {
25                 /// @todo Check if there is a case at all that "aside" is prefilled here
26                 if (!isset($a->page['aside'])) {
27                         $a->page['aside'] = '';
28                 }
29
30                 $a->page['aside'] .= \Friendica\Content\Widget\SavedSearches::getHTML('search?q=' . $search, $search);
31         }
32 }
33
34 function search_content(App $a) {
35         if (Config::get('system','block_public') && !Session::isAuthenticated()) {
36                 notice(L10n::t('Public access denied.') . EOL);
37                 return;
38         }
39
40         if (Config::get('system','local_search') && !Session::isAuthenticated()) {
41                 $e = new \Friendica\Network\HTTPException\ForbiddenException(L10n::t("Only logged in users are permitted to perform a search."));
42                 $e->httpdesc = L10n::t("Public access denied.");
43                 throw $e;
44         }
45
46         if (Config::get('system','permit_crawling') && !Session::isAuthenticated()) {
47                 // Default values:
48                 // 10 requests are "free", after the 11th only a call per minute is allowed
49
50                 $free_crawls = intval(Config::get('system','free_crawls'));
51                 if ($free_crawls == 0)
52                         $free_crawls = 10;
53
54                 $crawl_permit_period = intval(Config::get('system','crawl_permit_period'));
55                 if ($crawl_permit_period == 0)
56                         $crawl_permit_period = 10;
57
58                 $remote = $_SERVER["REMOTE_ADDR"];
59                 $result = Cache::get("remote_search:".$remote);
60                 if (!is_null($result)) {
61                         $resultdata = json_decode($result);
62                         if (($resultdata->time > (time() - $crawl_permit_period)) && ($resultdata->accesses > $free_crawls)) {
63                                 throw new \Friendica\Network\HTTPException\TooManyRequestsException(L10n::t("Only one search per minute is permitted for not logged in users."));
64                         }
65                         Cache::set("remote_search:".$remote, json_encode(["time" => time(), "accesses" => $resultdata->accesses + 1]), Cache::HOUR);
66                 } else
67                         Cache::set("remote_search:".$remote, json_encode(["time" => time(), "accesses" => 1]), Cache::HOUR);
68         }
69
70         Nav::setSelected('search');
71
72         $search = (!empty($_REQUEST['q']) ? Strings::escapeTags(trim(rawurldecode($_REQUEST['q']))) : '');
73
74         $tag = false;
75         if (!empty($_GET['tag'])) {
76                 $tag = true;
77                 $search = (!empty($_GET['tag']) ? '#' . Strings::escapeTags(trim(rawurldecode($_GET['tag']))) : '');
78         }
79
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"),
84                 '$title_size' => 3,
85                 '$content' => HTML::search($search,'search-box',false)
86         ]);
87
88         if (strpos($search,'#') === 0) {
89                 $tag = true;
90                 $search = substr($search,1);
91         }
92         if (strpos($search,'@') === 0) {
93                 return BaseSearchModule::performSearch();
94         }
95         if (strpos($search,'!') === 0) {
96                 return BaseSearchModule::performSearch();
97         }
98
99         if (parse_url($search, PHP_URL_SCHEME) != '') {
100                 $id = Item::fetchByLink($search);
101                 if (!empty($id)) {
102                         $item = Item::selectFirst(['guid'], ['id' => $id]);
103                         if (DBA::isResult($item)) {
104                                 $a->internalRedirect('display/' . $item['guid']);
105                         }
106                 }
107         }
108
109         if (!empty($_GET['search-option']))
110                 switch($_GET['search-option']) {
111                         case 'fulltext':
112                                 break;
113                         case 'tags':
114                                 $tag = true;
115                                 break;
116                         case 'contacts':
117                                 return BaseSearchModule::performSearch('@');
118                         case 'forums':
119                                 return BaseSearchModule::performSearch('!');
120                 }
121
122         if (!$search)
123                 return $o;
124
125         if (Config::get('system','only_tag_search'))
126                 $tag = true;
127
128         // Here is the way permissions work in the search module...
129         // Only public posts can be shown
130         // OR your own posts if you are a logged in member
131         // No items will be shown if the member has a blocked profile wall.
132
133         $pager = new Pager($a->query_string);
134
135         if ($tag) {
136                 Logger::log("Start tag search for '".$search."'", Logger::DEBUG);
137
138                 $condition = ["(`uid` = 0 OR (`uid` = ? AND NOT `global`))
139                         AND `otype` = ? AND `type` = ? AND `term` = ?",
140                         local_user(), TERM_OBJ_POST, TERM_HASHTAG, $search];
141                 $params = ['order' => ['received' => true],
142                         'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
143                 $terms = DBA::select('term', ['oid'], $condition, $params);
144
145                 $itemids = [];
146                 while ($term = DBA::fetch($terms)) {
147                         $itemids[] = $term['oid'];
148                 }
149                 DBA::close($terms);
150
151                 if (!empty($itemids)) {
152                         $params = ['order' => ['id' => true]];
153                         $items = Item::selectForUser(local_user(), [], ['id' => $itemids], $params);
154                         $r = Item::inArray($items);
155                 } else {
156                         $r = [];
157                 }
158         } else {
159                 Logger::log("Start fulltext search for '".$search."'", Logger::DEBUG);
160
161                 $condition = ["(`uid` = 0 OR (`uid` = ? AND NOT `global`))
162                         AND `body` LIKE CONCAT('%',?,'%')",
163                         local_user(), $search];
164                 $params = ['order' => ['id' => true],
165                         'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
166                 $items = Item::selectForUser(local_user(), [], $condition, $params);
167                 $r = Item::inArray($items);
168         }
169
170         if (!DBA::isResult($r)) {
171                 info(L10n::t('No results.') . EOL);
172                 return $o;
173         }
174
175
176         if ($tag) {
177                 $title = L10n::t('Items tagged with: %s', $search);
178         } else {
179                 $title = L10n::t('Results for: %s', $search);
180         }
181
182         $o .= Renderer::replaceMacros(Renderer::getMarkupTemplate("section_title.tpl"),[
183                 '$title' => $title
184         ]);
185
186         Logger::log("Start Conversation for '".$search."'", Logger::DEBUG);
187         $o .= conversation($a, $r, $pager, 'search', false, false, 'commented', local_user());
188
189         $o .= $pager->renderMinimal(count($r));
190
191         Logger::log("Done '".$search."'", Logger::DEBUG);
192
193         return $o;
194 }