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