]> git.mxchange.org Git - friendica.git/blob - mod/search.php
Merge pull request #6977 from annando/fix-reshare
[friendica.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\Core\System;
16 use Friendica\Database\DBA;
17 use Friendica\Model\Item;
18 use Friendica\Util\Strings;
19
20 require_once 'mod/dirfind.php';
21
22 function search_saved_searches() {
23
24         $o = '';
25         $search = (!empty($_GET['search']) ? Strings::escapeTags(trim(rawurldecode($_GET['search']))) : '');
26
27         $r = q("SELECT `id`,`term` FROM `search` WHERE `uid` = %d",
28                 intval(local_user())
29         );
30
31         if (DBA::isResult($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 = Renderer::getMarkupTemplate("saved_searches_aside.tpl");
45
46                 $o .= Renderer::replaceMacros($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 = (!empty($_GET['search']) ? Strings::escapeTags(trim(rawurldecode($_GET['search']))) : '');
62
63         if (local_user()) {
64                 if (!empty($_GET['save']) && $search) {
65                         $r = q("SELECT * FROM `search` WHERE `uid` = %d AND `term` = '%s' LIMIT 1",
66                                 intval(local_user()),
67                                 DBA::escape($search)
68                         );
69                         if (!DBA::isResult($r)) {
70                                 DBA::insert('search', ['uid' => local_user(), 'term' => $search]);
71                         }
72                 }
73                 if (!empty($_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 function search_content(App $a) {
94
95         if (Config::get('system','block_public') && !local_user() && !remote_user()) {
96                 notice(L10n::t('Public access denied.') . EOL);
97                 return;
98         }
99
100         if (Config::get('system','local_search') && !local_user() && !remote_user()) {
101                 System::httpExit(403,
102                                 ["title" => L10n::t("Public access denied."),
103                                         "description" => L10n::t("Only logged in users are permitted to perform a search.")]);
104                 exit();
105                 //notice(L10n::t('Public access denied.').EOL);
106                 //return;
107         }
108
109         if (Config::get('system','permit_crawling') && !local_user() && !remote_user()) {
110                 // Default values:
111                 // 10 requests are "free", after the 11th only a call per minute is allowed
112
113                 $free_crawls = intval(Config::get('system','free_crawls'));
114                 if ($free_crawls == 0)
115                         $free_crawls = 10;
116
117                 $crawl_permit_period = intval(Config::get('system','crawl_permit_period'));
118                 if ($crawl_permit_period == 0)
119                         $crawl_permit_period = 10;
120
121                 $remote = $_SERVER["REMOTE_ADDR"];
122                 $result = Cache::get("remote_search:".$remote);
123                 if (!is_null($result)) {
124                         $resultdata = json_decode($result);
125                         if (($resultdata->time > (time() - $crawl_permit_period)) && ($resultdata->accesses > $free_crawls)) {
126                                 System::httpExit(429,
127                                                 ["title" => L10n::t("Too Many Requests"),
128                                                         "description" => L10n::t("Only one search per minute is permitted for not logged in users.")]);
129                                 exit();
130                         }
131                         Cache::set("remote_search:".$remote, json_encode(["time" => time(), "accesses" => $resultdata->accesses + 1]), Cache::HOUR);
132                 } else
133                         Cache::set("remote_search:".$remote, json_encode(["time" => time(), "accesses" => 1]), Cache::HOUR);
134         }
135
136         Nav::setSelected('search');
137
138         $search = (!empty($_REQUEST['search']) ? Strings::escapeTags(trim(rawurldecode($_REQUEST['search']))) : '');
139
140         $tag = false;
141         if (!empty($_GET['tag'])) {
142                 $tag = true;
143                 $search = (!empty($_GET['tag']) ? '#' . Strings::escapeTags(trim(rawurldecode($_GET['tag']))) : '');
144         }
145
146         // contruct a wrapper for the search header
147         $o = Renderer::replaceMacros(Renderer::getMarkupTemplate("content_wrapper.tpl"),[
148                 'name' => "search-header",
149                 '$title' => L10n::t("Search"),
150                 '$title_size' => 3,
151                 '$content' => HTML::search($search,'search-box','search', false)
152         ]);
153
154         if (strpos($search,'#') === 0) {
155                 $tag = true;
156                 $search = substr($search,1);
157         }
158         if (strpos($search,'@') === 0) {
159                 return dirfind_content($a);
160         }
161         if (strpos($search,'!') === 0) {
162                 return dirfind_content($a);
163         }
164
165         if (!empty($_GET['search-option']))
166                 switch($_GET['search-option']) {
167                         case 'fulltext':
168                                 break;
169                         case 'tags':
170                                 $tag = true;
171                                 break;
172                         case 'contacts':
173                                 return dirfind_content($a, "@");
174                                 break;
175                         case 'forums':
176                                 return dirfind_content($a, "!");
177                                 break;
178                 }
179
180         if (!$search)
181                 return $o;
182
183         if (Config::get('system','only_tag_search'))
184                 $tag = true;
185
186         // Here is the way permissions work in the search module...
187         // Only public posts can be shown
188         // OR your own posts if you are a logged in member
189         // No items will be shown if the member has a blocked profile wall.
190
191         $pager = new Pager($a->query_string);
192
193         if ($tag) {
194                 Logger::log("Start tag search for '".$search."'", Logger::DEBUG);
195
196                 $condition = ["(`uid` = 0 OR (`uid` = ? AND NOT `global`))
197                         AND `otype` = ? AND `type` = ? AND `term` = ?",
198                         local_user(), TERM_OBJ_POST, TERM_HASHTAG, $search];
199                 $params = ['order' => ['created' => true],
200                         'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
201                 $terms = DBA::select('term', ['oid'], $condition, $params);
202
203                 $itemids = [];
204                 while ($term = DBA::fetch($terms)) {
205                         $itemids[] = $term['oid'];
206                 }
207                 DBA::close($terms);
208
209                 if (!empty($itemids)) {
210                         $params = ['order' => ['id' => true]];
211                         $items = Item::selectForUser(local_user(), [], ['id' => $itemids], $params);
212                         $r = Item::inArray($items);
213                 } else {
214                         $r = [];
215                 }
216         } else {
217                 Logger::log("Start fulltext search for '".$search."'", Logger::DEBUG);
218
219                 $condition = ["(`uid` = 0 OR (`uid` = ? AND NOT `global`))
220                         AND `body` LIKE CONCAT('%',?,'%')",
221                         local_user(), $search];
222                 $params = ['order' => ['id' => true],
223                         'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
224                 $items = Item::selectForUser(local_user(), [], $condition, $params);
225                 $r = Item::inArray($items);
226         }
227
228         if (!DBA::isResult($r)) {
229                 info(L10n::t('No results.') . EOL);
230                 return $o;
231         }
232
233
234         if ($tag) {
235                 $title = L10n::t('Items tagged with: %s', $search);
236         } else {
237                 $title = L10n::t('Results for: %s', $search);
238         }
239
240         $o .= Renderer::replaceMacros(Renderer::getMarkupTemplate("section_title.tpl"),[
241                 '$title' => $title
242         ]);
243
244         Logger::log("Start Conversation for '".$search."'", Logger::DEBUG);
245         $o .= conversation($a, $r, $pager, 'search', false, false, 'commented', local_user());
246
247         $o .= $pager->renderMinimal(count($r));
248
249         Logger::log("Done '".$search."'", Logger::DEBUG);
250
251         return $o;
252 }