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