4144e2608f91f6b9bb7a44b4e5c4fd6a4e3bb1bd
[friendica.git/.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\Renderer;
15 use Friendica\Database\DBA;
16 use Friendica\Model\Item;
17 use Friendica\Module\BaseSearchModule;
18 use Friendica\Util\Strings;
19
20 function search_saved_searches() {
21
22         $o = '';
23         $search = (!empty($_GET['search']) ? Strings::escapeTags(trim(rawurldecode($_GET['search']))) : '');
24
25         $r = q("SELECT `id`,`term` FROM `search` WHERE `uid` = %d",
26                 intval(local_user())
27         );
28
29         if (DBA::isResult($r)) {
30                 $saved = [];
31                 foreach ($r as $rr) {
32                         $saved[] = [
33                                 'id'            => $rr['id'],
34                                 'term'          => $rr['term'],
35                                 'encodedterm'   => urlencode($rr['term']),
36                                 'delete'        => L10n::t('Remove term'),
37                                 'selected'      => ($search==$rr['term']),
38                         ];
39                 }
40
41
42                 $tpl = Renderer::getMarkupTemplate("saved_searches_aside.tpl");
43
44                 $o .= Renderer::replaceMacros($tpl, [
45                         '$title'        => L10n::t('Saved Searches'),
46                         '$add'          => '',
47                         '$searchbox'    => '',
48                         '$saved'        => $saved,
49                 ]);
50         }
51
52         return $o;
53
54 }
55
56
57 function search_init(App $a) {
58
59         $search = (!empty($_GET['search']) ? Strings::escapeTags(trim(rawurldecode($_GET['search']))) : '');
60
61         if (local_user()) {
62                 if (!empty($_GET['save']) && $search) {
63                         $r = q("SELECT * FROM `search` WHERE `uid` = %d AND `term` = '%s' LIMIT 1",
64                                 intval(local_user()),
65                                 DBA::escape($search)
66                         );
67                         if (!DBA::isResult($r)) {
68                                 DBA::insert('search', ['uid' => local_user(), 'term' => $search]);
69                         }
70                 }
71                 if (!empty($_GET['remove']) && $search) {
72                         DBA::delete('search', ['uid' => local_user(), 'term' => $search]);
73                 }
74
75                 /// @todo Check if there is a case at all that "aside" is prefilled here
76                 if (!isset($a->page['aside'])) {
77                         $a->page['aside'] = '';
78                 }
79
80                 $a->page['aside'] .= search_saved_searches();
81
82         } else {
83                 unset($_SESSION['theme']);
84                 unset($_SESSION['mobile-theme']);
85         }
86
87
88
89 }
90
91 function search_content(App $a) {
92
93         if (Config::get('system','block_public') && !local_user() && !remote_user()) {
94                 notice(L10n::t('Public access denied.') . EOL);
95                 return;
96         }
97
98         if (Config::get('system','local_search') && !local_user() && !remote_user()) {
99                 $e = new \Friendica\Network\HTTPException\ForbiddenException(L10n::t("Only logged in users are permitted to perform a search."));
100                 $e->httpdesc = L10n::t("Public access denied.");
101                 throw $e;
102         }
103
104         if (Config::get('system','permit_crawling') && !local_user() && !remote_user()) {
105                 // Default values:
106                 // 10 requests are "free", after the 11th only a call per minute is allowed
107
108                 $free_crawls = intval(Config::get('system','free_crawls'));
109                 if ($free_crawls == 0)
110                         $free_crawls = 10;
111
112                 $crawl_permit_period = intval(Config::get('system','crawl_permit_period'));
113                 if ($crawl_permit_period == 0)
114                         $crawl_permit_period = 10;
115
116                 $remote = $_SERVER["REMOTE_ADDR"];
117                 $result = Cache::get("remote_search:".$remote);
118                 if (!is_null($result)) {
119                         $resultdata = json_decode($result);
120                         if (($resultdata->time > (time() - $crawl_permit_period)) && ($resultdata->accesses > $free_crawls)) {
121                                 throw new \Friendica\Network\HTTPException\TooManyRequestsException(L10n::t("Only one search per minute is permitted for not logged in users."));
122                         }
123                         Cache::set("remote_search:".$remote, json_encode(["time" => time(), "accesses" => $resultdata->accesses + 1]), Cache::HOUR);
124                 } else
125                         Cache::set("remote_search:".$remote, json_encode(["time" => time(), "accesses" => 1]), Cache::HOUR);
126         }
127
128         Nav::setSelected('search');
129
130         $search = (!empty($_REQUEST['search']) ? Strings::escapeTags(trim(rawurldecode($_REQUEST['search']))) : '');
131
132         $tag = false;
133         if (!empty($_GET['tag'])) {
134                 $tag = true;
135                 $search = (!empty($_GET['tag']) ? '#' . Strings::escapeTags(trim(rawurldecode($_GET['tag']))) : '');
136         }
137
138         // contruct a wrapper for the search header
139         $o = Renderer::replaceMacros(Renderer::getMarkupTemplate("content_wrapper.tpl"),[
140                 'name' => "search-header",
141                 '$title' => L10n::t("Search"),
142                 '$title_size' => 3,
143                 '$content' => HTML::search($search,'search-box','search', false)
144         ]);
145
146         if (strpos($search,'#') === 0) {
147                 $tag = true;
148                 $search = substr($search,1);
149         }
150         if (strpos($search,'@') === 0) {
151                 return BaseSearchModule::performSearch();
152         }
153         if (strpos($search,'!') === 0) {
154                 return BaseSearchModule::performSearch();
155         }
156
157         if (!empty($_GET['search-option']))
158                 switch($_GET['search-option']) {
159                         case 'fulltext':
160                                 break;
161                         case 'tags':
162                                 $tag = true;
163                                 break;
164                         case 'contacts':
165                                 return BaseSearchModule::performSearch('@');
166                         case 'forums':
167                                 return BaseSearchModule::performSearch('!');
168                 }
169
170         if (!$search)
171                 return $o;
172
173         if (Config::get('system','only_tag_search'))
174                 $tag = true;
175
176         // Here is the way permissions work in the search module...
177         // Only public posts can be shown
178         // OR your own posts if you are a logged in member
179         // No items will be shown if the member has a blocked profile wall.
180
181         $pager = new Pager($a->query_string);
182
183         if ($tag) {
184                 Logger::log("Start tag search for '".$search."'", Logger::DEBUG);
185
186                 $condition = ["(`uid` = 0 OR (`uid` = ? AND NOT `global`))
187                         AND `otype` = ? AND `type` = ? AND `term` = ?",
188                         local_user(), TERM_OBJ_POST, TERM_HASHTAG, $search];
189                 $params = ['order' => ['created' => true],
190                         'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
191                 $terms = DBA::select('term', ['oid'], $condition, $params);
192
193                 $itemids = [];
194                 while ($term = DBA::fetch($terms)) {
195                         $itemids[] = $term['oid'];
196                 }
197                 DBA::close($terms);
198
199                 if (!empty($itemids)) {
200                         $params = ['order' => ['id' => true]];
201                         $items = Item::selectForUser(local_user(), [], ['id' => $itemids], $params);
202                         $r = Item::inArray($items);
203                 } else {
204                         $r = [];
205                 }
206         } else {
207                 Logger::log("Start fulltext search for '".$search."'", Logger::DEBUG);
208
209                 $condition = ["(`uid` = 0 OR (`uid` = ? AND NOT `global`))
210                         AND `body` LIKE CONCAT('%',?,'%')",
211                         local_user(), $search];
212                 $params = ['order' => ['id' => true],
213                         'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
214                 $items = Item::selectForUser(local_user(), [], $condition, $params);
215                 $r = Item::inArray($items);
216         }
217
218         if (!DBA::isResult($r)) {
219                 info(L10n::t('No results.') . EOL);
220                 return $o;
221         }
222
223
224         if ($tag) {
225                 $title = L10n::t('Items tagged with: %s', $search);
226         } else {
227                 $title = L10n::t('Results for: %s', $search);
228         }
229
230         $o .= Renderer::replaceMacros(Renderer::getMarkupTemplate("section_title.tpl"),[
231                 '$title' => $title
232         ]);
233
234         Logger::log("Start Conversation for '".$search."'", Logger::DEBUG);
235         $o .= conversation($a, $r, $pager, 'search', false, false, 'commented', local_user());
236
237         $o .= $pager->renderMinimal(count($r));
238
239         Logger::log("Done '".$search."'", Logger::DEBUG);
240
241         return $o;
242 }