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