3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Protocol;
25 use Friendica\Content\Text\HTML;
26 use Friendica\Core\Logger;
27 use Friendica\Core\Protocol;
28 use Friendica\Core\Worker;
29 use Friendica\Database\DBA;
31 use Friendica\Model\GContact;
32 use Friendica\Model\GServer;
33 use Friendica\Util\DateTimeFormat;
34 use Friendica\Util\Network;
35 use Friendica\Util\Strings;
39 * @todo Move GNU Social URL schemata (http://server.tld/user/number) to http://server.tld/username
40 * @todo Fetch profile data from profile page for Redmatrix users
41 * @todo Detect if it is a forum
47 const USERS_GCONTACTS = 2;
48 const USERS_GCONTACTS_FALLBACK = 3;
53 * @param integer $cid Contact ID
54 * @param integer $uid User ID
55 * @param integer $zcid Global Contact ID
56 * @param integer $url POCO address that should be polled
58 * Given a contact-id (minimum), load the PortableContacts friend list for that contact,
59 * and add the entries to the gcontact (Global Contact) table, or update existing entries
60 * if anything (name or photo) has changed.
61 * We use normalised urls for comparison which ignore http vs https and www.domain vs domain
63 * Once the global contact is stored add (if necessary) the contact linkage which associates
64 * the given uid, cid to the global contact entry. There can be many uid/cid combinations
65 * pointing to the same global contact id.
66 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
68 public static function loadWorker($cid, $uid = 0, $zcid = 0, $url = null)
70 // Call the function "load" via the worker
71 Worker::add(PRIORITY_LOW, 'FetchPoCo', (int)$cid, (int)$uid, (int)$zcid, $url);
75 * Fetch POCO data from the worker
77 * @param integer $cid Contact ID
78 * @param integer $uid User ID
79 * @param integer $zcid Global Contact ID
80 * @param integer $url POCO address that should be polled
81 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
83 public static function load($cid, $uid, $zcid, $url)
87 $contact = DBA::selectFirst('contact', ['poco', 'uid'], ['id' => $cid]);
88 if (DBA::isResult($contact)) {
89 $url = $contact['poco'];
90 $uid = $contact['uid'];
102 $url = $url . (($uid) ? '/@me/@all?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,contactType,generation' : '?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,contactType,generation');
104 Logger::log('load: ' . $url, Logger::DEBUG);
106 $fetchresult = Network::fetchUrlFull($url);
107 $s = $fetchresult->getBody();
109 Logger::log('load: returns ' . $s, Logger::DATA);
111 Logger::log('load: return code: ' . $fetchresult->getReturnCode(), Logger::DEBUG);
113 if (($fetchresult->getReturnCode() > 299) || (! $s)) {
117 $j = json_decode($s, true);
119 Logger::debug('load', ['json' => $j]);
121 if (!isset($j['entry'])) {
126 foreach ($j['entry'] as $entry) {
133 $updated = DBA::NULL_DATETIME;
140 if (!empty($entry['displayName'])) {
141 $name = $entry['displayName'];
144 if (isset($entry['urls'])) {
145 foreach ($entry['urls'] as $url) {
146 if ($url['type'] == 'profile') {
147 $profile_url = $url['value'];
150 if ($url['type'] == 'webfinger') {
151 $connect_url = str_replace('acct:', '', $url['value']);
156 if (isset($entry['photos'])) {
157 foreach ($entry['photos'] as $photo) {
158 if ($photo['type'] == 'profile') {
159 $profile_photo = $photo['value'];
165 if (isset($entry['updated'])) {
166 $updated = date(DateTimeFormat::MYSQL, strtotime($entry['updated']));
169 if (isset($entry['network'])) {
170 $network = $entry['network'];
173 if (isset($entry['currentLocation'])) {
174 $location = $entry['currentLocation'];
177 if (isset($entry['aboutMe'])) {
178 $about = HTML::toBBCode($entry['aboutMe']);
181 if (isset($entry['generation']) && ($entry['generation'] > 0)) {
182 $generation = ++$entry['generation'];
185 if (isset($entry['tags'])) {
186 foreach ($entry['tags'] as $tag) {
187 $keywords = implode(", ", $tag);
191 if (isset($entry['contactType']) && ($entry['contactType'] >= 0)) {
192 $contact_type = $entry['contactType'];
195 $gcontact = ["url" => $profile_url,
197 "network" => $network,
198 "photo" => $profile_photo,
200 "location" => $location,
201 "keywords" => $keywords,
202 "connect" => $connect_url,
203 "updated" => $updated,
204 "contact-type" => $contact_type,
205 "generation" => $generation];
208 $gcontact = GContact::sanitize($gcontact);
209 $gcid = GContact::update($gcontact);
211 GContact::link($gcid, $uid, $cid, $zcid);
212 } catch (Exception $e) {
213 Logger::log($e->getMessage(), Logger::DEBUG);
216 Logger::log("load: loaded $total entries", Logger::DEBUG);
218 $condition = ["`cid` = ? AND `uid` = ? AND `zcid` = ? AND `updated` < UTC_TIMESTAMP - INTERVAL 2 DAY", $cid, $uid, $zcid];
219 DBA::delete('glink', $condition);
223 * Returns a list of all known servers
224 * @return array List of server urls
227 public static function serverlist()
230 "SELECT `url`, `site_name` AS `displayName`, `network`, `platform`, `version` FROM `gserver`
231 WHERE `network` IN ('%s', '%s', '%s') AND `last_contact` > `last_failure`
232 ORDER BY `last_contact`
234 DBA::escape(Protocol::DFRN),
235 DBA::escape(Protocol::DIASPORA),
236 DBA::escape(Protocol::OSTATUS)
239 if (!DBA::isResult($r)) {
247 * Fetch server list from remote servers and adds them when they are new.
249 * @param string $poco URL to the POCO endpoint
250 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
252 private static function fetchServerlist($poco)
254 $curlResult = Network::curl($poco . "/@server");
256 if (!$curlResult->isSuccess()) {
260 $serverlist = json_decode($curlResult->getBody(), true);
262 if (!is_array($serverlist)) {
266 foreach ($serverlist as $server) {
267 $server_url = str_replace("/index.php", "", $server['url']);
269 $r = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", DBA::escape(Strings::normaliseLink($server_url)));
271 if (!DBA::isResult($r)) {
272 Logger::log("Call server check for server ".$server_url, Logger::DEBUG);
273 Worker::add(PRIORITY_LOW, 'UpdateGServer', $server_url);
278 public static function discoverSingleServer($id)
280 $server = DBA::selectFirst('gserver', ['poco', 'nurl', 'url', 'network'], ['id' => $id]);
282 if (!DBA::isResult($server)) {
286 // Discover new servers out there (Works from Friendica version 3.5.2)
287 self::fetchServerlist($server["poco"]);
289 // Fetch all users from the other server
290 $url = $server["poco"] . "/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,contactType,generation";
292 Logger::info("Fetch all users from the server " . $server["url"]);
294 $curlResult = Network::curl($url);
296 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
297 $data = json_decode($curlResult->getBody(), true);
300 self::discoverServer($data, 2);
303 if (DI::config()->get('system', 'poco_discovery') >= self::USERS_GCONTACTS) {
304 $timeframe = DI::config()->get('system', 'poco_discovery_since');
306 if ($timeframe == 0) {
310 $updatedSince = date(DateTimeFormat::MYSQL, time() - $timeframe * 86400);
312 // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
313 $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,contactType,generation";
317 $curlResult = Network::curl($url);
319 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
320 Logger::info("Fetch all global contacts from the server " . $server["nurl"]);
321 $data = json_decode($curlResult->getBody(), true);
324 $success = self::discoverServer($data);
328 if (!$success && !empty($data) && DI::config()->get('system', 'poco_discovery') >= self::USERS_GCONTACTS_FALLBACK) {
329 Logger::info("Fetch contacts from users of the server " . $server["nurl"]);
330 self::discoverServerUsers($data, $server);
334 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
335 DBA::update('gserver', $fields, ['nurl' => $server["nurl"]]);
339 // If the server hadn't replied correctly, then force a sanity check
340 GServer::check($server["url"], $server["network"], true);
342 // If we couldn't reach the server, we will try it some time later
343 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
344 DBA::update('gserver', $fields, ['nurl' => $server["nurl"]]);
350 private static function discoverServerUsers(array $data, array $server)
352 if (!isset($data['entry'])) {
356 foreach ($data['entry'] as $entry) {
359 if (isset($entry['urls'])) {
360 foreach ($entry['urls'] as $url) {
361 if ($url['type'] == 'profile') {
362 $profile_url = $url['value'];
363 $path_array = explode('/', parse_url($profile_url, PHP_URL_PATH));
364 $username = end($path_array);
369 if ($username != '') {
370 Logger::log('Fetch contacts for the user ' . $username . ' from the server ' . $server['nurl'], Logger::DEBUG);
372 // Fetch all contacts from a given user from the other server
373 $url = $server['poco'] . '/' . $username . '/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,contactType,generation';
375 $curlResult = Network::curl($url);
377 if ($curlResult->isSuccess()) {
378 $data = json_decode($curlResult->getBody(), true);
381 self::discoverServer($data, 3);
388 private static function discoverServer(array $data, $default_generation = 0)
390 if (empty($data['entry'])) {
396 foreach ($data['entry'] as $entry) {
402 $updated = DBA::NULL_DATETIME;
407 $generation = $default_generation;
409 if (!empty($entry['displayName'])) {
410 $name = $entry['displayName'];
413 if (isset($entry['urls'])) {
414 foreach ($entry['urls'] as $url) {
415 if ($url['type'] == 'profile') {
416 $profile_url = $url['value'];
419 if ($url['type'] == 'webfinger') {
420 $connect_url = str_replace('acct:' , '', $url['value']);
426 if (isset($entry['photos'])) {
427 foreach ($entry['photos'] as $photo) {
428 if ($photo['type'] == 'profile') {
429 $profile_photo = $photo['value'];
435 if (isset($entry['updated'])) {
436 $updated = date(DateTimeFormat::MYSQL, strtotime($entry['updated']));
439 if (isset($entry['network'])) {
440 $network = $entry['network'];
443 if (isset($entry['currentLocation'])) {
444 $location = $entry['currentLocation'];
447 if (isset($entry['aboutMe'])) {
448 $about = HTML::toBBCode($entry['aboutMe']);
451 if (isset($entry['generation']) && ($entry['generation'] > 0)) {
452 $generation = ++$entry['generation'];
455 if (isset($entry['contactType']) && ($entry['contactType'] >= 0)) {
456 $contact_type = $entry['contactType'];
459 if (isset($entry['tags'])) {
460 foreach ($entry['tags'] as $tag) {
461 $keywords = implode(", ", $tag);
465 if ($generation > 0) {
468 Logger::log("Store profile ".$profile_url, Logger::DEBUG);
470 $gcontact = ["url" => $profile_url,
472 "network" => $network,
473 "photo" => $profile_photo,
475 "location" => $location,
476 "keywords" => $keywords,
477 "connect" => $connect_url,
478 "updated" => $updated,
479 "contact-type" => $contact_type,
480 "generation" => $generation];
483 $gcontact = GContact::sanitize($gcontact);
484 GContact::update($gcontact);
485 } catch (Exception $e) {
486 Logger::log($e->getMessage(), Logger::DEBUG);
489 Logger::log("Done for profile ".$profile_url, Logger::DEBUG);