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;
34 const USERS_GCONTACTS = 2;
35 const USERS_GCONTACTS_FALLBACK = 3;
38 * @brief Fetch POCO data
40 * @param integer $cid Contact ID
41 * @param integer $uid User ID
42 * @param integer $zcid Global Contact ID
43 * @param integer $url POCO address that should be polled
45 * Given a contact-id (minimum), load the PortableContacts friend list for that contact,
46 * and add the entries to the gcontact (Global Contact) table, or update existing entries
47 * if anything (name or photo) has changed.
48 * We use normalised urls for comparison which ignore http vs https and www.domain vs domain
50 * Once the global contact is stored add (if necessary) the contact linkage which associates
51 * the given uid, cid to the global contact entry. There can be many uid/cid combinations
52 * pointing to the same global contact id.
53 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
55 public static function loadWorker($cid, $uid = 0, $zcid = 0, $url = null)
57 // Call the function "load" via the worker
58 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "load", (int)$cid, (int)$uid, (int)$zcid, $url);
62 * @brief Fetch POCO data from the worker
64 * @param integer $cid Contact ID
65 * @param integer $uid User ID
66 * @param integer $zcid Global Contact ID
67 * @param integer $url POCO address that should be polled
68 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
70 public static function load($cid, $uid, $zcid, $url)
74 $contact = DBA::selectFirst('contact', ['poco', 'uid'], ['id' => $cid]);
75 if (DBA::isResult($contact)) {
76 $url = $contact['poco'];
77 $uid = $contact['uid'];
89 $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');
91 Logger::log('load: ' . $url, Logger::DEBUG);
93 $fetchresult = Network::fetchUrlFull($url);
94 $s = $fetchresult->getBody();
96 Logger::log('load: returns ' . $s, Logger::DATA);
98 Logger::log('load: return code: ' . $fetchresult->getReturnCode(), Logger::DEBUG);
100 if (($fetchresult->getReturnCode() > 299) || (! $s)) {
104 $j = json_decode($s, true);
106 Logger::log('load: json: ' . print_r($j, true), Logger::DATA);
108 if (!isset($j['entry'])) {
113 foreach ($j['entry'] as $entry) {
120 $updated = DBA::NULL_DATETIME;
128 if (!empty($entry['displayName'])) {
129 $name = $entry['displayName'];
132 if (isset($entry['urls'])) {
133 foreach ($entry['urls'] as $url) {
134 if ($url['type'] == 'profile') {
135 $profile_url = $url['value'];
138 if ($url['type'] == 'webfinger') {
139 $connect_url = str_replace('acct:', '', $url['value']);
144 if (isset($entry['photos'])) {
145 foreach ($entry['photos'] as $photo) {
146 if ($photo['type'] == 'profile') {
147 $profile_photo = $photo['value'];
153 if (isset($entry['updated'])) {
154 $updated = date(DateTimeFormat::MYSQL, strtotime($entry['updated']));
157 if (isset($entry['network'])) {
158 $network = $entry['network'];
161 if (isset($entry['currentLocation'])) {
162 $location = $entry['currentLocation'];
165 if (isset($entry['aboutMe'])) {
166 $about = HTML::toBBCode($entry['aboutMe']);
169 if (isset($entry['gender'])) {
170 $gender = $entry['gender'];
173 if (isset($entry['generation']) && ($entry['generation'] > 0)) {
174 $generation = ++$entry['generation'];
177 if (isset($entry['tags'])) {
178 foreach ($entry['tags'] as $tag) {
179 $keywords = implode(", ", $tag);
183 if (isset($entry['contactType']) && ($entry['contactType'] >= 0)) {
184 $contact_type = $entry['contactType'];
187 $gcontact = ["url" => $profile_url,
189 "network" => $network,
190 "photo" => $profile_photo,
192 "location" => $location,
194 "keywords" => $keywords,
195 "connect" => $connect_url,
196 "updated" => $updated,
197 "contact-type" => $contact_type,
198 "generation" => $generation];
201 $gcontact = GContact::sanitize($gcontact);
202 $gcid = GContact::update($gcontact);
204 GContact::link($gcid, $uid, $cid, $zcid);
205 } catch (Exception $e) {
206 Logger::log($e->getMessage(), Logger::DEBUG);
209 Logger::log("load: loaded $total entries", Logger::DEBUG);
211 $condition = ["`cid` = ? AND `uid` = ? AND `zcid` = ? AND `updated` < UTC_TIMESTAMP - INTERVAL 2 DAY", $cid, $uid, $zcid];
212 DBA::delete('glink', $condition);
215 public static function reachable($profile, $server = "", $network = "", $force = false)
218 $server = self::detectServer($profile);
225 return self::checkServer($server, $network, $force);
228 public static function detectServer($profile)
230 // Try to detect the server path based upon some known standard paths
233 if ($server_url == "") {
234 $friendica = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $profile);
235 if ($friendica != $profile) {
236 $server_url = $friendica;
240 if ($server_url == "") {
241 $diaspora = preg_replace("=(https?://)(.*)/u/(.*)=ism", "$1$2", $profile);
242 if ($diaspora != $profile) {
243 $server_url = $diaspora;
247 if ($server_url == "") {
248 $red = preg_replace("=(https?://)(.*)/channel/(.*)=ism", "$1$2", $profile);
249 if ($red != $profile) {
255 if ($server_url == "") {
256 $mastodon = preg_replace("=(https?://)(.*)/users/(.*)=ism", "$1$2", $profile);
257 if ($mastodon != $profile) {
258 $server_url = $mastodon;
262 // Numeric OStatus variant
263 if ($server_url == "") {
264 $ostatus = preg_replace("=(https?://)(.*)/user/(.*)=ism", "$1$2", $profile);
265 if ($ostatus != $profile) {
266 $server_url = $ostatus;
271 if ($server_url == "") {
272 $base = preg_replace("=(https?://)(.*?)/(.*)=ism", "$1$2", $profile);
273 if ($base != $profile) {
278 if ($server_url == "") {
283 "SELECT `id` FROM `gserver` WHERE `nurl` = '%s' AND `last_contact` > `last_failure`",
284 DBA::escape(Strings::normaliseLink($server_url))
287 if (DBA::isResult($r)) {
291 // Fetch the host-meta to check if this really is a server
292 $curlResult = Network::curl($server_url."/.well-known/host-meta");
293 if (!$curlResult->isSuccess()) {
300 public static function alternateOStatusUrl($url)
302 return(preg_match("=https?://.+/user/\d+=ism", $url, $matches));
305 public static function lastUpdated($profile, $force = false)
308 "SELECT * FROM `gcontact` WHERE `nurl` = '%s'",
309 DBA::escape(Strings::normaliseLink($profile))
312 if (!DBA::isResult($gcontacts)) {
316 $contact = ["url" => $profile];
318 if ($gcontacts[0]["created"] <= DBA::NULL_DATETIME) {
319 $contact['created'] = DateTimeFormat::utcNow();
324 $server_url = Strings::normaliseLink(self::detectServer($profile));
327 if (($server_url == '') && ($gcontacts[0]["server_url"] != "")) {
328 $server_url = $gcontacts[0]["server_url"];
331 if (!$force && (($server_url == '') || ($gcontacts[0]["server_url"] == $gcontacts[0]["nurl"]))) {
332 $server_url = Strings::normaliseLink(self::detectServer($profile));
335 if (!in_array($gcontacts[0]["network"], [Protocol::DFRN, Protocol::DIASPORA, Protocol::FEED, Protocol::OSTATUS, ""])) {
336 Logger::log("Profile ".$profile.": Network type ".$gcontacts[0]["network"]." can't be checked", Logger::DEBUG);
340 if ($server_url != "") {
341 if (!self::checkServer($server_url, $gcontacts[0]["network"], $force)) {
343 $fields = ['last_failure' => DateTimeFormat::utcNow()];
344 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($profile)]);
347 Logger::log("Profile ".$profile.": Server ".$server_url." wasn't reachable.", Logger::DEBUG);
350 $contact['server_url'] = $server_url;
353 if (in_array($gcontacts[0]["network"], ["", Protocol::FEED])) {
355 "SELECT `network` FROM `gserver` WHERE `nurl` = '%s' AND `network` != ''",
356 DBA::escape(Strings::normaliseLink($server_url))
360 $contact['network'] = $server[0]["network"];
366 // noscrape is really fast so we don't cache the call.
367 if (($server_url != "") && ($gcontacts[0]["nick"] != "")) {
368 // Use noscrape if possible
369 $server = q("SELECT `noscrape`, `network` FROM `gserver` WHERE `nurl` = '%s' AND `noscrape` != ''", DBA::escape(Strings::normaliseLink($server_url)));
372 $curlResult = Network::curl($server[0]["noscrape"]."/".$gcontacts[0]["nick"]);
374 if ($curlResult->isSuccess() && ($curlResult->getBody() != "")) {
375 $noscrape = json_decode($curlResult->getBody(), true);
377 if (is_array($noscrape)) {
378 $contact["network"] = $server[0]["network"];
380 if (isset($noscrape["fn"])) {
381 $contact["name"] = $noscrape["fn"];
383 if (isset($noscrape["comm"])) {
384 $contact["community"] = $noscrape["comm"];
386 if (isset($noscrape["tags"])) {
387 $keywords = implode(" ", $noscrape["tags"]);
388 if ($keywords != "") {
389 $contact["keywords"] = $keywords;
393 $location = Profile::formatLocation($noscrape);
395 $contact["location"] = $location;
397 if (isset($noscrape["dfrn-notify"])) {
398 $contact["notify"] = $noscrape["dfrn-notify"];
400 // Remove all fields that are not present in the gcontact table
401 unset($noscrape["fn"]);
402 unset($noscrape["key"]);
403 unset($noscrape["homepage"]);
404 unset($noscrape["comm"]);
405 unset($noscrape["tags"]);
406 unset($noscrape["locality"]);
407 unset($noscrape["region"]);
408 unset($noscrape["country-name"]);
409 unset($noscrape["contacts"]);
410 unset($noscrape["dfrn-request"]);
411 unset($noscrape["dfrn-confirm"]);
412 unset($noscrape["dfrn-notify"]);
413 unset($noscrape["dfrn-poll"]);
415 // Set the date of the last contact
416 /// @todo By now the function "update_gcontact" doesn't work with this field
417 //$contact["last_contact"] = DateTimeFormat::utcNow();
419 $contact = array_merge($contact, $noscrape);
421 GContact::update($contact);
423 if (!empty($noscrape["updated"])) {
424 $fields = ['last_contact' => DateTimeFormat::utcNow()];
425 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($profile)]);
427 Logger::log("Profile ".$profile." was last updated at ".$noscrape["updated"]." (noscrape)", Logger::DEBUG);
429 return $noscrape["updated"];
436 // If we only can poll the feed, then we only do this once a while
437 if (!$force && !self::updateNeeded($gcontacts[0]["created"], $gcontacts[0]["updated"], $gcontacts[0]["last_failure"], $gcontacts[0]["last_contact"])) {
438 Logger::log("Profile ".$profile." was last updated at ".$gcontacts[0]["updated"]." (cached)", Logger::DEBUG);
440 GContact::update($contact);
441 return $gcontacts[0]["updated"];
444 $data = Probe::uri($profile);
446 // Is the profile link the alternate OStatus link notation? (http://domain.tld/user/4711)
447 // Then check the other link and delete this one
448 if (($data["network"] == Protocol::OSTATUS) && self::alternateOStatusUrl($profile)
449 && (Strings::normaliseLink($profile) == Strings::normaliseLink($data["alias"]))
450 && (Strings::normaliseLink($profile) != Strings::normaliseLink($data["url"]))
452 // Delete the old entry
453 DBA::delete('gcontact', ['nurl' => Strings::normaliseLink($profile)]);
455 $gcontact = array_merge($gcontacts[0], $data);
457 $gcontact["server_url"] = $data["baseurl"];
460 $gcontact = GContact::sanitize($gcontact);
461 GContact::update($gcontact);
463 self::lastUpdated($data["url"], $force);
464 } catch (Exception $e) {
465 Logger::log($e->getMessage(), Logger::DEBUG);
468 Logger::log("Profile ".$profile." was deleted", Logger::DEBUG);
472 if (($data["poll"] == "") || (in_array($data["network"], [Protocol::FEED, Protocol::PHANTOM]))) {
473 $fields = ['last_failure' => DateTimeFormat::utcNow()];
474 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($profile)]);
476 Logger::log("Profile ".$profile." wasn't reachable (profile)", Logger::DEBUG);
480 $contact = array_merge($contact, $data);
482 $contact["server_url"] = $data["baseurl"];
484 GContact::update($contact);
486 $curlResult = Network::curl($data["poll"]);
488 if (!$curlResult->isSuccess()) {
489 $fields = ['last_failure' => DateTimeFormat::utcNow()];
490 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($profile)]);
492 Logger::log("Profile ".$profile." wasn't reachable (no feed)", Logger::DEBUG);
496 $doc = new DOMDocument();
497 /// @TODO Avoid error supression here
498 @$doc->loadXML($curlResult->getBody());
500 $xpath = new DOMXPath($doc);
501 $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
503 $entries = $xpath->query('/atom:feed/atom:entry');
507 foreach ($entries as $entry) {
508 $published_item = $xpath->query('atom:published/text()', $entry)->item(0);
509 $updated_item = $xpath->query('atom:updated/text()' , $entry)->item(0);
510 $published = isset($published_item->nodeValue) ? DateTimeFormat::utc($published_item->nodeValue) : null;
511 $updated = isset($updated_item->nodeValue) ? DateTimeFormat::utc($updated_item->nodeValue) : null;
513 if (!isset($published) || !isset($updated)) {
514 Logger::notice('Invalid entry for XPath.', ['entry' => $entry, 'profile' => $profile]);
518 if ($last_updated < $published) {
519 $last_updated = $published;
522 if ($last_updated < $updated) {
523 $last_updated = $updated;
527 // Maybe there aren't any entries. Then check if it is a valid feed
528 if ($last_updated == "") {
529 if ($xpath->query('/atom:feed')->length > 0) {
530 $last_updated = DBA::NULL_DATETIME;
534 $fields = ['last_contact' => DateTimeFormat::utcNow()];
536 if (!empty($last_updated)) {
537 $fields['updated'] = $last_updated;
540 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($profile)]);
542 if (($gcontacts[0]["generation"] == 0)) {
543 $fields = ['generation' => 9];
544 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($profile)]);
547 Logger::log("Profile ".$profile." was last updated at ".$last_updated, Logger::DEBUG);
549 return $last_updated;
552 public static function updateNeeded($created, $updated, $last_failure, $last_contact)
554 $now = strtotime(DateTimeFormat::utcNow());
556 if ($updated > $last_contact) {
557 $contact_time = strtotime($updated);
559 $contact_time = strtotime($last_contact);
562 $failure_time = strtotime($last_failure);
563 $created_time = strtotime($created);
565 // If there is no "created" time then use the current time
566 if ($created_time <= 0) {
567 $created_time = $now;
570 // If the last contact was less than 24 hours then don't update
571 if (($now - $contact_time) < (60 * 60 * 24)) {
575 // If the last failure was less than 24 hours then don't update
576 if (($now - $failure_time) < (60 * 60 * 24)) {
580 // If the last contact was less than a week ago and the last failure is older than a week then don't update
581 //if ((($now - $contact_time) < (60 * 60 * 24 * 7)) && ($contact_time > $failure_time))
584 // 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
585 if ((($now - $contact_time) > (60 * 60 * 24 * 7)) && (($now - $created_time) > (60 * 60 * 24 * 7)) && (($now - $failure_time) < (60 * 60 * 24 * 7))) {
589 // 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
590 if ((($now - $contact_time) > (60 * 60 * 24 * 30)) && (($now - $created_time) > (60 * 60 * 24 * 30)) && (($now - $failure_time) < (60 * 60 * 24 * 30))) {
597 /// @TODO Maybe move this out to an utilities class?
598 private static function toBoolean($val)
600 if (($val == "true") || ($val == 1)) {
602 } elseif (($val == "false") || ($val == 0)) {
610 * @brief Detect server type (Hubzilla or Friendica) via the poco data
612 * @param array $data POCO data
613 * @return array Server data
615 private static function detectPocoData(array $data)
617 if (!isset($data['entry'])) {
621 if (count($data['entry']) == 0) {
625 if (!isset($data['entry'][0]['urls'])) {
629 if (count($data['entry'][0]['urls']) == 0) {
633 foreach ($data['entry'][0]['urls'] as $url) {
634 if ($url['type'] == 'zot') {
636 $server["platform"] = 'Hubzilla';
637 $server["network"] = Protocol::DIASPORA;
645 * @brief Detect server type by using the nodeinfo data
647 * @param string $server_url address of the server
648 * @return array Server data
649 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
651 private static function fetchNodeinfo($server_url)
653 $curlResult = Network::curl($server_url."/.well-known/nodeinfo");
654 if (!$curlResult->isSuccess()) {
658 $nodeinfo = json_decode($curlResult->getBody(), true);
660 if (!is_array($nodeinfo) || !isset($nodeinfo['links'])) {
667 foreach ($nodeinfo['links'] as $link) {
668 if (!is_array($link) || empty($link['rel'])) {
669 Logger::log('Invalid nodeinfo format for ' . $server_url, Logger::DEBUG);
672 if ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
673 $nodeinfo1_url = $link['href'];
674 } elseif ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/2.0') {
675 $nodeinfo2_url = $link['href'];
679 if ($nodeinfo1_url . $nodeinfo2_url == '') {
685 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
686 if (!empty($nodeinfo2_url) && (parse_url($server_url, PHP_URL_HOST) == parse_url($nodeinfo2_url, PHP_URL_HOST))) {
687 $server = self::parseNodeinfo2($nodeinfo2_url);
690 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
691 if (empty($server) && !empty($nodeinfo1_url) && (parse_url($server_url, PHP_URL_HOST) == parse_url($nodeinfo1_url, PHP_URL_HOST))) {
692 $server = self::parseNodeinfo1($nodeinfo1_url);
699 * @brief Parses Nodeinfo 1
701 * @param string $nodeinfo_url address of the nodeinfo path
702 * @return array Server data
703 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
705 private static function parseNodeinfo1($nodeinfo_url)
707 $curlResult = Network::curl($nodeinfo_url);
709 if (!$curlResult->isSuccess()) {
713 $nodeinfo = json_decode($curlResult->getBody(), true);
715 if (!is_array($nodeinfo)) {
721 $server['register_policy'] = Register::CLOSED;
723 if (is_bool($nodeinfo['openRegistrations']) && $nodeinfo['openRegistrations']) {
724 $server['register_policy'] = Register::OPEN;
727 if (is_array($nodeinfo['software'])) {
728 if (isset($nodeinfo['software']['name'])) {
729 $server['platform'] = $nodeinfo['software']['name'];
732 if (isset($nodeinfo['software']['version'])) {
733 $server['version'] = $nodeinfo['software']['version'];
734 // Version numbers on Nodeinfo are presented with additional info, e.g.:
735 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
736 $server['version'] = preg_replace("=(.+)-(.{4,})=ism", "$1", $server['version']);
740 if (isset($nodeinfo['metadata']['nodeName'])) {
741 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
744 if (!empty($nodeinfo['usage']['users']['total'])) {
745 $server['registered-users'] = $nodeinfo['usage']['users']['total'];
752 if (is_array($nodeinfo['protocols']['inbound'])) {
753 foreach ($nodeinfo['protocols']['inbound'] as $inbound) {
754 if ($inbound == 'diaspora') {
757 if ($inbound == 'friendica') {
760 if ($inbound == 'gnusocial') {
767 $server['network'] = Protocol::OSTATUS;
770 $server['network'] = Protocol::DIASPORA;
773 $server['network'] = Protocol::DFRN;
784 * @brief Parses Nodeinfo 2
786 * @param string $nodeinfo_url address of the nodeinfo path
787 * @return array Server data
788 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
790 private static function parseNodeinfo2($nodeinfo_url)
792 $curlResult = Network::curl($nodeinfo_url);
793 if (!$curlResult->isSuccess()) {
797 $nodeinfo = json_decode($curlResult->getBody(), true);
799 if (!is_array($nodeinfo)) {
805 $server['register_policy'] = Register::CLOSED;
807 if (is_bool($nodeinfo['openRegistrations']) && $nodeinfo['openRegistrations']) {
808 $server['register_policy'] = Register::OPEN;
811 if (is_array($nodeinfo['software'])) {
812 if (isset($nodeinfo['software']['name'])) {
813 $server['platform'] = $nodeinfo['software']['name'];
816 if (isset($nodeinfo['software']['version'])) {
817 $server['version'] = $nodeinfo['software']['version'];
818 // Version numbers on Nodeinfo are presented with additional info, e.g.:
819 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
820 $server['version'] = preg_replace("=(.+)-(.{4,})=ism", "$1", $server['version']);
824 if (isset($nodeinfo['metadata']['nodeName'])) {
825 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
828 if (!empty($nodeinfo['usage']['users']['total'])) {
829 $server['registered-users'] = $nodeinfo['usage']['users']['total'];
836 if (!empty($nodeinfo['protocols'])) {
837 foreach ($nodeinfo['protocols'] as $protocol) {
838 if ($protocol == 'diaspora') {
840 } elseif ($protocol == 'friendica') {
842 } elseif ($protocol == 'gnusocial') {
849 $server['network'] = Protocol::OSTATUS;
850 } elseif ($diaspora) {
851 $server['network'] = Protocol::DIASPORA;
852 } elseif ($friendica) {
853 $server['network'] = Protocol::DFRN;
856 if (empty($server)) {
864 * @brief Detect server type (Hubzilla or Friendica) via the front page body
866 * @param string $body Front page of the server
867 * @return array Server data
869 private static function detectServerType($body)
873 $doc = new DOMDocument();
874 /// @TODO Acoid supressing error
875 @$doc->loadHTML($body);
876 $xpath = new DOMXPath($doc);
878 $list = $xpath->query("//meta[@name]");
880 foreach ($list as $node) {
882 if ($node->attributes->length) {
883 foreach ($node->attributes as $attribute) {
884 $attr[$attribute->name] = $attribute->value;
887 if ($attr['name'] == 'generator') {
888 $version_part = explode(" ", $attr['content']);
889 if (count($version_part) == 2) {
890 if (in_array($version_part[0], ["Friendika", "Friendica"])) {
892 $server["platform"] = $version_part[0];
893 $server["version"] = $version_part[1];
894 $server["network"] = Protocol::DFRN;
901 $list = $xpath->query("//meta[@property]");
903 foreach ($list as $node) {
905 if ($node->attributes->length) {
906 foreach ($node->attributes as $attribute) {
907 $attr[$attribute->name] = $attribute->value;
910 if ($attr['property'] == 'generator' && in_array($attr['content'], ["hubzilla", "BlaBlaNet"])) {
912 $server["platform"] = $attr['content'];
913 $server["version"] = "";
914 $server["network"] = Protocol::DIASPORA;
923 $server["site_name"] = XML::getFirstNodeValue($xpath, '//head/title/text()');
928 public static function checkServer($server_url, $network = "", $force = false)
930 // Unify the server address
931 $server_url = trim($server_url, "/");
932 $server_url = str_replace("/index.php", "", $server_url);
934 if ($server_url == "") {
938 $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($server_url)]);
939 if (DBA::isResult($gserver)) {
940 if ($gserver["created"] <= DBA::NULL_DATETIME) {
941 $fields = ['created' => DateTimeFormat::utcNow()];
942 $condition = ['nurl' => Strings::normaliseLink($server_url)];
943 DBA::update('gserver', $fields, $condition);
945 $poco = $gserver["poco"];
946 $noscrape = $gserver["noscrape"];
948 if ($network == "") {
949 $network = $gserver["network"];
952 $last_contact = $gserver["last_contact"];
953 $last_failure = $gserver["last_failure"];
954 $version = $gserver["version"];
955 $platform = $gserver["platform"];
956 $site_name = $gserver["site_name"];
957 $info = $gserver["info"];
958 $register_policy = $gserver["register_policy"];
959 $registered_users = $gserver["registered-users"];
961 // See discussion under https://forum.friendi.ca/display/0b6b25a8135aabc37a5a0f5684081633
962 // It can happen that a zero date is in the database, but storing it again is forbidden.
963 if ($last_contact < DBA::NULL_DATETIME) {
964 $last_contact = DBA::NULL_DATETIME;
967 if ($last_failure < DBA::NULL_DATETIME) {
968 $last_failure = DBA::NULL_DATETIME;
971 if (!$force && !self::updateNeeded($gserver["created"], "", $last_failure, $last_contact)) {
972 Logger::log("Use cached data for server ".$server_url, Logger::DEBUG);
973 return ($last_contact >= $last_failure);
982 $register_policy = -1;
983 $registered_users = 0;
985 $last_contact = DBA::NULL_DATETIME;
986 $last_failure = DBA::NULL_DATETIME;
988 Logger::log("Server ".$server_url." is outdated or unknown. Start discovery. Force: ".$force." Created: ".$gserver["created"]." Failure: ".$last_failure." Contact: ".$last_contact, Logger::DEBUG);
991 $possible_failure = false;
992 $orig_last_failure = $last_failure;
993 $orig_last_contact = $last_contact;
995 // Mastodon uses the "@" for user profiles.
996 // But this can be misunderstood.
997 if (parse_url($server_url, PHP_URL_USER) != '') {
998 DBA::update('gserver', ['last_failure' => DateTimeFormat::utcNow()], ['nurl' => Strings::normaliseLink($server_url)]);
1002 // Check if the page is accessible via SSL.
1003 $orig_server_url = $server_url;
1004 $server_url = str_replace("http://", "https://", $server_url);
1006 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
1007 $curlResult = Network::curl($server_url."/.well-known/host-meta", false, $redirects, ['timeout' => 20]);
1009 // Quit if there is a timeout.
1010 // But we want to make sure to only quit if we are mostly sure that this server url fits.
1011 if (DBA::isResult($gserver) && ($orig_server_url == $server_url) &&
1012 ($curlResult->isTimeout())) {
1013 Logger::log("Connection to server ".$server_url." timed out.", Logger::DEBUG);
1014 DBA::update('gserver', ['last_failure' => DateTimeFormat::utcNow()], ['nurl' => Strings::normaliseLink($server_url)]);
1018 // Maybe the page is unencrypted only?
1019 $xmlobj = @simplexml_load_string($curlResult->getBody(), 'SimpleXMLElement', 0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
1020 if (!$curlResult->isSuccess() || ($curlResult->getBody() == "") || empty($xmlobj) || !is_object($xmlobj)) {
1021 $server_url = str_replace("https://", "http://", $server_url);
1023 // We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
1024 $curlResult = Network::curl($server_url."/.well-known/host-meta", false, $redirects, ['timeout' => 20]);
1026 // Quit if there is a timeout
1027 if ($curlResult->isTimeout()) {
1028 Logger::log("Connection to server " . $server_url . " timed out.", Logger::DEBUG);
1029 DBA::update('gserver', ['last_failure' => DateTimeFormat::utcNow()], ['nurl' => Strings::normaliseLink($server_url)]);
1033 $xmlobj = @simplexml_load_string($curlResult->getBody(), 'SimpleXMLElement', 0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
1036 if (!$curlResult->isSuccess() || ($curlResult->getBody() == "") || empty($xmlobj) || !is_object($xmlobj)) {
1037 // Workaround for bad configured servers (known nginx problem)
1038 if (!empty($curlResult->getInfo()) && !in_array($curlResult->getInfo()["http_code"], ["403", "404"])) {
1042 $possible_failure = true;
1045 // If the server has no possible failure we reset the cached data
1046 if (!$possible_failure) {
1051 $register_policy = -1;
1055 // This will be too low, but better than no value at all.
1056 $registered_users = DBA::count('gcontact', ['server_url' => Strings::normaliseLink($server_url)]);
1061 $curlResult = Network::curl($server_url."/poco");
1063 if ($curlResult->isSuccess()) {
1064 $data = json_decode($curlResult->getBody(), true);
1066 if (isset($data['totalResults'])) {
1067 $registered_users = $data['totalResults'];
1068 $poco = $server_url . "/poco";
1069 $server = self::detectPocoData($data);
1071 if (!empty($server)) {
1072 $platform = $server['platform'];
1073 $network = $server['network'];
1080 * There are servers out there who don't return 404 on a failure
1081 * We have to be sure that don't misunderstand this
1083 if (is_null($data)) {
1092 // Test for Diaspora, Hubzilla, Mastodon or older Friendica servers
1093 $curlResult = Network::curl($server_url);
1095 if (!$curlResult->isSuccess() || ($curlResult->getBody() == "")) {
1098 $server = self::detectServerType($curlResult->getBody());
1100 if (!empty($server)) {
1101 $platform = $server['platform'];
1102 $network = $server['network'];
1103 $version = $server['version'];
1104 $site_name = $server['site_name'];
1107 $lines = explode("\n", $curlResult->getHeader());
1109 if (count($lines)) {
1110 foreach ($lines as $line) {
1111 $line = trim($line);
1113 if (stristr($line, 'X-Diaspora-Version:')) {
1114 $platform = "Diaspora";
1115 $version = trim(str_replace("X-Diaspora-Version:", "", $line));
1116 $version = trim(str_replace("x-diaspora-version:", "", $version));
1117 $network = Protocol::DIASPORA;
1118 $versionparts = explode("-", $version);
1119 $version = $versionparts[0];
1122 if (stristr($line, 'Server: Mastodon')) {
1123 $platform = "Mastodon";
1124 $network = Protocol::OSTATUS;
1131 if (!$failure && ($poco == "")) {
1132 // Test for Statusnet
1133 // Will also return data for Friendica and GNU Social - but it will be overwritten later
1134 // The "not implemented" is a special treatment for really, really old Friendica versions
1135 $curlResult = Network::curl($server_url."/api/statusnet/version.json");
1137 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1138 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1139 $platform = "StatusNet";
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 GNU Social
1147 $curlResult = Network::curl($server_url."/api/gnusocial/version.json");
1149 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1150 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1151 $platform = "GNU Social";
1152 // Remove junk that some GNU Social servers return
1153 $version = str_replace(chr(239) . chr(187) . chr(191), "", $curlResult->getBody());
1154 $version = trim($version, '"');
1155 $network = Protocol::OSTATUS;
1158 // Test for Mastodon
1159 $orig_version = $version;
1160 $curlResult = Network::curl($server_url . "/api/v1/instance");
1162 if ($curlResult->isSuccess() && ($curlResult->getBody() != '')) {
1163 $data = json_decode($curlResult->getBody(), true);
1165 if (isset($data['version'])) {
1166 $platform = "Mastodon";
1167 $version = defaults($data, 'version', '');
1168 $site_name = defaults($data, 'title', '');
1169 $info = defaults($data, 'description', '');
1170 $network = Protocol::OSTATUS;
1173 if (!empty($data['stats']['user_count'])) {
1174 $registered_users = $data['stats']['user_count'];
1178 if (strstr($orig_version . $version, 'Pleroma')) {
1179 $platform = 'Pleroma';
1180 $version = trim(str_replace('Pleroma', '', $version));
1185 // Test for Hubzilla and Red
1186 $curlResult = Network::curl($server_url . "/siteinfo.json");
1188 if ($curlResult->isSuccess()) {
1189 $data = json_decode($curlResult->getBody(), true);
1191 if (isset($data['url'])) {
1192 $platform = $data['platform'];
1193 $version = $data['version'];
1194 $network = Protocol::DIASPORA;
1197 if (!empty($data['site_name'])) {
1198 $site_name = $data['site_name'];
1201 if (!empty($data['channels_total'])) {
1202 $registered_users = $data['channels_total'];
1205 if (!empty($data['register_policy'])) {
1206 switch ($data['register_policy']) {
1207 case "REGISTER_OPEN":
1208 $register_policy = Register::OPEN;
1211 case "REGISTER_APPROVE":
1212 $register_policy = Register::APPROVE;
1215 case "REGISTER_CLOSED":
1217 $register_policy = Register::CLOSED;
1222 // Test for Hubzilla, Redmatrix or Friendica
1223 $curlResult = Network::curl($server_url."/api/statusnet/config.json");
1225 if ($curlResult->isSuccess()) {
1226 $data = json_decode($curlResult->getBody(), true);
1228 if (isset($data['site']['server'])) {
1229 if (isset($data['site']['platform'])) {
1230 $platform = $data['site']['platform']['PLATFORM_NAME'];
1231 $version = $data['site']['platform']['STD_VERSION'];
1232 $network = Protocol::DIASPORA;
1235 if (isset($data['site']['BlaBlaNet'])) {
1236 $platform = $data['site']['BlaBlaNet']['PLATFORM_NAME'];
1237 $version = $data['site']['BlaBlaNet']['STD_VERSION'];
1238 $network = Protocol::DIASPORA;
1241 if (isset($data['site']['hubzilla'])) {
1242 $platform = $data['site']['hubzilla']['PLATFORM_NAME'];
1243 $version = $data['site']['hubzilla']['RED_VERSION'];
1244 $network = Protocol::DIASPORA;
1247 if (isset($data['site']['redmatrix'])) {
1248 if (isset($data['site']['redmatrix']['PLATFORM_NAME'])) {
1249 $platform = $data['site']['redmatrix']['PLATFORM_NAME'];
1250 } elseif (isset($data['site']['redmatrix']['RED_PLATFORM'])) {
1251 $platform = $data['site']['redmatrix']['RED_PLATFORM'];
1254 $version = $data['site']['redmatrix']['RED_VERSION'];
1255 $network = Protocol::DIASPORA;
1258 if (isset($data['site']['friendica'])) {
1259 $platform = $data['site']['friendica']['FRIENDICA_PLATFORM'];
1260 $version = $data['site']['friendica']['FRIENDICA_VERSION'];
1261 $network = Protocol::DFRN;
1264 $site_name = $data['site']['name'];
1267 $inviteonly = false;
1270 if (!empty($data['site']['closed'])) {
1271 $closed = self::toBoolean($data['site']['closed']);
1274 if (!empty($data['site']['private'])) {
1275 $private = self::toBoolean($data['site']['private']);
1278 if (!empty($data['site']['inviteonly'])) {
1279 $inviteonly = self::toBoolean($data['site']['inviteonly']);
1282 if (!$closed && !$private and $inviteonly) {
1283 $register_policy = Register::APPROVE;
1284 } elseif (!$closed && !$private) {
1285 $register_policy = Register::OPEN;
1287 $register_policy = Register::CLOSED;
1294 // Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
1296 $curlResult = Network::curl($server_url . "/statistics.json");
1298 if ($curlResult->isSuccess()) {
1299 $data = json_decode($curlResult->getBody(), true);
1301 if (isset($data['version'])) {
1302 $version = $data['version'];
1303 // Version numbers on statistics.json are presented with additional info, e.g.:
1304 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
1305 $version = preg_replace("=(.+)-(.{4,})=ism", "$1", $version);
1308 if (!empty($data['name'])) {
1309 $site_name = $data['name'];
1312 if (!empty($data['network'])) {
1313 $platform = $data['network'];
1316 if ($platform == "Diaspora") {
1317 $network = Protocol::DIASPORA;
1320 if (!empty($data['registrations_open']) && $data['registrations_open']) {
1321 $register_policy = Register::OPEN;
1323 $register_policy = Register::CLOSED;
1328 // Query nodeinfo. Working for (at least) Diaspora and Friendica.
1330 $server = self::fetchNodeinfo($server_url);
1332 if (!empty($server)) {
1333 $register_policy = $server['register_policy'];
1335 if (isset($server['platform'])) {
1336 $platform = $server['platform'];
1339 if (isset($server['network'])) {
1340 $network = $server['network'];
1343 if (isset($server['version'])) {
1344 $version = $server['version'];
1347 if (isset($server['site_name'])) {
1348 $site_name = $server['site_name'];
1351 if (isset($server['registered-users'])) {
1352 $registered_users = $server['registered-users'];
1357 // Check for noscrape
1358 // Friendica servers could be detected as OStatus servers
1359 if (!$failure && in_array($network, [Protocol::DFRN, Protocol::OSTATUS])) {
1360 $curlResult = Network::curl($server_url . "/friendica/json");
1362 if (!$curlResult->isSuccess()) {
1363 $curlResult = Network::curl($server_url . "/friendika/json");
1366 if ($curlResult->isSuccess()) {
1367 $data = json_decode($curlResult->getBody(), true);
1369 if (isset($data['version'])) {
1370 $network = Protocol::DFRN;
1372 if (!empty($data['no_scrape_url'])) {
1373 $noscrape = $data['no_scrape_url'];
1376 $version = $data['version'];
1378 if (!empty($data['site_name'])) {
1379 $site_name = $data['site_name'];
1382 $info = defaults($data, 'info', '');
1384 $register_policy = defaults($data, 'register_policy', 'REGISTER_CLOSED');
1385 switch ($register_policy) {
1386 case 'REGISTER_OPEN':
1387 $register_policy = Register::OPEN;
1390 case 'REGISTER_APPROVE':
1391 $register_policy = Register::APPROVE;
1395 Logger::log("Register policy '$register_policy' from $server_url is invalid.");
1396 // Defaulting to closed
1398 case 'REGISTER_CLOSED':
1399 case 'REGISTER_INVITATION':
1400 $register_policy = Register::CLOSED;
1404 $platform = defaults($data, 'platform', '');
1409 // Every server has got at least an admin account
1410 if (!$failure && ($registered_users == 0)) {
1411 $registered_users = 1;
1414 if ($possible_failure && !$failure) {
1419 $last_contact = $orig_last_contact;
1420 $last_failure = DateTimeFormat::utcNow();
1422 $last_contact = DateTimeFormat::utcNow();
1423 $last_failure = $orig_last_failure;
1426 if (($last_contact <= $last_failure) && !$failure) {
1427 Logger::log("Server ".$server_url." seems to be alive, but last contact wasn't set - could be a bug", Logger::DEBUG);
1428 } elseif (($last_contact >= $last_failure) && $failure) {
1429 Logger::log("Server ".$server_url." seems to be dead, but last failure wasn't set - could be a bug", Logger::DEBUG);
1432 // Check again if the server exists
1433 $found = DBA::exists('gserver', ['nurl' => Strings::normaliseLink($server_url)]);
1435 $version = strip_tags($version);
1436 $site_name = strip_tags($site_name);
1437 $info = strip_tags($info);
1438 $platform = strip_tags($platform);
1440 $fields = ['url' => $server_url, 'version' => $version,
1441 'site_name' => $site_name, 'info' => $info, 'register_policy' => $register_policy,
1442 'poco' => $poco, 'noscrape' => $noscrape, 'network' => $network,
1443 'platform' => $platform, 'registered-users' => $registered_users,
1444 'last_contact' => $last_contact, 'last_failure' => $last_failure];
1447 DBA::update('gserver', $fields, ['nurl' => Strings::normaliseLink($server_url)]);
1448 } elseif (!$failure) {
1449 $fields['nurl'] = Strings::normaliseLink($server_url);
1450 $fields['created'] = DateTimeFormat::utcNow();
1451 DBA::insert('gserver', $fields);
1454 if (!$failure && in_array($fields['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
1455 self::discoverRelay($server_url);
1458 Logger::log("End discovery for server " . $server_url, Logger::DEBUG);
1464 * @brief Fetch relay data from a given server url
1466 * @param string $server_url address of the server
1467 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1469 private static function discoverRelay($server_url)
1471 Logger::log("Discover relay data for server " . $server_url, Logger::DEBUG);
1473 $curlResult = Network::curl($server_url . "/.well-known/x-social-relay");
1475 if (!$curlResult->isSuccess()) {
1479 $data = json_decode($curlResult->getBody(), true);
1481 if (!is_array($data)) {
1485 $gserver = DBA::selectFirst('gserver', ['id', 'relay-subscribe', 'relay-scope'], ['nurl' => Strings::normaliseLink($server_url)]);
1487 if (!DBA::isResult($gserver)) {
1491 if (($gserver['relay-subscribe'] != $data['subscribe']) || ($gserver['relay-scope'] != $data['scope'])) {
1492 $fields = ['relay-subscribe' => $data['subscribe'], 'relay-scope' => $data['scope']];
1493 DBA::update('gserver', $fields, ['id' => $gserver['id']]);
1496 DBA::delete('gserver-tag', ['gserver-id' => $gserver['id']]);
1498 if ($data['scope'] == 'tags') {
1501 foreach ($data['tags'] as $tag) {
1502 $tag = mb_strtolower($tag);
1503 if (strlen($tag) < 100) {
1508 foreach ($tags as $tag) {
1509 DBA::insert('gserver-tag', ['gserver-id' => $gserver['id'], 'tag' => $tag], true);
1513 // Create or update the relay contact
1515 if (isset($data['protocols'])) {
1516 if (isset($data['protocols']['diaspora'])) {
1517 $fields['network'] = Protocol::DIASPORA;
1519 if (isset($data['protocols']['diaspora']['receive'])) {
1520 $fields['batch'] = $data['protocols']['diaspora']['receive'];
1521 } elseif (is_string($data['protocols']['diaspora'])) {
1522 $fields['batch'] = $data['protocols']['diaspora'];
1526 if (isset($data['protocols']['dfrn'])) {
1527 $fields['network'] = Protocol::DFRN;
1529 if (isset($data['protocols']['dfrn']['receive'])) {
1530 $fields['batch'] = $data['protocols']['dfrn']['receive'];
1531 } elseif (is_string($data['protocols']['dfrn'])) {
1532 $fields['batch'] = $data['protocols']['dfrn'];
1536 Diaspora::setRelayContact($server_url, $fields);
1540 * @brief Returns a list of all known servers
1541 * @return array List of server urls
1544 public static function serverlist()
1547 "SELECT `url`, `site_name` AS `displayName`, `network`, `platform`, `version` FROM `gserver`
1548 WHERE `network` IN ('%s', '%s', '%s') AND `last_contact` > `last_failure`
1549 ORDER BY `last_contact`
1551 DBA::escape(Protocol::DFRN),
1552 DBA::escape(Protocol::DIASPORA),
1553 DBA::escape(Protocol::OSTATUS)
1556 if (!DBA::isResult($r)) {
1564 * @brief Fetch server list from remote servers and adds them when they are new.
1566 * @param string $poco URL to the POCO endpoint
1567 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1569 private static function fetchServerlist($poco)
1571 $curlResult = Network::curl($poco . "/@server");
1573 if (!$curlResult->isSuccess()) {
1577 $serverlist = json_decode($curlResult->getBody(), true);
1579 if (!is_array($serverlist)) {
1583 foreach ($serverlist as $server) {
1584 $server_url = str_replace("/index.php", "", $server['url']);
1586 $r = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", DBA::escape(Strings::normaliseLink($server_url)));
1588 if (!DBA::isResult($r)) {
1589 Logger::log("Call server check for server ".$server_url, Logger::DEBUG);
1590 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", $server_url);
1595 private static function discoverFederation()
1597 $last = Config::get('poco', 'last_federation_discovery');
1600 $next = $last + (24 * 60 * 60);
1602 if ($next > time()) {
1607 // Discover Friendica, Hubzilla and Diaspora servers
1608 $curlResult = Network::fetchUrl("http://the-federation.info/pods.json");
1610 if (!empty($curlResult)) {
1611 $servers = json_decode($curlResult, true);
1613 if (!empty($servers['pods'])) {
1614 foreach ($servers['pods'] as $server) {
1615 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", "https://" . $server['host']);
1620 // Disvover Mastodon servers
1621 if (!Config::get('system', 'ostatus_disabled')) {
1622 $accesstoken = Config::get('system', 'instances_social_key');
1624 if (!empty($accesstoken)) {
1625 $api = 'https://instances.social/api/1.0/instances/list?count=0';
1626 $header = ['Authorization: Bearer '.$accesstoken];
1627 $curlResult = Network::curl($api, false, $redirects, ['headers' => $header]);
1629 if ($curlResult->isSuccess()) {
1630 $servers = json_decode($curlResult->getBody(), true);
1632 foreach ($servers['instances'] as $server) {
1633 $url = (is_null($server['https_score']) ? 'http' : 'https') . '://' . $server['name'];
1634 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", $url);
1640 // Currently disabled, since the service isn't available anymore.
1641 // It is not removed since I hope that there will be a successor.
1642 // Discover GNU Social Servers.
1643 //if (!Config::get('system','ostatus_disabled')) {
1644 // $serverdata = "http://gstools.org/api/get_open_instances/";
1646 // $curlResult = Network::curl($serverdata);
1647 // if ($curlResult->isSuccess()) {
1648 // $servers = json_decode($result->getBody(), true);
1650 // foreach($servers['data'] as $server)
1651 // self::checkServer($server['instance_address']);
1655 Config::set('poco', 'last_federation_discovery', time());
1658 public static function discoverSingleServer($id)
1660 $server = DBA::selectFirst('gserver', ['poco', 'nurl', 'url', 'network'], ['id' => $id]);
1662 if (!DBA::isResult($server)) {
1666 // Discover new servers out there (Works from Friendica version 3.5.2)
1667 self::fetchServerlist($server["poco"]);
1669 // Fetch all users from the other server
1670 $url = $server["poco"] . "/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1672 Logger::info("Fetch all users from the server " . $server["url"]);
1674 $curlResult = Network::curl($url);
1676 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
1677 $data = json_decode($curlResult->getBody(), true);
1679 if (!empty($data)) {
1680 self::discoverServer($data, 2);
1683 if (Config::get('system', 'poco_discovery') >= self::USERS_GCONTACTS) {
1684 $timeframe = Config::get('system', 'poco_discovery_since');
1686 if ($timeframe == 0) {
1690 $updatedSince = date(DateTimeFormat::MYSQL, time() - $timeframe * 86400);
1692 // Fetch all global contacts from the other server (Not working with Redmatrix and Friendica versions before 3.3)
1693 $url = $server["poco"]."/@global?updatedSince=".$updatedSince."&fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
1697 $curlResult = Network::curl($url);
1699 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
1700 Logger::info("Fetch all global contacts from the server " . $server["nurl"]);
1701 $data = json_decode($curlResult->getBody(), true);
1703 if (!empty($data)) {
1704 $success = self::discoverServer($data);
1708 if (!$success && !empty($data) && Config::get('system', 'poco_discovery') >= self::USERS_GCONTACTS_FALLBACK) {
1709 Logger::info("Fetch contacts from users of the server " . $server["nurl"]);
1710 self::discoverServerUsers($data, $server);
1714 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1715 DBA::update('gserver', $fields, ['nurl' => $server["nurl"]]);
1719 // If the server hadn't replied correctly, then force a sanity check
1720 self::checkServer($server["url"], $server["network"], true);
1722 // If we couldn't reach the server, we will try it some time later
1723 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1724 DBA::update('gserver', $fields, ['nurl' => $server["nurl"]]);
1730 public static function discover($complete = false)
1732 // Update the server list
1733 self::discoverFederation();
1737 $requery_days = intval(Config::get('system', 'poco_requery_days'));
1739 if ($requery_days == 0) {
1743 $last_update = date('c', time() - (60 * 60 * 24 * $requery_days));
1745 $gservers = q("SELECT `id`, `url`, `nurl`, `network`
1747 WHERE `last_contact` >= `last_failure`
1749 AND `last_poco_query` < '%s'
1750 ORDER BY RAND()", DBA::escape($last_update)
1753 if (DBA::isResult($gservers)) {
1754 foreach ($gservers as $gserver) {
1755 if (!self::checkServer($gserver['url'], $gserver['network'])) {
1756 // The server is not reachable? Okay, then we will try it later
1757 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1758 DBA::update('gserver', $fields, ['nurl' => $gserver['nurl']]);
1762 Logger::log('Update directory from server ' . $gserver['url'] . ' with ID ' . $gserver['id'], Logger::DEBUG);
1763 Worker::add(PRIORITY_LOW, 'DiscoverPoCo', 'update_server_directory', (int) $gserver['id']);
1765 if (!$complete && ( --$no_of_queries == 0)) {
1772 private static function discoverServerUsers(array $data, array $server)
1774 if (!isset($data['entry'])) {
1778 foreach ($data['entry'] as $entry) {
1781 if (isset($entry['urls'])) {
1782 foreach ($entry['urls'] as $url) {
1783 if ($url['type'] == 'profile') {
1784 $profile_url = $url['value'];
1785 $path_array = explode('/', parse_url($profile_url, PHP_URL_PATH));
1786 $username = end($path_array);
1791 if ($username != '') {
1792 Logger::log('Fetch contacts for the user ' . $username . ' from the server ' . $server['nurl'], Logger::DEBUG);
1794 // Fetch all contacts from a given user from the other server
1795 $url = $server['poco'] . '/' . $username . '/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation';
1797 $curlResult = Network::curl($url);
1799 if ($curlResult->isSuccess()) {
1800 $data = json_decode($curlResult->getBody(), true);
1802 if (!empty($data)) {
1803 self::discoverServer($data, 3);
1810 private static function discoverServer(array $data, $default_generation = 0)
1812 if (empty($data['entry'])) {
1818 foreach ($data['entry'] as $entry) {
1820 $profile_photo = '';
1824 $updated = DBA::NULL_DATETIME;
1830 $generation = $default_generation;
1832 if (!empty($entry['displayName'])) {
1833 $name = $entry['displayName'];
1836 if (isset($entry['urls'])) {
1837 foreach ($entry['urls'] as $url) {
1838 if ($url['type'] == 'profile') {
1839 $profile_url = $url['value'];
1842 if ($url['type'] == 'webfinger') {
1843 $connect_url = str_replace('acct:' , '', $url['value']);
1849 if (isset($entry['photos'])) {
1850 foreach ($entry['photos'] as $photo) {
1851 if ($photo['type'] == 'profile') {
1852 $profile_photo = $photo['value'];
1858 if (isset($entry['updated'])) {
1859 $updated = date(DateTimeFormat::MYSQL, strtotime($entry['updated']));
1862 if (isset($entry['network'])) {
1863 $network = $entry['network'];
1866 if (isset($entry['currentLocation'])) {
1867 $location = $entry['currentLocation'];
1870 if (isset($entry['aboutMe'])) {
1871 $about = HTML::toBBCode($entry['aboutMe']);
1874 if (isset($entry['gender'])) {
1875 $gender = $entry['gender'];
1878 if (isset($entry['generation']) && ($entry['generation'] > 0)) {
1879 $generation = ++$entry['generation'];
1882 if (isset($entry['contactType']) && ($entry['contactType'] >= 0)) {
1883 $contact_type = $entry['contactType'];
1886 if (isset($entry['tags'])) {
1887 foreach ($entry['tags'] as $tag) {
1888 $keywords = implode(", ", $tag);
1892 if ($generation > 0) {
1895 Logger::log("Store profile ".$profile_url, Logger::DEBUG);
1897 $gcontact = ["url" => $profile_url,
1899 "network" => $network,
1900 "photo" => $profile_photo,
1902 "location" => $location,
1903 "gender" => $gender,
1904 "keywords" => $keywords,
1905 "connect" => $connect_url,
1906 "updated" => $updated,
1907 "contact-type" => $contact_type,
1908 "generation" => $generation];
1911 $gcontact = GContact::sanitize($gcontact);
1912 GContact::update($gcontact);
1913 } catch (Exception $e) {
1914 Logger::log($e->getMessage(), Logger::DEBUG);
1917 Logger::log("Done for profile ".$profile_url, Logger::DEBUG);