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