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