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