]> git.mxchange.org Git - friendica.git/blob - src/Core/Search.php
Move Module\Search\Acl::contactAutocomplete to Core\Search::searchGlobalContact
[friendica.git] / src / Core / Search.php
1 <?php
2
3 namespace Friendica\Core;
4
5 use Friendica\BaseObject;
6 use Friendica\Database\DBA;
7 use Friendica\Model\Contact;
8 use Friendica\Model\GContact;
9 use Friendica\Network\HTTPException;
10 use Friendica\Network\Probe;
11 use Friendica\Object\Search\ContactResult;
12 use Friendica\Object\Search\ResultList;
13 use Friendica\Protocol\PortableContact;
14 use Friendica\Util\Network;
15 use Friendica\Util\Strings;
16
17 /**
18  * Specific class to perform searches for different systems. Currently:
19  * - Probe for contacts
20  * - Search in the local directory
21  * - Search in the global directory
22  */
23 class Search extends BaseObject
24 {
25         const DEFAULT_DIRECTORY = 'https://dir.friendica.social';
26
27         const TYPE_PEOPLE = 0;
28         const TYPE_FORUM  = 1;
29         const TYPE_ALL    = 2;
30
31         /**
32          * Search a user based on his/her profile address
33          * pattern: @username@domain.tld
34          *
35          * @param string $user The user to search for
36          *
37          * @return ResultList
38          * @throws HTTPException\InternalServerErrorException
39          * @throws \ImagickException
40          */
41         public static function getContactsFromProbe($user)
42         {
43                 $emptyResultList = new ResultList(1, 0, 1);
44
45                 if ((filter_var($user, FILTER_VALIDATE_EMAIL) && Network::isEmailDomainValid($user)) ||
46                     (substr(Strings::normaliseLink($user), 0, 7) == "http://")) {
47
48                         /// @todo Possibly use "getIdForURL" instead?
49                         $user_data = Probe::uri($user);
50                         if (empty($user_data)) {
51                                 return $emptyResultList;
52                         }
53
54                         if (!in_array($user_data["network"], Protocol::FEDERATED)) {
55                                 return $emptyResultList;
56                         }
57
58                         // Ensure that we do have a contact entry
59                         Contact::getIdForURL(defaults($user_data, 'url', ''));
60
61                         $contactDetails = Contact::getDetailsByURL(defaults($user_data, 'url', ''), local_user());
62                         $itemUrl        = defaults($contactDetails, 'addr', defaults($user_data, 'url', ''));
63
64                         $result = new ContactResult(
65                                 defaults($user_data, 'name', ''),
66                                 defaults($user_data, 'addr', ''),
67                                 $itemUrl,
68                                 defaults($user_data, 'url', ''),
69                                 defaults($user_data, 'photo', ''),
70                                 defaults($user_data, 'network', ''),
71                                 defaults($contactDetails, 'id', 0),
72                                 0,
73                                 defaults($user_data, 'tags', '')
74                         );
75
76                         return new ResultList(1, 1, 1, [$result]);
77                 } else {
78                         return $emptyResultList;
79                 }
80         }
81
82         /**
83          * Search in the global directory for occurrences of the search string
84          *
85          * @see https://github.com/friendica/friendica-directory/blob/master/docs/Protocol.md#search
86          *
87          * @param string $search
88          * @param int    $type specific type of searching
89          * @param int    $page
90          *
91          * @return ResultList
92          * @throws HTTPException\InternalServerErrorException
93          */
94         public static function getContactsFromGlobalDirectory($search, $type = self::TYPE_ALL, $page = 1)
95         {
96                 $config = self::getApp()->getConfig();
97                 $server = $config->get('system', 'directory', self::DEFAULT_DIRECTORY);
98
99                 $searchUrl = $server . '/search';
100
101                 switch ($type) {
102                         case self::TYPE_FORUM:
103                                 $searchUrl .= '/forum';
104                                 break;
105                         case self::TYPE_PEOPLE:
106                                 $searchUrl .= '/people';
107                                 break;
108                 }
109                 $searchUrl .= '?q=' . urlencode($search);
110
111                 if ($page > 1) {
112                         $searchUrl .= '&page=' . $page;
113                 }
114
115                 $resultJson = Network::fetchUrl($searchUrl, false, 0, 'application/json');
116
117                 $results = json_decode($resultJson, true);
118
119                 $resultList = new ResultList(
120                         defaults($results, 'page', 1),
121                         defaults($results, 'count', 0),
122                         defaults($results, 'itemsperpage', 30)
123                 );
124
125                 $profiles = defaults($results, 'profiles', []);
126
127                 foreach ($profiles as $profile) {
128                         $contactDetails = Contact::getDetailsByURL(defaults($profile, 'profile_url', ''), local_user());
129                         $itemUrl        = defaults($contactDetails, 'addr', defaults($profile, 'profile_url', ''));
130
131                         $result = new ContactResult(
132                                 defaults($profile, 'name', ''),
133                                 defaults($profile, 'addr', ''),
134                                 $itemUrl,
135                                 defaults($profile, 'profile_url', ''),
136                                 defaults($profile, 'photo', ''),
137                                 Protocol::DFRN,
138                                 defaults($contactDetails, 'cid', 0),
139                                 0,
140                                 defaults($profile, 'tags', ''));
141
142                         $resultList->addResult($result);
143                 }
144
145                 return $resultList;
146         }
147
148         /**
149          * Search in the local database for occurrences of the search string
150          *
151          * @param string $search
152          * @param int    $type
153          * @param int    $start
154          * @param int    $itemPage
155          *
156          * @return ResultList
157          * @throws HTTPException\InternalServerErrorException
158          */
159         public static function getContactsFromLocalDirectory($search, $type = self::TYPE_ALL, $start = 0, $itemPage = 80)
160         {
161                 $config = self::getApp()->getConfig();
162
163                 $diaspora = $config->get('system', 'diaspora_enabled') ? Protocol::DIASPORA : Protocol::DFRN;
164                 $ostatus  = !$config->get('system', 'ostatus_disabled') ? Protocol::OSTATUS : Protocol::DFRN;
165
166                 $wildcard = Strings::escapeHtml('%' . $search . '%');
167
168                 $count = DBA::count('gcontact', [
169                         'NOT `hide`
170                         AND `network` IN (?, ?, ?, ?)
171                         AND ((`last_contact` >= `last_failure`) OR (`updated` >= `last_failure`))
172                         AND (`url` LIKE ? OR `name` LIKE ? OR `location` LIKE ? 
173                                 OR `addr` LIKE ? OR `about` LIKE ? OR `keywords` LIKE ?)
174                         AND `community` = ?',
175                         Protocol::ACTIVITYPUB, Protocol::DFRN, $ostatus, $diaspora,
176                         $wildcard, $wildcard, $wildcard,
177                         $wildcard, $wildcard, $wildcard,
178                         ($type === self::TYPE_FORUM),
179                 ]);
180
181                 $resultList = new ResultList($start, $itemPage, $count);
182
183                 if (empty($count)) {
184                         return $resultList;
185                 }
186
187                 $data = DBA::select('gcontact', ['nurl'], [
188                         'NOT `hide`
189                         AND `network` IN (?, ?, ?, ?)
190                         AND ((`last_contact` >= `last_failure`) OR (`updated` >= `last_failure`))
191                         AND (`url` LIKE ? OR `name` LIKE ? OR `location` LIKE ? 
192                                 OR `addr` LIKE ? OR `about` LIKE ? OR `keywords` LIKE ?)
193                         AND `community` = ?',
194                         Protocol::ACTIVITYPUB, Protocol::DFRN, $ostatus, $diaspora,
195                         $wildcard, $wildcard, $wildcard,
196                         $wildcard, $wildcard, $wildcard,
197                         ($type === self::TYPE_FORUM),
198                 ], [
199                         'group_by' => ['nurl', 'updated'],
200                         'limit'    => [$start, $itemPage],
201                         'order'    => ['updated' => 'DESC']
202                 ]);
203
204                 if (!DBA::isResult($data)) {
205                         return $resultList;
206                 }
207
208                 while ($row = DBA::fetch($data)) {
209                         if (PortableContact::alternateOStatusUrl($row["nurl"])) {
210                                 continue;
211                         }
212
213                         $urlParts = parse_url($row["nurl"]);
214
215                         // Ignore results that look strange.
216                         // For historic reasons the gcontact table does contain some garbage.
217                         if (!empty($urlParts['query']) || !empty($urlParts['fragment'])) {
218                                 continue;
219                         }
220
221                         $contact = Contact::getDetailsByURL($row["nurl"], local_user());
222
223                         if ($contact["name"] == "") {
224                                 $contact["name"] = end(explode("/", $urlParts["path"]));
225                         }
226
227                         $result = new ContactResult(
228                                 $contact["name"],
229                                 $contact["addr"],
230                                 $contact["addr"],
231                                 $contact["url"],
232                                 $contact["photo"],
233                                 $contact["network"],
234                                 $contact["cid"],
235                                 $contact["zid"],
236                                 $contact["keywords"]
237                         );
238
239                         $resultList->addResult($result);
240                 }
241
242                 DBA::close($data);
243
244                 // Add found profiles from the global directory to the local directory
245                 Worker::add(PRIORITY_LOW, 'DiscoverPoCo', "dirsearch", urlencode($search));
246
247                 return $resultList;
248         }
249
250
251
252         /**
253          * Searching for global contacts for autocompletion
254          *
255          * @brief Searching for global contacts for autocompletion
256          * @param string $search Name or part of a name or nick
257          * @param string $mode   Search mode (e.g. "community")
258          * @param int    $page   Page number (starts at 1)
259          * @return array with the search results
260          * @throws HTTPException\InternalServerErrorException
261          */
262         public static function searchGlobalContact($search, $mode, int $page = 1)
263         {
264                 if (Config::get('system', 'block_public') && !Session::isAuthenticated()) {
265                         return [];
266                 }
267
268                 // don't search if search term has less than 2 characters
269                 if (!$search || mb_strlen($search) < 2) {
270                         return [];
271                 }
272
273                 if (substr($search, 0, 1) === '@') {
274                         $search = substr($search, 1);
275                 }
276
277                 // check if searching in the local global contact table is enabled
278                 if (Config::get('system', 'poco_local_search')) {
279                         $return = GContact::searchByName($search, $mode);
280                 } else {
281                         $p = $page > 1 ? 'p=' . $page : '';
282                         $curlResult = Network::curl(get_server() . '/search/people?' . $p . '&q=' . urlencode($search), false, ['accept_content' => 'application/json']);
283                         if ($curlResult->isSuccess()) {
284                                 $searchResult = json_decode($curlResult->getBody(), true);
285                                 if (!empty($searchResult['profiles'])) {
286                                         $return = $searchResult['profiles'];
287                                 }
288                         }
289                 }
290
291                 return $return ?? [];
292         }
293 }