]> git.mxchange.org Git - friendica.git/blob - src/Core/Search.php
dcc297780c5ee800bd3263e25f256ed5e0c06abd
[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\Network\HTTPException;
9 use Friendica\Network\Probe;
10 use Friendica\Object\Search\ContactResult;
11 use Friendica\Object\Search\ResultList;
12 use Friendica\Protocol\PortableContact;
13 use Friendica\Util\Network;
14 use Friendica\Util\Strings;
15
16 /**
17  * Specific class to perform searches for different systems. Currently:
18  * - Probe for contacts
19  * - Search in the local directory
20  * - Search in the global directory
21  */
22 class Search extends BaseObject
23 {
24         const DEFAULT_DIRECTORY = 'https://dir.friendica.social';
25
26         /**
27          * Search a user based on his/her profile address
28          * pattern: @username@domain.tld
29          *
30          * @param string $user The user to search for
31          *
32          * @return ResultList|null
33          * @throws HTTPException\InternalServerErrorException
34          * @throws \ImagickException
35          */
36         public static function getContactsFromProbe($user)
37         {
38                 if ((filter_var($user, FILTER_VALIDATE_EMAIL) && Network::isEmailDomainValid($user)) ||
39                     (substr(Strings::normaliseLink($user), 0, 7) == "http://")) {
40
41                         $user_data = Probe::uri($user);
42                         if (empty($user_data)) {
43                                 return null;
44                         }
45
46                         if (!(in_array($user_data["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::OSTATUS, Protocol::DIASPORA]))) {
47                                 return null;
48                         }
49
50                         $contactDetails = Contact::getDetailsByURL(defaults($user_data, 'url', ''), local_user());
51                         $itemUrl = (($contactDetails["addr"] != "") ? $contactDetails["addr"] : defaults($user_data, 'url', ''));
52
53                         $result = new ContactResult(
54                                 defaults($user_data, 'name', ''),
55                                 defaults($user_data, 'addr', ''),
56                                 $itemUrl,
57                                 defaults($user_data, 'url', ''),
58                                 defaults($user_data, 'photo', ''),
59                                 defaults($user_data, 'network', ''),
60                                 defaults($contactDetails, 'cid', 0),
61                                 0,
62                                 defaults($user_data, 'tags', '')
63                         );
64
65                         return new ResultList(1, 1, 1, [$result]);
66
67                 } else {
68                         return null;
69                 }
70         }
71
72         /**
73          * Search in the global directory for occurrences of the search string
74          * This is mainly based on the JSON results of https://dir.friendica.social
75          *
76          * @param string $search
77          * @param int    $page
78          *
79          * @return ResultList|null
80          * @throws HTTPException\InternalServerErrorException
81          */
82         public static function getContactsFromGlobalDirectory($search, $page = 1)
83         {
84                 $config = self::getApp()->getConfig();
85                 $server = $config->get('system', 'directory', self::DEFAULT_DIRECTORY);
86
87                 $searchUrl = $server . '/search?q=' . urlencode($search);
88
89                 if ($page > 1) {
90                         $searchUrl .= '&page=' . $page;
91                 }
92
93                 $red = 0;
94                 $resultJson = Network::fetchUrl($searchUrl, false,$red, 0, 'application/json');
95
96                 $results    = json_decode($resultJson, true);
97
98                 $resultList = new ResultList(
99                         defaults($results, 'page', 1),
100                         defaults($results, 'count', 1),
101                         defaults($results, 'itemsperpage', 1)
102                 );
103
104                 $profiles = defaults($results, 'profiles', []);
105
106                 foreach ($profiles as $profile) {
107                         $contactDetails = Contact::getDetailsByURL(defaults($profile, 'profile_url', ''), local_user());
108                         $itemUrl = (!empty($contactDetails['addr']) ? $contactDetails['addr'] : defaults($profile, 'profile_url', ''));
109
110                         $result = new ContactResult(
111                                 defaults($profile, 'name', ''),
112                                 defaults($profile, 'addr', ''),
113                                 $itemUrl,
114                                 defaults($profile, 'profile_url', ''),
115                                 defaults($profile, 'photo', ''),
116                                 Protocol::DFRN,
117                                 defaults($contactDetails, 'cid', 0),
118                                 0,
119                                 defaults($profile, 'tags', ''));
120
121                         $resultList->addResult($result);
122                 }
123
124                 return $resultList;
125         }
126
127         /**
128          * Search in the local database for occurrences of the search string
129          *
130          * @param string $search
131          * @param int    $start
132          * @param int    $itemPage
133          * @param bool   $community
134          *
135          * @return ResultList|null
136          * @throws HTTPException\InternalServerErrorException
137          */
138         public static function getContactsFromLocalDirectory($search, $start = 0, $itemPage = 80, $community = false)
139         {
140                 $config = self::getApp()->getConfig();
141
142                 $diaspora = $config->get('system', 'diaspora_enabled') ? Protocol::DIASPORA : Protocol::DFRN;
143                 $ostatus  = !$config->get('system', 'ostatus_disabled') ? Protocol::OSTATUS : Protocol::DFRN;
144
145                 $wildcard = Strings::escapeHtml('%' . $search . '%');
146
147                 $count = DBA::count('gcontact', [
148                         'NOT `hide`
149                         AND `network` IN (?, ?, ?, ?)
150                         AND ((`last_contact` >= `last_failure`) OR (`updated` >= `last_failure`))
151                         AND (`url` LIKE ? OR `name` LIKE ? OR `location` LIKE ? 
152                                 OR `addr` LIKE ? OR `about` LIKE ? OR `keywords` LIKE ?)
153                         AND `community` = ?',
154                         Protocol::ACTIVITYPUB, Protocol::DFRN, $ostatus, $diaspora,
155                         $wildcard, $wildcard, $wildcard,
156                         $wildcard, $wildcard, $wildcard,
157                         $community,
158                 ]);
159
160                 if (empty($count)) {
161                         return null;
162                 }
163
164                 $data = DBA::select('gcontact', ['nurl'], [
165                         'NOT `hide`
166                         AND `network` IN (?, ?, ?, ?)
167                         AND ((`last_contact` >= `last_failure`) OR (`updated` >= `last_failure`))
168                         AND (`url` LIKE ? OR `name` LIKE ? OR `location` LIKE ? 
169                                 OR `addr` LIKE ? OR `about` LIKE ? OR `keywords` LIKE ?)
170                         AND `community` = ?',
171                         Protocol::ACTIVITYPUB, Protocol::DFRN, $ostatus, $diaspora,
172                         $wildcard, $wildcard, $wildcard,
173                         $wildcard, $wildcard, $wildcard,
174                         $community,
175                 ], [
176                         'group_by' => ['nurl', 'updated'],
177                         'limit' => [$start, $itemPage],
178                         'order' => ['updated' => 'DESC']
179                 ]);
180
181                 if (!DBA::isResult($data)) {
182                         return null;
183                 }
184
185                 $resultList = new ResultList($start, $itemPage, $count);
186
187                 while ($row = DBA::fetch($data)) {
188                         if (PortableContact::alternateOStatusUrl($row["nurl"])) {
189                                 continue;
190                         }
191
192                         $urlParts = parse_url($row["nurl"]);
193
194                         // Ignore results that look strange.
195                         // For historic reasons the gcontact table does contain some garbage.
196                         if (!empty($urlParts['query']) || !empty($urlParts['fragment'])) {
197                                 continue;
198                         }
199
200                         $contact = Contact::getDetailsByURL($row["nurl"], local_user());
201
202                         if ($contact["name"] == "") {
203                                 $contact["name"] = end(explode("/", $urlParts["path"]));
204                         }
205
206                         $result = new ContactResult(
207                                 $contact["name"],
208                                 $contact["addr"],
209                                 $contact["addr"],
210                                 $contact["url"],
211                                 $contact["photo"],
212                                 $contact["network"],
213                                 $contact["cid"],
214                                 $contact["zid"],
215                                 $contact["keywords"]
216                         );
217
218                         $resultList->addResult($result);
219                 }
220
221                 DBA::close($data);
222
223                 // Add found profiles from the global directory to the local directory
224                 Worker::add(PRIORITY_LOW, 'DiscoverPoCo', "dirsearch", urlencode($search));
225
226                 return $resultList;
227         }
228 }