3 * @file src/Protocol/PortableContact.php
5 * @todo Move GNU Social URL schemata (http://server.tld/user/number) to http://server.tld/username
6 * @todo Fetch profile data from profile page for Redmatrix users
7 * @todo Detect if it is a forum
10 namespace Friendica\Protocol;
15 use Friendica\Content\Text\HTML;
16 use Friendica\Core\Config;
17 use Friendica\Core\Logger;
18 use Friendica\Core\Protocol;
19 use Friendica\Core\Worker;
20 use Friendica\Database\DBA;
21 use Friendica\Model\GContact;
22 use Friendica\Model\Profile;
23 use Friendica\Module\Register;
24 use Friendica\Network\Probe;
25 use Friendica\Util\DateTimeFormat;
26 use Friendica\Util\Network;
27 use Friendica\Util\Strings;
28 use Friendica\Util\XML;
33 * @brief Fetch POCO data
35 * @param integer $cid Contact ID
36 * @param integer $uid User ID
37 * @param integer $zcid Global Contact ID
38 * @param integer $url POCO address that should be polled
40 * Given a contact-id (minimum), load the PortableContacts friend list for that contact,
41 * and add the entries to the gcontact (Global Contact) table, or update existing entries
42 * if anything (name or photo) has changed.
43 * We use normalised urls for comparison which ignore http vs https and www.domain vs domain
45 * Once the global contact is stored add (if necessary) the contact linkage which associates
46 * the given uid, cid to the global contact entry. There can be many uid/cid combinations
47 * pointing to the same global contact id.
48 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
50 public static function loadWorker($cid, $uid = 0, $zcid = 0, $url = null)
52 // Call the function "load" via the worker
53 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "load", (int)$cid, (int)$uid, (int)$zcid, $url);
57 * @brief Fetch POCO data from the worker
59 * @param integer $cid Contact ID
60 * @param integer $uid User ID
61 * @param integer $zcid Global Contact ID
62 * @param integer $url POCO address that should be polled
63 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
65 public static function load($cid, $uid, $zcid, $url)
69 $contact = DBA::selectFirst('contact', ['poco', 'uid'], ['id' => $cid]);
70 if (DBA::isResult($contact)) {
71 $url = $contact['poco'];
72 $uid = $contact['uid'];
84 $url = $url . (($uid) ? '/@me/@all?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation' : '?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation');
86 Logger::log('load: ' . $url, Logger::DEBUG);
88 $fetchresult = Network::fetchUrlFull($url);
89 $s = $fetchresult->getBody();
91 Logger::log('load: returns ' . $s, Logger::DATA);
93 Logger::log('load: return code: ' . $fetchresult->getReturnCode(), Logger::DEBUG);
95 if (($fetchresult->getReturnCode() > 299) || (! $s)) {
99 $j = json_decode($s, true);
101 Logger::log('load: json: ' . print_r($j, true), Logger::DATA);
103 if (!isset($j['entry'])) {
108 foreach ($j['entry'] as $entry) {
115 $updated = DBA::NULL_DATETIME;
123 if (!empty($entry['displayName'])) {
124 $name = $entry['displayName'];
127 if (isset($entry['urls'])) {
128 foreach ($entry['urls'] as $url) {
129 if ($url['type'] == 'profile') {
130 $profile_url = $url['value'];
133 if ($url['type'] == 'webfinger') {
134 $connect_url = str_replace('acct:', '', $url['value']);
139 if (isset($entry['photos'])) {
140 foreach ($entry['photos'] as $photo) {
141 if ($photo['type'] == 'profile') {
142 $profile_photo = $photo['value'];
148 if (isset($entry['updated'])) {
149 $updated = date(DateTimeFormat::MYSQL, strtotime($entry['updated']));
152 if (isset($entry['network'])) {
153 $network = $entry['network'];
156 if (isset($entry['currentLocation'])) {
157 $location = $entry['currentLocation'];
160 if (isset($entry['aboutMe'])) {
161 $about = HTML::toBBCode($entry['aboutMe']);
164 if (isset($entry['gender'])) {
165 $gender = $entry['gender'];
168 if (isset($entry['generation']) && ($entry['generation'] > 0)) {
169 $generation = ++$entry['generation'];
172 if (isset($entry['tags'])) {
173 foreach ($entry['tags'] as $tag) {
174 $keywords = implode(", ", $tag);
178 if (isset($entry['contactType']) && ($entry['contactType'] >= 0)) {
179 $contact_type = $entry['contactType'];
182 $gcontact = ["url" => $profile_url,
184 "network" => $network,
185 "photo" => $profile_photo,
187 "location" => $location,
189 "keywords" => $keywords,
190 "connect" => $connect_url,
191 "updated" => $updated,
192 "contact-type" => $contact_type,
193 "generation" => $generation];
196 $gcontact = GContact::sanitize($gcontact);
197 $gcid = GContact::update($gcontact);
199 GContact::link($gcid, $uid, $cid, $zcid);
200 } catch (Exception $e) {
201 Logger::log($e->getMessage(), Logger::DEBUG);
204 Logger::log("load: loaded $total entries", Logger::DEBUG);
206 $condition = ["`cid` = ? AND `uid` = ? AND `zcid` = ? AND `updated` < UTC_TIMESTAMP - INTERVAL 2 DAY", $cid, $uid, $zcid];
207 DBA::delete('glink', $condition);
210 public static function reachable($profile, $server = "", $network = "", $force = false)
213 $server = self::detectServer($profile);
220 return self::checkServer($server, $network, $force);
223 public static function detectServer($profile)
225 // Try to detect the server path based upon some known standard paths
228 if ($server_url == "") {
229 $friendica = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $profile);
230 if ($friendica != $profile) {
231 $server_url = $friendica;
235 if ($server_url == "") {
236 $diaspora = preg_replace("=(https?://)(.*)/u/(.*)=ism", "$1$2", $profile);
237 if ($diaspora != $profile) {
238 $server_url = $diaspora;
242 if ($server_url == "") {
243 $red = preg_replace("=(https?://)(.*)/channel/(.*)=ism", "$1$2", $profile);
244 if ($red != $profile) {
250 if ($server_url == "") {
251 $mastodon = preg_replace("=(https?://)(.*)/users/(.*)=ism", "$1$2", $profile);
252 if ($mastodon != $profile) {
253 $server_url = $mastodon;
257 // Numeric OStatus variant
258 if ($server_url == "") {
259 $ostatus = preg_replace("=(https?://)(.*)/user/(.*)=ism", "$1$2", $profile);
260 if ($ostatus != $profile) {
261 $server_url = $ostatus;
266 if ($server_url == "") {
267 $base = preg_replace("=(https?://)(.*?)/(.*)=ism", "$1$2", $profile);
268 if ($base != $profile) {
273 if ($server_url == "") {
278 "SELECT `id` FROM `gserver` WHERE `nurl` = '%s' AND `last_contact` > `last_failure`",
279 DBA::escape(Strings::normaliseLink($server_url))
282 if (DBA::isResult($r)) {
286 // Fetch the host-meta to check if this really is a server
287 $curlResult = Network::curl($server_url."/.well-known/host-meta");
288 if (!$curlResult->isSuccess()) {
295 public static function alternateOStatusUrl($url)
297 return(preg_match("=https?://.+/user/\d+=ism", $url, $matches));
300 public static function lastUpdated($profile, $force = false)
303 "SELECT * FROM `gcontact` WHERE `nurl` = '%s'",
304 DBA::escape(Strings::normaliseLink($profile))
307 if (!DBA::isResult($gcontacts)) {
311 $contact = ["url" => $profile];
313 if ($gcontacts[0]["created"] <= DBA::NULL_DATETIME) {
314 $contact['created'] = DateTimeFormat::utcNow();
319 $server_url = Strings::normaliseLink(self::detectServer($profile));
322 if (($server_url == '') && ($gcontacts[0]["server_url"] != "")) {
323 $server_url = $gcontacts[0]["server_url"];
326 if (!$force && (($server_url == '') || ($gcontacts[0]["server_url"] == $gcontacts[0]["nurl"]))) {
327 $server_url = Strings::normaliseLink(self::detectServer($profile));
330 if (!in_array($gcontacts[0]["network"], [Protocol::DFRN, Protocol::DIASPORA, Protocol::FEED, Protocol::OSTATUS, ""])) {
331 Logger::log("Profile ".$profile.": Network type ".$gcontacts[0]["network"]." can't be checked", Logger::DEBUG);
335 if ($server_url != "") {
336 if (!self::checkServer($server_url, $gcontacts[0]["network"], $force)) {
338 $fields = ['last_failure' => DateTimeFormat::utcNow()];
339 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($profile)]);
342 Logger::log("Profile ".$profile.": Server ".$server_url." wasn't reachable.", Logger::DEBUG);
345 $contact['server_url'] = $server_url;
348 if (in_array($gcontacts[0]["network"], ["", Protocol::FEED])) {
350 "SELECT `network` FROM `gserver` WHERE `nurl` = '%s' AND `network` != ''",
351 DBA::escape(Strings::normaliseLink($server_url))
355 $contact['network'] = $server[0]["network"];
361 // noscrape is really fast so we don't cache the call.
362 if (($server_url != "") && ($gcontacts[0]["nick"] != "")) {
363 // Use noscrape if possible
364 $server = q("SELECT `noscrape`, `network` FROM `gserver` WHERE `nurl` = '%s' AND `noscrape` != ''", DBA::escape(Strings::normaliseLink($server_url)));
367 $curlResult = Network::curl($server[0]["noscrape"]."/".$gcontacts[0]["nick"]);
369 if ($curlResult->isSuccess() && ($curlResult->getBody() != "")) {
370 $noscrape = json_decode($curlResult->getBody(), true);
372 if (is_array($noscrape)) {
373 $contact["network"] = $server[0]["network"];
375 if (isset($noscrape["fn"])) {
376 $contact["name"] = $noscrape["fn"];
378 if (isset($noscrape["comm"])) {
379 $contact["community"] = $noscrape["comm"];
381 if (isset($noscrape["tags"])) {
382 $keywords = implode(" ", $noscrape["tags"]);
383 if ($keywords != "") {
384 $contact["keywords"] = $keywords;
388 $location = Profile::formatLocation($noscrape);
390 $contact["location"] = $location;
392 if (isset($noscrape["dfrn-notify"])) {
393 $contact["notify"] = $noscrape["dfrn-notify"];
395 // Remove all fields that are not present in the gcontact table
396 unset($noscrape["fn"]);
397 unset($noscrape["key"]);
398 unset($noscrape["homepage"]);
399 unset($noscrape["comm"]);
400 unset($noscrape["tags"]);
401 unset($noscrape["locality"]);
402 unset($noscrape["region"]);
403 unset($noscrape["country-name"]);
404 unset($noscrape["contacts"]);
405 unset($noscrape["dfrn-request"]);
406 unset($noscrape["dfrn-confirm"]);
407 unset($noscrape["dfrn-notify"]);
408 unset($noscrape["dfrn-poll"]);
410 // Set the date of the last contact
411 /// @todo By now the function "update_gcontact" doesn't work with this field
412 //$contact["last_contact"] = DateTimeFormat::utcNow();
414 $contact = array_merge($contact, $noscrape);
416 GContact::update($contact);
418 if (!empty($noscrape["updated"])) {
419 $fields = ['last_contact' => DateTimeFormat::utcNow()];
420 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($profile)]);
422 Logger::log("Profile ".$profile." was last updated at ".$noscrape["updated"]." (noscrape)", Logger::DEBUG);
424 return $noscrape["updated"];
431 // If we only can poll the feed, then we only do this once a while
432 if (!$force && !self::updateNeeded($gcontacts[0]["created"], $gcontacts[0]["updated"], $gcontacts[0]["last_failure"], $gcontacts[0]["last_contact"])) {
433 Logger::log("Profile ".$profile." was last updated at ".$gcontacts[0]["updated"]." (cached)", Logger::DEBUG);
435 GContact::update($contact);
436 return $gcontacts[0]["updated"];
439 $data = Probe::uri($profile);
441 // Is the profile link the alternate OStatus link notation? (http://domain.tld/user/4711)
442 // Then check the other link and delete this one
443 if (($data["network"] == Protocol::OSTATUS) && self::alternateOStatusUrl($profile)
444 && (Strings::normaliseLink($profile) == Strings::normaliseLink($data["alias"]))
445 && (Strings::normaliseLink($profile) != Strings::normaliseLink($data["url"]))
447 // Delete the old entry
448 DBA::delete('gcontact', ['nurl' => Strings::normaliseLink($profile)]);
450 $gcontact = array_merge($gcontacts[0], $data);
452 $gcontact["server_url"] = $data["baseurl"];
455 $gcontact = GContact::sanitize($gcontact);
456 GContact::update($gcontact);
458 self::lastUpdated($data["url"], $force);
459 } catch (Exception $e) {
460 Logger::log($e->getMessage(), Logger::DEBUG);
463 Logger::log("Profile ".$profile." was deleted", Logger::DEBUG);
467 if (($data["poll"] == "") || (in_array($data["network"], [Protocol::FEED, Protocol::PHANTOM]))) {
468 $fields = ['last_failure' => DateTimeFormat::utcNow()];
469 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($profile)]);
471 Logger::log("Profile ".$profile." wasn't reachable (profile)", Logger::DEBUG);
475 $contact = array_merge($contact, $data);
477 $contact["server_url"] = $data["baseurl"];
479 GContact::update($contact);
481 $curlResult = Network::curl($data["poll"]);
483 if (!$curlResult->isSuccess()) {
484 $fields = ['last_failure' => DateTimeFormat::utcNow()];
485 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($profile)]);
487 Logger::log("Profile ".$profile." wasn't reachable (no feed)", Logger::DEBUG);
491 $doc = new DOMDocument();
492 /// @TODO Avoid error supression here
493 @$doc->loadXML($curlResult->getBody());
495 $xpath = new DOMXPath($doc);
496 $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
498 $entries = $xpath->query('/atom:feed/atom:entry');
502 foreach ($entries as $entry) {
503 $published = DateTimeFormat::utc($xpath->query('atom:published/text()', $entry)->item(0)->nodeValue);
504 $updated = DateTimeFormat::utc($xpath->query('atom:updated/text()' , $entry)->item(0)->nodeValue);
506 if ($last_updated < $published) {
507 $last_updated = $published;
510 if ($last_updated < $updated) {
511 $last_updated = $updated;
515 // Maybe there aren't any entries. Then check if it is a valid feed
516 if ($last_updated == "") {
517 if ($xpath->query('/atom:feed')->length > 0) {
518 $last_updated = DBA::NULL_DATETIME;
522 $fields = ['last_contact' => DateTimeFormat::utcNow()];
524 if (!empty($last_updated)) {
525 $fields['updated'] = $last_updated;
528 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($profile)]);
530 if (($gcontacts[0]["generation"] == 0)) {
531 $fields = ['generation' => 9];
532 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($profile)]);
535 Logger::log("Profile ".$profile." was last updated at ".$last_updated, Logger::DEBUG);
537 return $last_updated;
540 public static function updateNeeded($created, $updated, $last_failure, $last_contact)
542 $now = strtotime(DateTimeFormat::utcNow());
544 if ($updated > $last_contact) {
545 $contact_time = strtotime($updated);
547 $contact_time = strtotime($last_contact);
550 $failure_time = strtotime($last_failure);
551 $created_time = strtotime($created);
553 // If there is no "created" time then use the current time
554 if ($created_time <= 0) {
555 $created_time = $now;
558 // If the last contact was less than 24 hours then don't update
559 if (($now - $contact_time) < (60 * 60 * 24)) {
563 // If the last failure was less than 24 hours then don't update
564 if (($now - $failure_time) < (60 * 60 * 24)) {
568 // If the last contact was less than a week ago and the last failure is older than a week then don't update
569 //if ((($now - $contact_time) < (60 * 60 * 24 * 7)) && ($contact_time > $failure_time))
572 // If the last contact time was more than a week ago and the contact was created more than a week ago, then only try once a week
573 if ((($now - $contact_time) > (60 * 60 * 24 * 7)) && (($now - $created_time) > (60 * 60 * 24 * 7)) && (($now - $failure_time) < (60 * 60 * 24 * 7))) {
577 // If the last contact time was more than a month ago and the contact was created more than a month ago, then only try once a month
578 if ((($now - $contact_time) > (60 * 60 * 24 * 30)) && (($now - $created_time) > (60 * 60 * 24 * 30)) && (($now - $failure_time) < (60 * 60 * 24 * 30))) {
585 /// @TODO Maybe move this out to an utilities class?
586 private static function toBoolean($val)
588 if (($val == "true") || ($val == 1)) {
590 } elseif (($val == "false") || ($val == 0)) {
598 * @brief Detect server type (Hubzilla or Friendica) via the poco data
600 * @param array $data POCO data
601 * @return array Server data
603 private static function detectPocoData(array $data)
605 if (!isset($data['entry'])) {
609 if (count($data['entry']) == 0) {
613 if (!isset($data['entry'][0]['urls'])) {
617 if (count($data['entry'][0]['urls']) == 0) {
621 foreach ($data['entry'][0]['urls'] as $url) {
622 if ($url['type'] == 'zot') {
624 $server["platform"] = 'Hubzilla';
625 $server["network"] = Protocol::DIASPORA;
633 * @brief Detect server type by using the nodeinfo data
635 * @param string $server_url address of the server
636 * @return array Server data
637 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
639 private static function fetchNodeinfo($server_url)
641 $curlResult = Network::curl($server_url."/.well-known/nodeinfo");
642 if (!$curlResult->isSuccess()) {
646 $nodeinfo = json_decode($curlResult->getBody(), true);
648 if (!is_array($nodeinfo) || !isset($nodeinfo['links'])) {
655 foreach ($nodeinfo['links'] as $link) {
656 if (!is_array($link) || empty($link['rel'])) {
657 Logger::log('Invalid nodeinfo format for ' . $server_url, Logger::DEBUG);
660 if ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
661 $nodeinfo1_url = $link['href'];
662 } elseif ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/2.0') {
663 $nodeinfo2_url = $link['href'];
667 if ($nodeinfo1_url . $nodeinfo2_url == '') {
673 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
674 if (!empty($nodeinfo2_url) && (parse_url($server_url, PHP_URL_HOST) == parse_url($nodeinfo2_url, PHP_URL_HOST))) {
675 $server = self::parseNodeinfo2($nodeinfo2_url);
678 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
679 if (empty($server) && !empty($nodeinfo1_url) && (parse_url($server_url, PHP_URL_HOST) == parse_url($nodeinfo1_url, PHP_URL_HOST))) {
680 $server = self::parseNodeinfo1($nodeinfo1_url);
687 * @brief Parses Nodeinfo 1
689 * @param string $nodeinfo_url address of the nodeinfo path
690 * @return array Server data
691 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
693 private static function parseNodeinfo1($nodeinfo_url)
695 $curlResult = Network::curl($nodeinfo_url);
697 if (!$curlResult->isSuccess()) {
701 $nodeinfo = json_decode($curlResult->getBody(), true);
703 if (!is_array($nodeinfo)) {
709 $server['register_policy'] = Register::CLOSED;
711 if (is_bool($nodeinfo['openRegistrations']) && $nodeinfo['openRegistrations']) {
712 $server['register_policy'] = Register::OPEN;
715 if (is_array($nodeinfo['software'])) {
716 if (isset($nodeinfo['software']['name'])) {
717 $server['platform'] = $nodeinfo['software']['name'];
720 if (isset($nodeinfo['software']['version'])) {
721 $server['version'] = $nodeinfo['software']['version'];
722 // Version numbers on Nodeinfo are presented with additional info, e.g.:
723 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
724 $server['version'] = preg_replace("=(.+)-(.{4,})=ism", "$1", $server['version']);
728 if (isset($nodeinfo['metadata']['nodeName'])) {
729 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
732 if (!empty($nodeinfo['usage']['users']['total'])) {
733 $server['registered-users'] = $nodeinfo['usage']['users']['total'];
740 if (is_array($nodeinfo['protocols']['inbound'])) {
741 foreach ($nodeinfo['protocols']['inbound'] as $inbound) {
742 if ($inbound == 'diaspora') {
745 if ($inbound == 'friendica') {
748 if ($inbound == 'gnusocial') {
755 $server['network'] = Protocol::OSTATUS;
758 $server['network'] = Protocol::DIASPORA;
761 $server['network'] = Protocol::DFRN;
772 * @brief Parses Nodeinfo 2
774 * @param string $nodeinfo_url address of the nodeinfo path
775 * @return array Server data
776 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
778 private static function parseNodeinfo2($nodeinfo_url)
780 $curlResult = Network::curl($nodeinfo_url);
781 if (!$curlResult->isSuccess()) {
785 $nodeinfo = json_decode($curlResult->getBody(), true);
787 if (!is_array($nodeinfo)) {
793 $server['register_policy'] = Register::CLOSED;
795 if (is_bool($nodeinfo['openRegistrations']) && $nodeinfo['openRegistrations']) {
796 $server['register_policy'] = Register::OPEN;
799 if (is_array($nodeinfo['software'])) {
800 if (isset($nodeinfo['software']['name'])) {
801 $server['platform'] = $nodeinfo['software']['name'];
804 if (isset($nodeinfo['software']['version'])) {
805 $server['version'] = $nodeinfo['software']['version'];
806 // Version numbers on Nodeinfo are presented with additional info, e.g.:
807 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
808 $server['version'] = preg_replace("=(.+)-(.{4,})=ism", "$1", $server['version']);
812 if (isset($nodeinfo['metadata']['nodeName'])) {
813 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
816 if (!empty($nodeinfo['usage']['users']['total'])) {
817 $server['registered-users'] = $nodeinfo['usage']['users']['total'];
824 if (!empty($nodeinfo['protocols'])) {
825 foreach ($nodeinfo['protocols'] as $protocol) {
826 if ($protocol == 'diaspora') {
828 } elseif ($protocol == 'friendica') {
830 } elseif ($protocol == 'gnusocial') {
837 $server['network'] = Protocol::OSTATUS;
838 } elseif ($diaspora) {
839 $server['network'] = Protocol::DIASPORA;
840 } elseif ($friendica) {
841 $server['network'] = Protocol::DFRN;
844 if (empty($server)) {
852 * @brief Detect server type (Hubzilla or Friendica) via the front page body
854 * @param string $body Front page of the server
855 * @return array Server data
857 private static function detectServerType($body)
861 $doc = new DOMDocument();
862 /// @TODO Acoid supressing error
863 @$doc->loadHTML($body);
864 $xpath = new DOMXPath($doc);
866 $list = $xpath->query("//meta[@name]");
868 foreach ($list as $node) {
870 if ($node->attributes->length) {
871 foreach ($node->attributes as $attribute) {
872 $attr[$attribute->name] = $attribute->value;
875 if ($attr['name'] == 'generator') {
876 $version_part = explode(" ", $attr['content']);
877 if (count($version_part) == 2) {
878 if (in_array($version_part[0], ["Friendika", "Friendica"])) {
880 $server["platform"] = $version_part[0];
881 $server["version"] = $version_part[1];
882 $server["network"] = Protocol::DFRN;
889 $list = $xpath->query("//meta[@property]");
891 foreach ($list as $node) {
893 if ($node->attributes->length) {
894 foreach ($node->attributes as $attribute) {
895 $attr[$attribute->name] = $attribute->value;
898 if ($attr['property'] == 'generator' && in_array($attr['content'], ["hubzilla", "BlaBlaNet"])) {
900 $server["platform"] = $attr['content'];
901 $server["version"] = "";
902 $server["network"] = Protocol::DIASPORA;
911 $server["site_name"] = XML::getFirstNodeValue($xpath, '//head/title/text()');
916 public static function checkServer($server_url, $network = "", $force = false)
918 // Unify the server address
919 $server_url = trim($server_url, "/");
920 $server_url = str_replace("/index.php", "", $server_url);
922 if ($server_url == "") {
926 $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($server_url)]);
927 if (DBA::isResult($gserver)) {
928 if ($gserver["created"] <= DBA::NULL_DATETIME) {
929 $fields = ['created' => DateTimeFormat::utcNow()];
930 $condition = ['nurl' => Strings::normaliseLink($server_url)];
931 DBA::update('gserver', $fields, $condition);
933 $poco = $gserver["poco"];
934 $noscrape = $gserver["noscrape"];
936 if ($network == "") {
937 $network = $gserver["network"];
940 $last_contact = $gserver["last_contact"];
941 $last_failure = $gserver["last_failure"];
942 $version = $gserver["version"];
943 $platform = $gserver["platform"];
944 $site_name = $gserver["site_name"];
945 $info = $gserver["info"];
946 $register_policy = $gserver["register_policy"];
947 $registered_users = $gserver["registered-users"];
949 // See discussion under https://forum.friendi.ca/display/0b6b25a8135aabc37a5a0f5684081633
950 // It can happen that a zero date is in the database, but storing it again is forbidden.
951 if ($last_contact < DBA::NULL_DATETIME) {
952 $last_contact = DBA::NULL_DATETIME;
955 if ($last_failure < DBA::NULL_DATETIME) {
956 $last_failure = DBA::NULL_DATETIME;
959 if (!$force && !self::updateNeeded($gserver["created"], "", $last_failure, $last_contact)) {
960 Logger::log("Use cached data for server ".$server_url, Logger::DEBUG);
961 return ($last_contact >= $last_failure);
970 $register_policy = -1;
971 $registered_users = 0;
973 $last_contact = DBA::NULL_DATETIME;
974 $last_failure = DBA::NULL_DATETIME;
976 Logger::log("Server ".$server_url." is outdated or unknown. Start discovery. Force: ".$force." Created: ".$gserver["created"]." Failure: ".$last_failure." Contact: ".$last_contact, Logger::DEBUG);
979 $possible_failure = false;
980 $orig_last_failure = $last_failure;
981 $orig_last_contact = $last_contact;
983 // Mastodon uses the "@" for user profiles.
984 // But this can be misunderstood.
985 if (parse_url($server_url, PHP_URL_USER) != '') {
986 DBA::update('gserver', ['last_failure' => DateTimeFormat::utcNow()], ['nurl' => Strings::normaliseLink($server_url)]);
990 // Check if the page is accessible via SSL.
991 $orig_server_url = $server_url;
992 $server_url = str_replace("http://", "https://", $server_url);
994 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
995 $curlResult = Network::curl($server_url."/.well-known/host-meta", false, $redirects, ['timeout' => 20]);
997 // Quit if there is a timeout.
998 // But we want to make sure to only quit if we are mostly sure that this server url fits.
999 if (DBA::isResult($gserver) && ($orig_server_url == $server_url) &&
1000 ($curlResult->isTimeout())) {
1001 Logger::log("Connection to server ".$server_url." timed out.", Logger::DEBUG);
1002 DBA::update('gserver', ['last_failure' => DateTimeFormat::utcNow()], ['nurl' => Strings::normaliseLink($server_url)]);
1006 // Maybe the page is unencrypted only?
1007 $xmlobj = @simplexml_load_string($curlResult->getBody(), 'SimpleXMLElement', 0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
1008 if (!$curlResult->isSuccess() || ($curlResult->getBody() == "") || empty($xmlobj) || !is_object($xmlobj)) {
1009 $server_url = str_replace("https://", "http://", $server_url);
1011 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
1012 $curlResult = Network::curl($server_url."/.well-known/host-meta", false, $redirects, ['timeout' => 20]);
1014 // Quit if there is a timeout
1015 if ($curlResult->isTimeout()) {
1016 Logger::log("Connection to server " . $server_url . " timed out.", Logger::DEBUG);
1017 DBA::update('gserver', ['last_failure' => DateTimeFormat::utcNow()], ['nurl' => Strings::normaliseLink($server_url)]);
1021 $xmlobj = @simplexml_load_string($curlResult->getBody(), 'SimpleXMLElement', 0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
1024 if (!$curlResult->isSuccess() || ($curlResult->getBody() == "") || empty($xmlobj) || !is_object($xmlobj)) {
1025 // Workaround for bad configured servers (known nginx problem)
1026 if (!empty($curlResult->getInfo()) && !in_array($curlResult->getInfo()["http_code"], ["403", "404"])) {
1030 $possible_failure = true;
1033 // If the server has no possible failure we reset the cached data
1034 if (!$possible_failure) {
1039 $register_policy = -1;
1043 // This will be too low, but better than no value at all.
1044 $registered_users = DBA::count('gcontact', ['server_url' => Strings::normaliseLink($server_url)]);
1049 $curlResult = Network::curl($server_url."/poco");
1051 if ($curlResult->isSuccess()) {
1052 $data = json_decode($curlResult->getBody(), true);
1054 if (isset($data['totalResults'])) {
1055 $registered_users = $data['totalResults'];
1056 $poco = $server_url . "/poco";
1057 $server = self::detectPocoData($data);
1059 if (!empty($server)) {
1060 $platform = $server['platform'];
1061 $network = $server['network'];
1068 * There are servers out there who don't return 404 on a failure
1069 * We have to be sure that don't misunderstand this
1071 if (is_null($data)) {
1080 // Test for Diaspora, Hubzilla, Mastodon or older Friendica servers
1081 $curlResult = Network::curl($server_url);
1083 if (!$curlResult->isSuccess() || ($curlResult->getBody() == "")) {
1086 $server = self::detectServerType($curlResult->getBody());
1088 if (!empty($server)) {
1089 $platform = $server['platform'];
1090 $network = $server['network'];
1091 $version = $server['version'];
1092 $site_name = $server['site_name'];
1095 $lines = explode("\n", $curlResult->getHeader());
1097 if (count($lines)) {
1098 foreach ($lines as $line) {
1099 $line = trim($line);
1101 if (stristr($line, 'X-Diaspora-Version:')) {
1102 $platform = "Diaspora";
1103 $version = trim(str_replace("X-Diaspora-Version:", "", $line));
1104 $version = trim(str_replace("x-diaspora-version:", "", $version));
1105 $network = Protocol::DIASPORA;
1106 $versionparts = explode("-", $version);
1107 $version = $versionparts[0];
1110 if (stristr($line, 'Server: Mastodon')) {
1111 $platform = "Mastodon";
1112 $network = Protocol::OSTATUS;
1119 if (!$failure && ($poco == "")) {
1120 // Test for Statusnet
1121 // Will also return data for Friendica and GNU Social - but it will be overwritten later
1122 // The "not implemented" is a special treatment for really, really old Friendica versions
1123 $curlResult = Network::curl($server_url."/api/statusnet/version.json");
1125 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1126 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1127 $platform = "StatusNet";
1128 // Remove junk that some GNU Social servers return
1129 $version = str_replace(chr(239).chr(187).chr(191), "", $curlResult->getBody());
1130 $version = trim($version, '"');
1131 $network = Protocol::OSTATUS;
1134 // Test for GNU Social
1135 $curlResult = Network::curl($server_url."/api/gnusocial/version.json");
1137 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1138 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1139 $platform = "GNU Social";
1140 // Remove junk that some GNU Social servers return
1141 $version = str_replace(chr(239) . chr(187) . chr(191), "", $curlResult->getBody());
1142 $version = trim($version, '"');
1143 $network = Protocol::OSTATUS;
1146 // Test for Mastodon
1147 $orig_version = $version;
1148 $curlResult = Network::curl($server_url . "/api/v1/instance");
1150 if ($curlResult->isSuccess() && ($curlResult->getBody() != '')) {
1151 $data = json_decode($curlResult->getBody(), true);
1153 if (isset($data['version'])) {
1154 $platform = "Mastodon";
1155 $version = defaults($data, 'version', '');
1156 $site_name = defaults($data, 'title', '');
1157 $info = defaults($data, 'description', '');
1158 $network = Protocol::OSTATUS;
1161 if (!empty($data['stats']['user_count'])) {
1162 $registered_users = $data['stats']['user_count'];
1166 if (strstr($orig_version . $version, 'Pleroma')) {
1167 $platform = 'Pleroma';
1168 $version = trim(str_replace('Pleroma', '', $version));
1173 // Test for Hubzilla and Red
1174 $curlResult = Network::curl($server_url . "/siteinfo.json");
1176 if ($curlResult->isSuccess()) {
1177 $data = json_decode($curlResult->getBody(), true);
1179 if (isset($data['url'])) {
1180 $platform = $data['platform'];
1181 $version = $data['version'];
1182 $network = Protocol::DIASPORA;
1185 if (!empty($data['site_name'])) {
1186 $site_name = $data['site_name'];
1189 if (!empty($data['channels_total'])) {
1190 $registered_users = $data['channels_total'];
1193 if (!empty($data['register_policy'])) {
1194 switch ($data['register_policy']) {
1195 case "REGISTER_OPEN":
1196 $register_policy = Register::OPEN;
1199 case "REGISTER_APPROVE":
1200 $register_policy = Register::APPROVE;
1203 case "REGISTER_CLOSED":
1205 $register_policy = Register::CLOSED;
1210 // Test for Hubzilla, Redmatrix or Friendica
1211 $curlResult = Network::curl($server_url."/api/statusnet/config.json");
1213 if ($curlResult->isSuccess()) {
1214 $data = json_decode($curlResult->getBody(), true);
1216 if (isset($data['site']['server'])) {
1217 if (isset($data['site']['platform'])) {
1218 $platform = $data['site']['platform']['PLATFORM_NAME'];
1219 $version = $data['site']['platform']['STD_VERSION'];
1220 $network = Protocol::DIASPORA;
1223 if (isset($data['site']['BlaBlaNet'])) {
1224 $platform = $data['site']['BlaBlaNet']['PLATFORM_NAME'];
1225 $version = $data['site']['BlaBlaNet']['STD_VERSION'];
1226 $network = Protocol::DIASPORA;
1229 if (isset($data['site']['hubzilla'])) {
1230 $platform = $data['site']['hubzilla']['PLATFORM_NAME'];
1231 $version = $data['site']['hubzilla']['RED_VERSION'];
1232 $network = Protocol::DIASPORA;
1235 if (isset($data['site']['redmatrix'])) {
1236 if (isset($data['site']['redmatrix']['PLATFORM_NAME'])) {
1237 $platform = $data['site']['redmatrix']['PLATFORM_NAME'];
1238 } elseif (isset($data['site']['redmatrix']['RED_PLATFORM'])) {
1239 $platform = $data['site']['redmatrix']['RED_PLATFORM'];
1242 $version = $data['site']['redmatrix']['RED_VERSION'];
1243 $network = Protocol::DIASPORA;
1246 if (isset($data['site']['friendica'])) {
1247 $platform = $data['site']['friendica']['FRIENDICA_PLATFORM'];
1248 $version = $data['site']['friendica']['FRIENDICA_VERSION'];
1249 $network = Protocol::DFRN;
1252 $site_name = $data['site']['name'];
1255 $inviteonly = false;
1258 if (!empty($data['site']['closed'])) {
1259 $closed = self::toBoolean($data['site']['closed']);
1262 if (!empty($data['site']['private'])) {
1263 $private = self::toBoolean($data['site']['private']);
1266 if (!empty($data['site']['inviteonly'])) {
1267 $inviteonly = self::toBoolean($data['site']['inviteonly']);
1270 if (!$closed && !$private and $inviteonly) {
1271 $register_policy = Register::APPROVE;
1272 } elseif (!$closed && !$private) {
1273 $register_policy = Register::OPEN;
1275 $register_policy = Register::CLOSED;
1282 // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
1284 $curlResult = Network::curl($server_url . "/statistics.json");
1286 if ($curlResult->isSuccess()) {
1287 $data = json_decode($curlResult->getBody(), true);
1289 if (isset($data['version'])) {
1290 $version = $data['version'];
1291 // Version numbers on statistics.json are presented with additional info, e.g.:
1292 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1293 $version = preg_replace("=(.+)-(.{4,})=ism", "$1", $version);
1296 if (!empty($data['name'])) {
1297 $site_name = $data['name'];
1300 if (!empty($data['network'])) {
1301 $platform = $data['network'];
1304 if ($platform == "Diaspora") {
1305 $network = Protocol::DIASPORA;
1308 if (!empty($data['registrations_open']) && $data['registrations_open']) {
1309 $register_policy = Register::OPEN;
1311 $register_policy = Register::CLOSED;
1316 // Query nodeinfo. Working for (at least) Diaspora and Friendica.
1318 $server = self::fetchNodeinfo($server_url);
1320 if (!empty($server)) {
1321 $register_policy = $server['register_policy'];
1323 if (isset($server['platform'])) {
1324 $platform = $server['platform'];
1327 if (isset($server['network'])) {
1328 $network = $server['network'];
1331 if (isset($server['version'])) {
1332 $version = $server['version'];
1335 if (isset($server['site_name'])) {
1336 $site_name = $server['site_name'];
1339 if (isset($server['registered-users'])) {
1340 $registered_users = $server['registered-users'];
1345 // Check for noscrape
1346 // Friendica servers could be detected as OStatus servers
1347 if (!$failure && in_array($network, [Protocol::DFRN, Protocol::OSTATUS])) {
1348 $curlResult = Network::curl($server_url . "/friendica/json");
1350 if (!$curlResult->isSuccess()) {
1351 $curlResult = Network::curl($server_url . "/friendika/json");
1354 if ($curlResult->isSuccess()) {
1355 $data = json_decode($curlResult->getBody(), true);
1357 if (isset($data['version'])) {
1358 $network = Protocol::DFRN;
1360 if (!empty($data['no_scrape_url'])) {
1361 $noscrape = $data['no_scrape_url'];
1364 $version = $data['version'];
1366 if (!empty($data['site_name'])) {
1367 $site_name = $data['site_name'];
1370 $info = defaults($data, 'info', '');
1372 $register_policy = defaults($data, 'register_policy', 'REGISTER_CLOSED');
1373 switch ($register_policy) {
1374 case 'REGISTER_OPEN':
1375 $register_policy = Register::OPEN;
1378 case 'REGISTER_APPROVE':
1379 $register_policy = Register::APPROVE;
1383 Logger::log("Register policy '$register_policy' from $server_url is invalid.");
1384 // Defaulting to closed
1386 case 'REGISTER_CLOSED':
1387 case 'REGISTER_INVITATION':
1388 $register_policy = Register::CLOSED;
1392 $platform = defaults($data, 'platform', '');
1397 // Every server has got at least an admin account
1398 if (!$failure && ($registered_users == 0)) {
1399 $registered_users = 1;
1402 if ($possible_failure && !$failure) {
1407 $last_contact = $orig_last_contact;
1408 $last_failure = DateTimeFormat::utcNow();
1410 $last_contact = DateTimeFormat::utcNow();
1411 $last_failure = $orig_last_failure;
1414 if (($last_contact <= $last_failure) && !$failure) {
1415 Logger::log("Server ".$server_url." seems to be alive, but last contact wasn't set - could be a bug", Logger::DEBUG);
1416 } elseif (($last_contact >= $last_failure) && $failure) {
1417 Logger::log("Server ".$server_url." seems to be dead, but last failure wasn't set - could be a bug", Logger::DEBUG);
1420 // Check again if the server exists
1421 $found = DBA::exists('gserver', ['nurl' => Strings::normaliseLink($server_url)]);
1423 $version = strip_tags($version);
1424 $site_name = strip_tags($site_name);
1425 $info = strip_tags($info);
1426 $platform = strip_tags($platform);
1428 $fields = ['url' => $server_url, 'version' => $version,
1429 'site_name' => $site_name, 'info' => $info, 'register_policy' => $register_policy,
1430 'poco' => $poco, 'noscrape' => $noscrape, 'network' => $network,
1431 'platform' => $platform, 'registered-users' => $registered_users,
1432 'last_contact' => $last_contact, 'last_failure' => $last_failure];
1435 DBA::update('gserver', $fields, ['nurl' => Strings::normaliseLink($server_url)]);
1436 } elseif (!$failure) {
1437 $fields['nurl'] = Strings::normaliseLink($server_url);
1438 $fields['created'] = DateTimeFormat::utcNow();
1439 DBA::insert('gserver', $fields);
1442 if (!$failure && in_array($fields['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
1443 self::discoverRelay($server_url);
1446 Logger::log("End discovery for server " . $server_url, Logger::DEBUG);
1452 * @brief Fetch relay data from a given server url
1454 * @param string $server_url address of the server
1455 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1457 private static function discoverRelay($server_url)
1459 Logger::log("Discover relay data for server " . $server_url, Logger::DEBUG);
1461 $curlResult = Network::curl($server_url . "/.well-known/x-social-relay");
1463 if (!$curlResult->isSuccess()) {
1467 $data = json_decode($curlResult->getBody(), true);
1469 if (!is_array($data)) {
1473 $gserver = DBA::selectFirst('gserver', ['id', 'relay-subscribe', 'relay-scope'], ['nurl' => Strings::normaliseLink($server_url)]);
1475 if (!DBA::isResult($gserver)) {
1479 if (($gserver['relay-subscribe'] != $data['subscribe']) || ($gserver['relay-scope'] != $data['scope'])) {
1480 $fields = ['relay-subscribe' => $data['subscribe'], 'relay-scope' => $data['scope']];
1481 DBA::update('gserver', $fields, ['id' => $gserver['id']]);
1484 DBA::delete('gserver-tag', ['gserver-id' => $gserver['id']]);
1486 if ($data['scope'] == 'tags') {
1489 foreach ($data['tags'] as $tag) {
1490 $tag = mb_strtolower($tag);
1491 if (strlen($tag) < 100) {
1496 foreach ($tags as $tag) {
1497 DBA::insert('gserver-tag', ['gserver-id' => $gserver['id'], 'tag' => $tag], true);
1501 // Create or update the relay contact
1503 if (isset($data['protocols'])) {
1504 if (isset($data['protocols']['diaspora'])) {
1505 $fields['network'] = Protocol::DIASPORA;
1507 if (isset($data['protocols']['diaspora']['receive'])) {
1508 $fields['batch'] = $data['protocols']['diaspora']['receive'];
1509 } elseif (is_string($data['protocols']['diaspora'])) {
1510 $fields['batch'] = $data['protocols']['diaspora'];
1514 if (isset($data['protocols']['dfrn'])) {
1515 $fields['network'] = Protocol::DFRN;
1517 if (isset($data['protocols']['dfrn']['receive'])) {
1518 $fields['batch'] = $data['protocols']['dfrn']['receive'];
1519 } elseif (is_string($data['protocols']['dfrn'])) {
1520 $fields['batch'] = $data['protocols']['dfrn'];
1524 Diaspora::setRelayContact($server_url, $fields);
1528 * @brief Returns a list of all known servers
1529 * @return array List of server urls
1532 public static function serverlist()
1535 "SELECT `url`, `site_name` AS `displayName`, `network`, `platform`, `version` FROM `gserver`
1536 WHERE `network` IN ('%s', '%s', '%s') AND `last_contact` > `last_failure`
1537 ORDER BY `last_contact`
1539 DBA::escape(Protocol::DFRN),
1540 DBA::escape(Protocol::DIASPORA),
1541 DBA::escape(Protocol::OSTATUS)
1544 if (!DBA::isResult($r)) {
1552 * @brief Fetch server list from remote servers and adds them when they are new.
1554 * @param string $poco URL to the POCO endpoint
1555 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1557 private static function fetchServerlist($poco)
1559 $curlResult = Network::curl($poco . "/@server");
1561 if (!$curlResult->isSuccess()) {
1565 $serverlist = json_decode($curlResult->getBody(), true);
1567 if (!is_array($serverlist)) {
1571 foreach ($serverlist as $server) {
1572 $server_url = str_replace("/index.php", "", $server['url']);
1574 $r = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", DBA::escape(Strings::normaliseLink($server_url)));
1576 if (!DBA::isResult($r)) {
1577 Logger::log("Call server check for server ".$server_url, Logger::DEBUG);
1578 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", $server_url);
1583 private static function discoverFederation()
1585 $last = Config::get('poco', 'last_federation_discovery');
1588 $next = $last + (24 * 60 * 60);
1590 if ($next > time()) {
1595 // Discover Friendica, Hubzilla and Diaspora servers
1596 $curlResult = Network::fetchUrl("http://the-federation.info/pods.json");
1598 if (!empty($curlResult)) {
1599 $servers = json_decode($curlResult, true);
1601 if (!empty($servers['pods'])) {
1602 foreach ($servers['pods'] as $server) {
1603 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", "https://" . $server['host']);
1608 // Disvover Mastodon servers
1609 if (!Config::get('system', 'ostatus_disabled')) {
1610 $accesstoken = Config::get('system', 'instances_social_key');
1612 if (!empty($accesstoken)) {
1613 $api = 'https://instances.social/api/1.0/instances/list?count=0';
1614 $header = ['Authorization: Bearer '.$accesstoken];
1615 $curlResult = Network::curl($api, false, $redirects, ['headers' => $header]);
1617 if ($curlResult->isSuccess()) {
1618 $servers = json_decode($curlResult->getBody(), true);
1620 foreach ($servers['instances'] as $server) {
1621 $url = (is_null($server['https_score']) ? 'http' : 'https') . '://' . $server['name'];
1622 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", $url);
1628 // Currently disabled, since the service isn't available anymore.
1629 // It is not removed since I hope that there will be a successor.
1630 // Discover GNU Social Servers.
1631 //if (!Config::get('system','ostatus_disabled')) {
1632 // $serverdata = "http://gstools.org/api/get_open_instances/";
1634 // $curlResult = Network::curl($serverdata);
1635 // if ($curlResult->isSuccess()) {
1636 // $servers = json_decode($result->getBody(), true);
1638 // foreach($servers['data'] as $server)
1639 // self::checkServer($server['instance_address']);
1643 Config::set('poco', 'last_federation_discovery', time());
1646 public static function discoverSingleServer($id)
1648 $r = q("SELECT `poco`, `nurl`, `url`, `network` FROM `gserver` WHERE `id` = %d", intval($id));
1650 if (!DBA::isResult($r)) {
1656 // Discover new servers out there (Works from Friendica version 3.5.2)
1657 self::fetchServerlist($server["poco"]);
1659 // Fetch all users from the other server
1660 $url = $server["poco"] . "/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1662 Logger::log("Fetch all users from the server " . $server["url"], Logger::DEBUG);
1664 $curlResult = Network::curl($url);
1666 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
1667 $data = json_decode($curlResult->getBody(), true);
1669 if (!empty($data)) {
1670 self::discoverServer($data, 2);
1673 if (Config::get('system', 'poco_discovery') > 1) {
1674 $timeframe = Config::get('system', 'poco_discovery_since');
1676 if ($timeframe == 0) {
1680 $updatedSince = date(DateTimeFormat::MYSQL, time() - $timeframe * 86400);
1682 // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1683 $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1687 $curlResult = Network::curl($url);
1689 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
1690 Logger::log("Fetch all global contacts from the server " . $server["nurl"], Logger::DEBUG);
1691 $data = json_decode($curlResult->getBody(), true);
1693 if (!empty($data)) {
1694 $success = self::discoverServer($data);
1698 if (!$success && (Config::get('system', 'poco_discovery') > 2)) {
1699 Logger::log("Fetch contacts from users of the server " . $server["nurl"], Logger::DEBUG);
1700 self::discoverServerUsers($data, $server);
1704 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1705 DBA::update('gserver', $fields, ['nurl' => $server["nurl"]]);
1709 // If the server hadn't replied correctly, then force a sanity check
1710 self::checkServer($server["url"], $server["network"], true);
1712 // If we couldn't reach the server, we will try it some time later
1713 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1714 DBA::update('gserver', $fields, ['nurl' => $server["nurl"]]);
1720 public static function discover($complete = false)
1722 // Update the server list
1723 self::discoverFederation();
1727 $requery_days = intval(Config::get('system', 'poco_requery_days'));
1729 if ($requery_days == 0) {
1733 $last_update = date('c', time() - (60 * 60 * 24 * $requery_days));
1735 $gservers = q("SELECT `id`, `url`, `nurl`, `network`
1737 WHERE `last_contact` >= `last_failure`
1739 AND `last_poco_query` < '%s'
1740 ORDER BY RAND()", DBA::escape($last_update)
1743 if (DBA::isResult($gservers)) {
1744 foreach ($gservers as $gserver) {
1745 if (!self::checkServer($gserver['url'], $gserver['network'])) {
1746 // The server is not reachable? Okay, then we will try it later
1747 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1748 DBA::update('gserver', $fields, ['nurl' => $gserver['nurl']]);
1752 Logger::log('Update directory from server ' . $gserver['url'] . ' with ID ' . $gserver['id'], Logger::DEBUG);
1753 Worker::add(PRIORITY_LOW, 'DiscoverPoCo', 'update_server_directory', (int) $gserver['id']);
1755 if (!$complete && ( --$no_of_queries == 0)) {
1762 private static function discoverServerUsers(array $data, array $server)
1764 if (!isset($data['entry'])) {
1768 foreach ($data['entry'] as $entry) {
1771 if (isset($entry['urls'])) {
1772 foreach ($entry['urls'] as $url) {
1773 if ($url['type'] == 'profile') {
1774 $profile_url = $url['value'];
1775 $path_array = explode('/', parse_url($profile_url, PHP_URL_PATH));
1776 $username = end($path_array);
1781 if ($username != '') {
1782 Logger::log('Fetch contacts for the user ' . $username . ' from the server ' . $server['nurl'], Logger::DEBUG);
1784 // Fetch all contacts from a given user from the other server
1785 $url = $server['poco'] . '/' . $username . '/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation';
1787 $curlResult = Network::curl($url);
1789 if ($curlResult->isSuccess()) {
1790 $data = json_decode($curlResult->getBody(), true);
1792 if (!empty($data)) {
1793 self::discoverServer($data, 3);
1800 private static function discoverServer(array $data, $default_generation = 0)
1802 if (empty($data['entry'])) {
1808 foreach ($data['entry'] as $entry) {
1810 $profile_photo = '';
1814 $updated = DBA::NULL_DATETIME;
1820 $generation = $default_generation;
1822 if (!empty($entry['displayName'])) {
1823 $name = $entry['displayName'];
1826 if (isset($entry['urls'])) {
1827 foreach ($entry['urls'] as $url) {
1828 if ($url['type'] == 'profile') {
1829 $profile_url = $url['value'];
1832 if ($url['type'] == 'webfinger') {
1833 $connect_url = str_replace('acct:' , '', $url['value']);
1839 if (isset($entry['photos'])) {
1840 foreach ($entry['photos'] as $photo) {
1841 if ($photo['type'] == 'profile') {
1842 $profile_photo = $photo['value'];
1848 if (isset($entry['updated'])) {
1849 $updated = date(DateTimeFormat::MYSQL, strtotime($entry['updated']));
1852 if (isset($entry['network'])) {
1853 $network = $entry['network'];
1856 if (isset($entry['currentLocation'])) {
1857 $location = $entry['currentLocation'];
1860 if (isset($entry['aboutMe'])) {
1861 $about = HTML::toBBCode($entry['aboutMe']);
1864 if (isset($entry['gender'])) {
1865 $gender = $entry['gender'];
1868 if (isset($entry['generation']) && ($entry['generation'] > 0)) {
1869 $generation = ++$entry['generation'];
1872 if (isset($entry['contactType']) && ($entry['contactType'] >= 0)) {
1873 $contact_type = $entry['contactType'];
1876 if (isset($entry['tags'])) {
1877 foreach ($entry['tags'] as $tag) {
1878 $keywords = implode(", ", $tag);
1882 if ($generation > 0) {
1885 Logger::log("Store profile ".$profile_url, Logger::DEBUG);
1887 $gcontact = ["url" => $profile_url,
1889 "network" => $network,
1890 "photo" => $profile_photo,
1892 "location" => $location,
1893 "gender" => $gender,
1894 "keywords" => $keywords,
1895 "connect" => $connect_url,
1896 "updated" => $updated,
1897 "contact-type" => $contact_type,
1898 "generation" => $generation];
1901 $gcontact = GContact::sanitize($gcontact);
1902 GContact::update($gcontact);
1903 } catch (Exception $e) {
1904 Logger::log($e->getMessage(), Logger::DEBUG);
1907 Logger::log("Done for profile ".$profile_url, Logger::DEBUG);