]> git.mxchange.org Git - friendica.git/blob - src/Core/Search.php
@brief is removed completely
[friendica.git] / src / Core / Search.php
1 <?php
2
3 namespace Friendica\Core;
4
5 use Friendica\Database\DBA;
6 use Friendica\DI;
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
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($user_data['url'] ?? '');
60
61                         $contactDetails = Contact::getDetailsByURL($user_data['url'] ?? '', local_user());
62
63                         $result = new ContactResult(
64                                 $user_data['name'] ?? '',
65                                 $user_data['addr'] ?? '',
66                                 ($contactDetails['addr'] ?? '') ?: ($user_data['url'] ?? ''),
67                                 $user_data['url'] ?? '',
68                                 $user_data['photo'] ?? '',
69                                 $user_data['network'] ?? '',
70                                 $contactDetails['id'] ?? 0,
71                                 0,
72                                 $user_data['tags'] ?? ''
73                         );
74
75                         return new ResultList(1, 1, 1, [$result]);
76                 } else {
77                         return $emptyResultList;
78                 }
79         }
80
81         /**
82          * Search in the global directory for occurrences of the search string
83          *
84          * @see https://github.com/friendica/friendica-directory/blob/master/docs/Protocol.md#search
85          *
86          * @param string $search
87          * @param int    $type specific type of searching
88          * @param int    $page
89          *
90          * @return ResultList
91          * @throws HTTPException\InternalServerErrorException
92          */
93         public static function getContactsFromGlobalDirectory($search, $type = self::TYPE_ALL, $page = 1)
94         {
95                 $server = DI::config()->get('system', 'directory', self::DEFAULT_DIRECTORY);
96
97                 $searchUrl = $server . '/search';
98
99                 switch ($type) {
100                         case self::TYPE_FORUM:
101                                 $searchUrl .= '/forum';
102                                 break;
103                         case self::TYPE_PEOPLE:
104                                 $searchUrl .= '/people';
105                                 break;
106                 }
107                 $searchUrl .= '?q=' . urlencode($search);
108
109                 if ($page > 1) {
110                         $searchUrl .= '&page=' . $page;
111                 }
112
113                 $resultJson = Network::fetchUrl($searchUrl, false, 0, 'application/json');
114
115                 $results = json_decode($resultJson, true);
116
117                 $resultList = new ResultList(
118                         ($results['page']         ?? 0) ?: 1,
119                          $results['count']        ?? 0,
120                         ($results['itemsperpage'] ?? 0) ?: 30
121                 );
122
123                 $profiles = $results['profiles'] ?? [];
124
125                 foreach ($profiles as $profile) {
126                         $profile_url = $profile['profile_url'] ?? '';
127                         $contactDetails = Contact::getDetailsByURL($profile_url, local_user());
128
129                         $result = new ContactResult(
130                                 $profile['name'] ?? '',
131                                 $profile['addr'] ?? '',
132                                 ($contactDetails['addr'] ?? '') ?: $profile_url,
133                                 $profile_url,
134                                 $profile['photo'] ?? '',
135                                 Protocol::DFRN,
136                                 $contactDetails['cid'] ?? 0,
137                                 0,
138                                 $profile['tags'] ?? ''
139                         );
140
141                         $resultList->addResult($result);
142                 }
143
144                 return $resultList;
145         }
146
147         /**
148          * Search in the local database for occurrences of the search string
149          *
150          * @param string $search
151          * @param int    $type
152          * @param int    $start
153          * @param int    $itemPage
154          *
155          * @return ResultList
156          * @throws HTTPException\InternalServerErrorException
157          */
158         public static function getContactsFromLocalDirectory($search, $type = self::TYPE_ALL, $start = 0, $itemPage = 80)
159         {
160                 $config = DI::config();
161
162                 $diaspora = $config->get('system', 'diaspora_enabled') ? Protocol::DIASPORA : Protocol::DFRN;
163                 $ostatus  = !$config->get('system', 'ostatus_disabled') ? Protocol::OSTATUS : Protocol::DFRN;
164
165                 $wildcard = Strings::escapeHtml('%' . $search . '%');
166
167                 $count = DBA::count('gcontact', [
168                         'NOT `hide`
169                         AND `network` IN (?, ?, ?, ?)
170                         AND ((`last_contact` >= `last_failure`) OR (`updated` >= `last_failure`))
171                         AND (`url` LIKE ? OR `name` LIKE ? OR `location` LIKE ? 
172                                 OR `addr` LIKE ? OR `about` LIKE ? OR `keywords` LIKE ?)
173                         AND `community` = ?',
174                         Protocol::ACTIVITYPUB, Protocol::DFRN, $ostatus, $diaspora,
175                         $wildcard, $wildcard, $wildcard,
176                         $wildcard, $wildcard, $wildcard,
177                         ($type === self::TYPE_FORUM),
178                 ]);
179
180                 $resultList = new ResultList($start, $itemPage, $count);
181
182                 if (empty($count)) {
183                         return $resultList;
184                 }
185
186                 $data = DBA::select('gcontact', ['nurl'], [
187                         'NOT `hide`
188                         AND `network` IN (?, ?, ?, ?)
189                         AND ((`last_contact` >= `last_failure`) OR (`updated` >= `last_failure`))
190                         AND (`url` LIKE ? OR `name` LIKE ? OR `location` LIKE ? 
191                                 OR `addr` LIKE ? OR `about` LIKE ? OR `keywords` LIKE ?)
192                         AND `community` = ?',
193                         Protocol::ACTIVITYPUB, Protocol::DFRN, $ostatus, $diaspora,
194                         $wildcard, $wildcard, $wildcard,
195                         $wildcard, $wildcard, $wildcard,
196                         ($type === self::TYPE_FORUM),
197                 ], [
198                         'group_by' => ['nurl', 'updated'],
199                         'limit'    => [$start, $itemPage],
200                         'order'    => ['updated' => 'DESC']
201                 ]);
202
203                 if (!DBA::isResult($data)) {
204                         return $resultList;
205                 }
206
207                 while ($row = DBA::fetch($data)) {
208                         $urlParts = parse_url($row["nurl"]);
209
210                         // Ignore results that look strange.
211                         // For historic reasons the gcontact table does contain some garbage.
212                         if (!empty($urlParts['query']) || !empty($urlParts['fragment'])) {
213                                 continue;
214                         }
215
216                         $contact = Contact::getDetailsByURL($row["nurl"], local_user());
217
218                         if ($contact["name"] == "") {
219                                 $contact["name"] = end(explode("/", $urlParts["path"]));
220                         }
221
222                         $result = new ContactResult(
223                                 $contact["name"],
224                                 $contact["addr"],
225                                 $contact["addr"],
226                                 $contact["url"],
227                                 $contact["photo"],
228                                 $contact["network"],
229                                 $contact["cid"],
230                                 $contact["zid"],
231                                 $contact["keywords"]
232                         );
233
234                         $resultList->addResult($result);
235                 }
236
237                 DBA::close($data);
238
239                 // Add found profiles from the global directory to the local directory
240                 Worker::add(PRIORITY_LOW, 'SearchDirectory', $search);
241
242                 return $resultList;
243         }
244
245         /**
246          * Searching for global contacts for autocompletion
247          *
248          * @param string $search Name or part of a name or nick
249          * @param string $mode   Search mode (e.g. "community")
250          * @param int    $page   Page number (starts at 1)
251          * @return array with the search results
252          * @throws HTTPException\InternalServerErrorException
253          */
254         public static function searchGlobalContact($search, $mode, int $page = 1)
255         {
256                 if (Config::get('system', 'block_public') && !Session::isAuthenticated()) {
257                         return [];
258                 }
259
260                 // don't search if search term has less than 2 characters
261                 if (!$search || mb_strlen($search) < 2) {
262                         return [];
263                 }
264
265                 if (substr($search, 0, 1) === '@') {
266                         $search = substr($search, 1);
267                 }
268
269                 // check if searching in the local global contact table is enabled
270                 if (Config::get('system', 'poco_local_search')) {
271                         $return = GContact::searchByName($search, $mode);
272                 } else {
273                         $p = $page > 1 ? 'p=' . $page : '';
274                         $curlResult = Network::curl(self::getGlobalDirectory() . '/search/people?' . $p . '&q=' . urlencode($search), false, ['accept_content' => 'application/json']);
275                         if ($curlResult->isSuccess()) {
276                                 $searchResult = json_decode($curlResult->getBody(), true);
277                                 if (!empty($searchResult['profiles'])) {
278                                         $return = $searchResult['profiles'];
279                                 }
280                         }
281                 }
282
283                 return $return ?? [];
284         }
285
286         /**
287          * Returns the global directory name, used in this node
288          *
289          * @return string
290          */
291         public static function getGlobalDirectory()
292         {
293                 return Config::get('system', 'directory', self::DEFAULT_DIRECTORY);
294         }
295 }